Public repository: timo / mitch

Reader

A migration stitcher (therefore mitch) for PostgreSQL, SQLite, MariaDB, and others

Populate migration files from stdin

public

Populate migration files from stdin
Changesete2ef4095244fe51e362ed47e303e245347e2af19
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents5057160a57ab
Children
Pushlog
by timo via ssh

modified src/mitch/cli/create.py +54 −2

@@ -1,4 +1,7 @@
1
+import re
2
+import sys
13
 from datetime import datetime, timezone
4
+from itertools import batched
25
 from pathlib import Path
36
 from typing import Annotated
47
 
@@ -6,7 +9,50 @@
69
 
710
 from ..project import Project
811
 
12
+SECTION_HEADER_PATTERN = re.compile(
13
+    r"^\s*--\s*(up|down)\.(?:sql)\s*(?:\r?\n|$)",
14
+    flags=re.IGNORECASE | re.MULTILINE,
15
+)
16
+
917
 app = typer.Typer(help="Add new migrations to the project.")
18
+
19
+
20
+def _create_new_file(path: Path, content: str | None = None) -> None:
21
+    """Create a file and optionally write content without allowing overwrite."""
22
+    if content is None:
23
+        path.touch(exist_ok=False)
24
+        return
25
+
26
+    with path.open("x", encoding="utf-8") as file:
27
+        file.write(content)
28
+
29
+
30
+def _parse_stdin_sections(stdin_text: str) -> tuple[str, str | None]:
31
+    """Parse optional SQL sections from stdin.
32
+
33
+    Supported section headers:
34
+    -- up.sql
35
+    -- down.sql
36
+    """
37
+    parts = SECTION_HEADER_PATTERN.split(stdin_text)
38
+
39
+    if len(parts) == 1:
40
+        # No section headers found, treat entire input as up script
41
+        return parts[0], None
42
+
43
+    if parts[0].strip() == "":
44
+        # If the first part is just whitespace, discard it.
45
+        # This is typically the case when the input starts with a section header.
46
+        parts = parts[1:]
47
+
48
+    up_script = ""
49
+    down_script = ""
50
+    for section, content in batched(parts, 2):
51
+        if section.lower() == "up":
52
+            up_script = content
53
+        elif section.lower() == "down":
54
+            down_script = content
55
+    return up_script, down_script
1056
 
1157
 
1258
 @app.command()
@@ -41,9 +87,15 @@
4187
 
4288
     Args:
4389
         migration_id: The ID of the new migration.
90
+
91
+    Stdin:
92
+        Optionally provide SQL via stdin. Use `-- up.sql` / `-- down.sql`
93
+        comment headers to split content between both scripts.
4494
     """
4595
 
4696
     migration_path = Path(root) / migration_id
97
+    stdin_sql = sys.stdin.read() if not sys.stdin.isatty() else ""
98
+    up_script_content, down_script_content = _parse_stdin_sections(stdin_sql)
4799
 
48100
     # Validate dependency IDs
49101
     project = Project.from_path(root)
@@ -55,12 +107,12 @@
55107
     # Create up script
56108
     up_script_path = migration_path.with_suffix(".up.sql")
57109
     up_script_path.parent.mkdir(parents=True, exist_ok=True)
58
-    up_script_path.touch(exist_ok=False)
110
+    _create_new_file(up_script_path, up_script_content)
59111
 
60112
     # Create down script
61113
     if not skip_downscript:
62114
         down_script_path = migration_path.with_suffix(".down.sql")
63
-        down_script_path.touch(exist_ok=False)
115
+        _create_new_file(down_script_path, down_script_content)
64116
 
65117
     # Create config file
66118
     if not skip_config:

modified tests/test_cli.py +43 −0

@@ -170,6 +170,49 @@
170170
     assert config["id"] == "001-init"
171171
     assert isinstance(config["created_at"], datetime)
172172
     assert config["created_at"].tzinfo is not None
173
+
174
+
175
+def test_create_populates_up_script_from_stdin(tmp_path):
176
+    _write_project_config(tmp_path, "create-stdin-up")
177
+    up_sql = "CREATE TABLE stdin_only (id int);\n"
178
+    result = runner.invoke(
179
+        app,
180
+        [
181
+            "create",
182
+            "001-init",
183
+            "--project",
184
+            str(tmp_path),
185
+        ],
186
+        input=up_sql,
187
+    )
188
+
189
+    assert result.exit_code == 0
190
+    assert (tmp_path / "001-init.up.sql").read_text(encoding="utf-8") == up_sql
191
+    assert (tmp_path / "001-init.down.sql").read_text(encoding="utf-8") == ""
192
+
193
+
194
+def test_create_populates_up_and_down_scripts_from_stdin_sections(tmp_path):
195
+    _write_project_config(tmp_path, "create-stdin-sections")
196
+    payload = (
197
+        "-- up.sql\n"
198
+        "CREATE TABLE stdin_split (id int);\n"
199
+        "-- down.sql\n"
200
+        "DROP TABLE stdin_split;\n"
201
+    )
202
+    result = runner.invoke(
203
+        app,
204
+        [
205
+            "create",
206
+            "001-init",
207
+            "--project",
208
+            str(tmp_path),
209
+        ],
210
+        input=payload,
211
+    )
212
+
213
+    assert result.exit_code == 0
214
+    assert (tmp_path / "001-init.up.sql").read_text(encoding="utf-8") == "CREATE TABLE stdin_split (id int);\n"
215
+    assert (tmp_path / "001-init.down.sql").read_text(encoding="utf-8") == "DROP TABLE stdin_split;\n"
173216
 
174217
 
175218
 def test_create_rejects_missing_dependencies(tmp_path):