pgmini-migrate 0.1.1__tar.gz → 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: pgmini-migrate
3
+ Version: 0.1.3
4
+ Summary: A minimal PostgreSQL migration tool for Python
5
+ Author-email: Nguyen Vu Duy Luan <nvdluan@gmail.com>
6
+ License: Copyright (c) 2025 Nguyen Vu Duy Luan
7
+ Project-URL: Homepage, https://github.com/NVDLuan/pgmini-migrate
8
+ Project-URL: Issues, https://github.com/NVDLuan/pgmini-migrate/issues
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: psycopg[binary]>=3.1.8
13
+ Requires-Dist: dotenv<0.10.0,>=0.9.9
14
+ Requires-Dist: click<9.0.0,>=8.2.1
15
+ Dynamic: license-file
16
+
17
+ # pgmini-migrate
18
+
19
+ `pgmini-migrate` is a **lightweight SQL migration tool** for PostgreSQL.
20
+ It allows you to easily **create migration files** and run **upgrades/downgrades** using simple CLI commands.
21
+
22
+ No ORM required — just pure SQL.
23
+
24
+ ---
25
+
26
+ ## ✨ Features
27
+ - Auto-generate migration files (`upgrade` + `downgrade`).
28
+ - Run **upgrade** or **downgrade** up to a specific version.
29
+ - Two connection options:
30
+ - via `DATABASE_URL`
31
+ - via `host`, `port`, `user`, `password`, `dbname`.
32
+ - Configurable migrations directory.
33
+ - Minimal, simple, and PostgreSQL-focused.
34
+
35
+ ---
36
+
37
+ ## 📦 Installation
38
+
39
+ ```bash
40
+ pip install pgmini-migrate
@@ -0,0 +1,24 @@
1
+ # pgmini-migrate
2
+
3
+ `pgmini-migrate` is a **lightweight SQL migration tool** for PostgreSQL.
4
+ It allows you to easily **create migration files** and run **upgrades/downgrades** using simple CLI commands.
5
+
6
+ No ORM required — just pure SQL.
7
+
8
+ ---
9
+
10
+ ## ✨ Features
11
+ - Auto-generate migration files (`upgrade` + `downgrade`).
12
+ - Run **upgrade** or **downgrade** up to a specific version.
13
+ - Two connection options:
14
+ - via `DATABASE_URL`
15
+ - via `host`, `port`, `user`, `password`, `dbname`.
16
+ - Configurable migrations directory.
17
+ - Minimal, simple, and PostgreSQL-focused.
18
+
19
+ ---
20
+
21
+ ## 📦 Installation
22
+
23
+ ```bash
24
+ pip install pgmini-migrate
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,349 @@
1
+ import os
2
+ import sys
3
+ import psycopg
4
+ from contextlib import contextmanager
5
+ from datetime import datetime
6
+ import argparse
7
+
8
+ # Default layout
9
+ DEFAULT_MIGRATIONS_DIR = "migrations"
10
+ UPGRADE_SUBDIR = "upgrade"
11
+ DOWNGRADE_SUBDIR = "downgrade"
12
+ MIGRATION_TABLE = "schema_migrations"
13
+
14
+
15
+ def load_env_file(env_path=".env"):
16
+ """Load simple env file KEY=VALUE into os.environ (if not already set)."""
17
+ if not os.path.exists(env_path):
18
+ return
19
+ with open(env_path, "r") as f:
20
+ for ln in f:
21
+ ln = ln.strip()
22
+ if not ln or ln.startswith("#"):
23
+ continue
24
+ if "=" not in ln:
25
+ continue
26
+ k, v = ln.split("=", 1)
27
+ k = k.strip()
28
+ v = v.strip().strip('"').strip("'")
29
+ # do not overwrite existing env set by host
30
+ if k not in os.environ:
31
+ os.environ[k] = v
32
+ print(f"Loaded env {k} from {env_path}: {v}")
33
+
34
+
35
+ def build_conninfo_from_args(args):
36
+ """Return a psycopg-compatible connection string or dict kwargs"""
37
+ if args.database_url:
38
+ return args.database_url
39
+ # build a dict for psycopg.connect(...)
40
+ kw = {}
41
+ if args.db_host:
42
+ kw["host"] = args.db_host
43
+ if args.db_port:
44
+ kw["port"] = args.db_port
45
+ if args.db_name:
46
+ kw["dbname"] = args.db_name
47
+ if args.db_user:
48
+ kw["user"] = args.db_user
49
+ if args.db_password:
50
+ kw["password"] = args.db_password
51
+ return kw
52
+
53
+
54
+ @contextmanager
55
+ def get_connection(conninfo):
56
+ """Context manager returning a connected psycopg connection (sync)."""
57
+ if isinstance(conninfo, str):
58
+ conn = psycopg.connect(conninfo)
59
+ else:
60
+ conn = psycopg.connect(**conninfo)
61
+ try:
62
+ yield conn
63
+ finally:
64
+ conn.close()
65
+
66
+
67
+ def ensure_migration_table(conn):
68
+ with conn.cursor() as cur:
69
+ cur.execute(
70
+ f"""
71
+ CREATE TABLE IF NOT EXISTS {MIGRATION_TABLE} (
72
+ version VARCHAR(255) PRIMARY KEY,
73
+ applied_at TIMESTAMP DEFAULT NOW()
74
+ )
75
+ """
76
+ )
77
+ conn.commit()
78
+
79
+
80
+ def get_applied_migrations(conn):
81
+ with conn.cursor() as cur:
82
+ cur.execute(f"SELECT version FROM {MIGRATION_TABLE} ORDER BY version")
83
+ rows = cur.fetchall()
84
+ return [row[0] for row in rows]
85
+
86
+
87
+ def apply_migration(conn, version, sql_path):
88
+ with open(sql_path, "r", encoding="utf-8") as f:
89
+ sql = f.read()
90
+ try:
91
+ with conn.cursor() as cur:
92
+ print(f"⬆️ Applying {version} -> {os.path.basename(sql_path)}")
93
+ cur.execute(sql)
94
+ cur.execute(
95
+ f"INSERT INTO {MIGRATION_TABLE} (version) VALUES (%s)", (version,)
96
+ )
97
+ conn.commit()
98
+ print(f"✅ {version} applied.")
99
+ except Exception as e:
100
+ conn.rollback()
101
+ print(f"❌ Failed to apply {version}: {e}")
102
+ raise
103
+
104
+
105
+ def rollback_migration_from_file(conn, version, sql_path):
106
+ with open(sql_path, "r", encoding="utf-8") as f:
107
+ sql = f.read()
108
+ try:
109
+ with conn.cursor() as cur:
110
+ print(f"⬇️ Rolling back {version} -> {os.path.basename(sql_path)}")
111
+ cur.execute(sql)
112
+ cur.execute(f"DELETE FROM {MIGRATION_TABLE} WHERE version = %s", (version,))
113
+ conn.commit()
114
+ print(f"✅ {version} rolled back.")
115
+ except Exception as e:
116
+ conn.rollback()
117
+ print(f"❌ Failed to rollback {version}: {e}")
118
+ raise
119
+
120
+
121
+ def find_migration_files(migrations_root):
122
+ """Return sorted list of upgrade filenames in migrations/upgrade"""
123
+ upgrade_dir = os.path.join(migrations_root, UPGRADE_SUBDIR)
124
+ if not os.path.isdir(upgrade_dir):
125
+ return []
126
+ files = [f for f in os.listdir(upgrade_dir) if f.endswith(".sql")]
127
+ files = sorted(files)
128
+ return files
129
+
130
+
131
+ def parse_version_from_filename(filename):
132
+ """Expect filenames like 001.description.upgrade.sql or 001.description.sql"""
133
+ base = os.path.basename(filename)
134
+ parts = base.split(".", 1)
135
+ return parts[0]
136
+
137
+
138
+ def full_upgrade_path(migrations_root, filename):
139
+ return os.path.join(migrations_root, UPGRADE_SUBDIR, filename)
140
+
141
+
142
+ def full_downgrade_path(migrations_root, filename):
143
+ return os.path.join(migrations_root, DOWNGRADE_SUBDIR, filename)
144
+
145
+
146
+ def get_next_version_str(migrations_root):
147
+ upgrade_dir = os.path.join(migrations_root, UPGRADE_SUBDIR)
148
+ os.makedirs(upgrade_dir, exist_ok=True)
149
+ files = [f for f in os.listdir(upgrade_dir) if f[0:3].isdigit()]
150
+ versions = [int(f[0:3]) for f in files if f[0:3].isdigit()]
151
+ next_v = max(versions) + 1 if versions else 1
152
+ return f"{next_v:03d}"
153
+
154
+
155
+ def create_migration(migrations_root, description):
156
+ desc = description.strip()
157
+ # sanitize description
158
+ desc_clean=desc.lower().replace(" ", "_").replace("-", "_")
159
+ version = get_next_version_str(migrations_root)
160
+ upgrade_name = f"{version}.{desc_clean}.upgrade.sql"
161
+ downgrade_name = f"{version}.{desc_clean}.downgrade.sql"
162
+
163
+ upgrade_path = full_upgrade_path(migrations_root, upgrade_name)
164
+ downgrade_path = full_downgrade_path(migrations_root, downgrade_name)
165
+
166
+ # ensure dirs
167
+ os.makedirs(os.path.dirname(upgrade_path), exist_ok=True)
168
+ os.makedirs(os.path.dirname(downgrade_path), exist_ok=True)
169
+
170
+ ts = datetime.utcnow().isoformat() + "Z"
171
+ with open(upgrade_path, "w", encoding="utf-8") as f:
172
+ f.write(f"-- +upgrade {version} {desc}\n-- created at {ts}\n\n")
173
+ with open(downgrade_path, "w", encoding="utf-8") as f:
174
+ f.write(f"-- +downgrade {version} {desc}\n-- created at {ts}\n\n")
175
+
176
+ print(f"Created:\n {upgrade_path}\n {downgrade_path}")
177
+ return upgrade_path, downgrade_path
178
+
179
+
180
+ def cmd_upgrade(args):
181
+ conninfo = build_conninfo_from_args(args)
182
+ migrations_root = args.migrations
183
+ files = find_migration_files(migrations_root)
184
+ if not files:
185
+ print("No migration files found.")
186
+ return
187
+
188
+ with get_connection(conninfo) as conn:
189
+ ensure_migration_table(conn)
190
+ applied = set(get_applied_migrations(conn))
191
+ for fname in files:
192
+ version = parse_version_from_filename(fname)
193
+ if version in applied:
194
+ print(f"Skipping {fname} (already applied).")
195
+ continue
196
+ sql_path = full_upgrade_path(migrations_root, fname)
197
+ apply_migration(conn, version, sql_path)
198
+
199
+
200
+ def cmd_history(args):
201
+ conninfo = build_conninfo_from_args(args)
202
+ with get_connection(conninfo) as conn:
203
+ ensure_migration_table(conn)
204
+ applied = get_applied_migrations(conn)
205
+ print("Applied migrations (ordered):")
206
+ for v in applied:
207
+ print(" -", v)
208
+
209
+
210
+ def cmd_show(args):
211
+ conninfo = build_conninfo_from_args(args)
212
+ with get_connection(conninfo) as conn:
213
+ ensure_migration_table(conn)
214
+ applied = get_applied_migrations(conn)
215
+ if not applied:
216
+ print("Database has no applied migrations (base).")
217
+ else:
218
+ print("Current version:", applied[-1])
219
+
220
+
221
+ def cmd_downgrade(args):
222
+ conninfo = build_conninfo_from_args(args)
223
+ migrations_root = args.migrations
224
+
225
+ with get_connection(conninfo) as conn:
226
+ ensure_migration_table(conn)
227
+ applied = get_applied_migrations(conn)
228
+
229
+ if not applied:
230
+ print("No migrations applied.")
231
+ return
232
+
233
+ target = args.target # None => step=1, "base" => all, specific version => to that
234
+ if target is None:
235
+ # default: rollback 1 step
236
+ target_index = len(applied) - 2
237
+ elif target == "base":
238
+ target_index = -1
239
+ else:
240
+ if target not in applied:
241
+ print(f"Target {target} not found in applied migrations.")
242
+ return
243
+ target_index = applied.index(target)
244
+
245
+ to_rollback = applied[target_index + 1 :]
246
+ if not to_rollback:
247
+ print("Nothing to rollback.")
248
+ return
249
+
250
+ # rollback in reverse order
251
+ for version in reversed(to_rollback):
252
+ # find corresponding file in downgrade dir
253
+ # find filename that starts with version in upgrade dir to get remainder name
254
+ upgrade_dir = os.path.join(migrations_root, UPGRADE_SUBDIR)
255
+ candidates = [f for f in os.listdir(upgrade_dir) if f.startswith(version)]
256
+ if not candidates:
257
+ print(f"⚠️ No upgrade file found for version {version} (can't map to downgrade).")
258
+ continue
259
+ # infer name: replace 'upgrade' -> 'downgrade'
260
+ up_fname = candidates[0]
261
+ down_fname = up_fname.replace(".upgrade.", ".downgrade.")
262
+ down_path = full_downgrade_path(migrations_root, down_fname)
263
+ if not os.path.exists(down_path):
264
+ print(f"⚠️ No rollback file for {version} -> expected {down_path}")
265
+ continue
266
+ rollback_migration_from_file(conn, version, down_path)
267
+
268
+
269
+ def build_arg_parser():
270
+ p = argparse.ArgumentParser(prog="pgmigrate", description="Simple PostgreSQL migration tool")
271
+
272
+ # NOTE: lấy default từ os.getenv() *tại thời điểm gọi*, không từ hằng module-level
273
+ migrations_default = os.getenv("MIGRATIONS_DIR", "migrations")
274
+
275
+ p.add_argument("--env-file", default=".env", help="Path to .env file (default: .env)")
276
+ p.add_argument(
277
+ "--migrations",
278
+ default=migrations_default,
279
+ help=f"Root migrations dir (default: {migrations_default})",
280
+ )
281
+
282
+ # DB connection options (mutually override database_url)
283
+ p.add_argument("--database-url", help="Full DATABASE_URL (postgresql://...)", default=None)
284
+ p.add_argument("--db-host", help="DB host", default=os.getenv("POSTGRES_HOST"))
285
+ p.add_argument("--db-port", help="DB port", default=os.getenv("POSTGRES_PORT"))
286
+ p.add_argument("--db-name", help="DB name", default=os.getenv("POSTGRES_DB"))
287
+ p.add_argument("--db-user", help="DB user", default=os.getenv("POSTGRES_USER"))
288
+ p.add_argument("--db-password", help="DB password", default=os.getenv("POSTGRES_PASSWORD"))
289
+
290
+ sub = p.add_subparsers(dest="cmd", required=True)
291
+
292
+ sub.add_parser("upgrade", help="Apply all pending migrations")
293
+
294
+ down_p = sub.add_parser("downgrade", help="Rollback migrations to target version (or 1 step if no target)")
295
+ down_p.add_argument("target", nargs="?", help="target version (e.g. 002) or 'base'")
296
+
297
+ sub.add_parser("history", help="Show applied migrations (history)")
298
+
299
+ sub.add_parser("show", help="Show current applied version")
300
+
301
+ create_p = sub.add_parser("create", help="Create new migration skeleton")
302
+ create_p.add_argument("description", nargs="+", help="Migration description (quoted)")
303
+
304
+ return p
305
+
306
+
307
+ def main(argv=None):
308
+ argv = argv if argv is not None else sys.argv[1:]
309
+
310
+ # -------------------------
311
+ # 1) pre-parse only --env-file
312
+ # -------------------------
313
+ pre_parser = argparse.ArgumentParser(add_help=False)
314
+ pre_parser.add_argument("--env-file", default=".env")
315
+ pre_args, _unknown = pre_parser.parse_known_args(argv)
316
+
317
+ # 2) load env file BEFORE building main parser so os.getenv picks values
318
+ if pre_args.env_file:
319
+ load_env_file(pre_args.env_file)
320
+
321
+ # 3) build the full parser (now os.getenv reflects .env content)
322
+ parser = build_arg_parser()
323
+
324
+ # 4) parse full args (using original argv)
325
+ args = parser.parse_args(argv)
326
+
327
+ # Dispatch commands:
328
+ if args.cmd == "create":
329
+ desc = " ".join(args.description)
330
+ create_migration(args.migrations, desc)
331
+ return
332
+
333
+ # For commands that touch DB, ensure connection info exists
334
+ conninfo = build_conninfo_from_args(args)
335
+ if not conninfo:
336
+ print("No database connection info provided. Provide --database-url or host/name/user/password or set env vars.")
337
+ sys.exit(2)
338
+
339
+ if args.cmd == "upgrade":
340
+ cmd_upgrade(args)
341
+ elif args.cmd == "downgrade":
342
+ cmd_downgrade(args)
343
+ elif args.cmd == "history":
344
+ cmd_history(args)
345
+ elif args.cmd == "show":
346
+ cmd_show(args)
347
+ else:
348
+ print("Unknown command:", args.cmd)
349
+ sys.exit(2)
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: pgmini-migrate
3
+ Version: 0.1.3
4
+ Summary: A minimal PostgreSQL migration tool for Python
5
+ Author-email: Nguyen Vu Duy Luan <nvdluan@gmail.com>
6
+ License: Copyright (c) 2025 Nguyen Vu Duy Luan
7
+ Project-URL: Homepage, https://github.com/NVDLuan/pgmini-migrate
8
+ Project-URL: Issues, https://github.com/NVDLuan/pgmini-migrate/issues
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: psycopg[binary]>=3.1.8
13
+ Requires-Dist: dotenv<0.10.0,>=0.9.9
14
+ Requires-Dist: click<9.0.0,>=8.2.1
15
+ Dynamic: license-file
16
+
17
+ # pgmini-migrate
18
+
19
+ `pgmini-migrate` is a **lightweight SQL migration tool** for PostgreSQL.
20
+ It allows you to easily **create migration files** and run **upgrades/downgrades** using simple CLI commands.
21
+
22
+ No ORM required — just pure SQL.
23
+
24
+ ---
25
+
26
+ ## ✨ Features
27
+ - Auto-generate migration files (`upgrade` + `downgrade`).
28
+ - Run **upgrade** or **downgrade** up to a specific version.
29
+ - Two connection options:
30
+ - via `DATABASE_URL`
31
+ - via `host`, `port`, `user`, `password`, `dbname`.
32
+ - Configurable migrations directory.
33
+ - Minimal, simple, and PostgreSQL-focused.
34
+
35
+ ---
36
+
37
+ ## 📦 Installation
38
+
39
+ ```bash
40
+ pip install pgmini-migrate
@@ -3,9 +3,9 @@ README.md
3
3
  pyproject.toml
4
4
  setup.py
5
5
  pgmini_migrate/__init__.py
6
+ pgmini_migrate/__main__.py
6
7
  pgmini_migrate/cli.py
7
- pgmini_migrate/generator.py
8
- pgmini_migrate/runner.py
8
+ pgmini_migrate/utils.py
9
9
  pgmini_migrate.egg-info/PKG-INFO
10
10
  pgmini_migrate.egg-info/SOURCES.txt
11
11
  pgmini_migrate.egg-info/dependency_links.txt
@@ -1,2 +1,3 @@
1
1
  psycopg[binary]>=3.1.8
2
2
  dotenv<0.10.0,>=0.9.9
3
+ click<9.0.0,>=8.2.1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pgmini-migrate"
7
- version = "0.1.1"
7
+ version = "0.1.3"
8
8
  description = "A minimal PostgreSQL migration tool for Python"
9
9
  readme = "README.md"
10
10
  license = { file = "LICENSE" }
@@ -13,9 +13,10 @@ authors = [
13
13
  ]
14
14
  dependencies = [
15
15
  "psycopg[binary]>=3.1.8",
16
- "dotenv (>=0.9.9,<0.10.0)"
16
+ "dotenv (>=0.9.9,<0.10.0)",
17
+ "click (>=8.2.1,<9.0.0)"
17
18
  ]
18
- requires-python = ">=3.8"
19
+ requires-python = ">=3.10"
19
20
 
20
21
  [project.scripts]
21
22
  pgmigrate = "pgmini_migrate.cli:main"
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name="pgmini-migrate",
5
- version="0.1.0",
5
+ version="0.1.3",
6
6
  packages=find_packages(),
7
7
  install_requires=["psycopg2-binary", 'psycopg', 'python-dotenv'],
8
8
  entry_points={
@@ -1,22 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: pgmini-migrate
3
- Version: 0.1.1
4
- Summary: A minimal PostgreSQL migration tool for Python
5
- Author-email: Nguyen Vu Duy Luan <nvdluan@gmail.com>
6
- License: Copyright (c) 2025 Nguyen Vu Duy Luan
7
- Project-URL: Homepage, https://github.com/NVDLuan/pgmini-migrate
8
- Project-URL: Issues, https://github.com/NVDLuan/pgmini-migrate/issues
9
- Requires-Python: >=3.8
10
- Description-Content-Type: text/markdown
11
- License-File: LICENSE
12
- Requires-Dist: psycopg[binary]>=3.1.8
13
- Requires-Dist: dotenv<0.10.0,>=0.9.9
14
- Dynamic: license-file
15
-
16
- # pgmini-migrate
17
-
18
- A minimal PostgreSQL migration tool using psycopg3.
19
-
20
- ## Install
21
- ```bash
22
- pip install pgmini-migrate
@@ -1,7 +0,0 @@
1
- # pgmini-migrate
2
-
3
- A minimal PostgreSQL migration tool using psycopg3.
4
-
5
- ## Install
6
- ```bash
7
- pip install pgmini-migrate
@@ -1,30 +0,0 @@
1
- import argparse
2
- from pgmini_migrate.generator import create_migration
3
- from pgmini_migrate.runner import upgrade, downgrade
4
-
5
- def main():
6
- parser = argparse.ArgumentParser(prog="pgmigrate", description="Mini migration tool for PostgreSQL")
7
- sub = parser.add_subparsers(dest="command")
8
-
9
- # create
10
- create_cmd = sub.add_parser("create", help="Create new migration")
11
- create_cmd.add_argument("description", nargs="+", help="Migration description")
12
-
13
- # upgrade
14
- upgrade_cmd = sub.add_parser("upgrade", help="Apply migrations")
15
- upgrade_cmd.add_argument("target", nargs="?", help="Target version (default: latest)")
16
-
17
- # downgrade
18
- downgrade_cmd = sub.add_parser("downgrade", help="Rollback migrations")
19
- downgrade_cmd.add_argument("target", nargs="?", help="Target version")
20
-
21
- args = parser.parse_args()
22
-
23
- if args.command == "create":
24
- create_migration(" ".join(args.description))
25
- elif args.command == "upgrade":
26
- upgrade(args.target)
27
- elif args.command == "downgrade":
28
- downgrade(args.target)
29
- else:
30
- parser.print_help()
@@ -1,37 +0,0 @@
1
- import os
2
-
3
-
4
- MIGRATIONS_DIR = os.getenv("MIGRATIONS_DIR", "migrations")
5
- UPGRADE_DIR = os.path.join(MIGRATIONS_DIR, "upgrade")
6
- DOWNGRADE_DIR = os.path.join(MIGRATIONS_DIR, "downgrade")
7
-
8
-
9
- def ensure_dirs():
10
- os.makedirs(UPGRADE_DIR, exist_ok=True)
11
- os.makedirs(DOWNGRADE_DIR, exist_ok=True)
12
-
13
- def get_next_version():
14
- ensure_dirs()
15
- files = os.listdir(UPGRADE_DIR)
16
- versions = []
17
- for f in files:
18
- if f[0:3].isdigit():
19
- versions.append(int(f[0:3]))
20
- return max(versions) + 1 if versions else 1
21
-
22
-
23
- def create_migration(description: str):
24
- version = get_next_version()
25
- version_str = f"{version:03d}"
26
- # format description thành tên file đẹp
27
- desc_clean = description.lower().replace(" ", "_")
28
-
29
- upgrade_file = os.path.join(UPGRADE_DIR, f"{version_str}.{desc_clean}.upgrade.sql")
30
- downgrade_file = os.path.join(DOWNGRADE_DIR, f"{version_str}.{desc_clean}.downgrade.sql")
31
-
32
- with open(upgrade_file, "w") as f:
33
- f.write(f"-- Migration {version_str}: {description}\n")
34
- with open(downgrade_file, "w") as f:
35
- f.write(f"-- Rollback {version_str}: {description}\n")
36
-
37
- print(f"✅ Created migration files:\n {upgrade_file}\n {downgrade_file}")
@@ -1,156 +0,0 @@
1
- import os
2
- from contextlib import contextmanager
3
-
4
- import psycopg
5
- from dotenv import load_dotenv
6
-
7
- load_dotenv('.env')
8
-
9
- DB_CONFIG = {
10
- "dbname": os.getenv("POSTGRES_DB", "postgres"),
11
- "user": os.getenv("POSTGRES_USER", "postgres"),
12
- "password": os.getenv("POSTGRES_PASSWORD", "postgres"),
13
- "host": os.getenv("POSTGRES_HOST", "localhost"),
14
- "port": os.getenv("POSTGRES_PORT", "5432"),
15
- }
16
-
17
- MIGRATIONS_DIR = os.getenv("MIGRATIONS_DIR", "migrations")
18
- UPGRADE_DIR = os.path.join(MIGRATIONS_DIR, "upgrade")
19
- DOWNGRADE_DIR = os.path.join(MIGRATIONS_DIR, "downgrade")
20
-
21
-
22
- @contextmanager
23
- def get_connection():
24
- conn = psycopg.connect(**DB_CONFIG)
25
- try:
26
- yield conn
27
- finally:
28
- conn.close()
29
-
30
-
31
- def ensure_migration_table(conn):
32
- with conn.cursor() as cur:
33
- cur.execute("""
34
- CREATE TABLE IF NOT EXISTS schema_migrations
35
- (
36
- version
37
- VARCHAR
38
- (
39
- 255
40
- ) PRIMARY KEY,
41
- applied_at TIMESTAMP DEFAULT NOW
42
- (
43
- )
44
- )
45
- """)
46
- conn.commit()
47
-
48
-
49
- def get_applied_migrations(conn):
50
- with conn.cursor() as cur:
51
- cur.execute("SELECT version FROM schema_migrations ORDER BY version")
52
- rows = cur.fetchall()
53
- return [row[0] for row in rows]
54
-
55
-
56
- def apply_migration(conn, version, sql_path):
57
- with open(sql_path, "r") as f:
58
- sql = f.read()
59
-
60
- try:
61
- with conn.cursor() as cur:
62
- print(f"⬆️ Applying migration {version} ...")
63
- cur.execute(sql)
64
- cur.execute(
65
- "INSERT INTO schema_migrations (version) VALUES (%s)", (version,)
66
- )
67
- conn.commit()
68
- print(f"✅ Migration {version} applied.")
69
- except Exception as e:
70
- conn.rollback()
71
- print(f"❌ Migration {version} failed: {e}")
72
- raise
73
-
74
-
75
- def rollback_migration(conn, version, sql_file):
76
- down_file = f"{version}.{sql_file.split('.', 1)[1].replace('upgrade', 'downgrade')}"
77
- sql_path = os.path.join(DOWNGRADE_DIR, down_file)
78
-
79
- if not os.path.exists(sql_path):
80
- print(f"⚠️ No rollback file for {version}")
81
- return
82
-
83
- with open(sql_path, "r") as f:
84
- sql = f.read()
85
-
86
- try:
87
- with conn.cursor() as cur:
88
- print(f"⬇️ Rolling back migration {version} ...")
89
- cur.execute(sql)
90
- cur.execute("DELETE FROM schema_migrations WHERE version = %s", (version,))
91
- conn.commit()
92
- print(f"✅ Migration {version} rolled back.")
93
- except Exception as e:
94
- conn.rollback()
95
- print(f"❌ Rollback {version} failed: {e}")
96
- raise
97
-
98
-
99
- def upgrade():
100
- with get_connection() as conn:
101
- ensure_migration_table(conn)
102
- applied = set(get_applied_migrations(conn))
103
-
104
- migration_files = sorted(os.listdir(UPGRADE_DIR))
105
- for filename in migration_files:
106
- version = filename.split(".")[0] # 001_init.sql -> 001
107
- if version in applied or not filename.endswith(".sql"):
108
- continue
109
- sql_path = os.path.join(UPGRADE_DIR, filename)
110
- apply_migration(conn, version, sql_path)
111
-
112
-
113
- def downgrade(target_version=None):
114
- with get_connection() as conn:
115
- ensure_migration_table(conn)
116
- applied = get_applied_migrations(conn)
117
-
118
- if not applied:
119
- print("⚠️ No migrations to rollback.")
120
- return
121
-
122
- if target_version == "base":
123
- target_index = -1
124
- elif target_version:
125
- if target_version not in applied:
126
- print(f"⚠️ Target version {target_version} not found in applied migrations.")
127
- return
128
- target_index = applied.index(target_version)
129
- else:
130
- # Nếu không truyền version → rollback 1 bước
131
- target_index = len(applied) - 2
132
-
133
- to_rollback = applied[target_index + 1:] # những migration mới hơn target
134
- if not to_rollback:
135
- print("⚠️ Nothing to rollback.")
136
- return
137
-
138
- # rollback ngược thứ tự
139
- for version in reversed(to_rollback):
140
- sql_file = next(
141
- (f for f in os.listdir(UPGRADE_DIR) if f.startswith(version)), None
142
- )
143
- if not sql_file:
144
- print(f"⚠️ No migration file found for {version}")
145
- continue
146
- sql_path = os.path.join(UPGRADE_DIR, sql_file)
147
- rollback_migration(conn, version, sql_path)
148
-
149
-
150
- def history():
151
- with get_connection() as conn:
152
- ensure_migration_table(conn)
153
- applied = get_applied_migrations(conn)
154
- print("📜 Applied migrations:")
155
- for v in applied:
156
- print(f" - {v}")
@@ -1,22 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: pgmini-migrate
3
- Version: 0.1.1
4
- Summary: A minimal PostgreSQL migration tool for Python
5
- Author-email: Nguyen Vu Duy Luan <nvdluan@gmail.com>
6
- License: Copyright (c) 2025 Nguyen Vu Duy Luan
7
- Project-URL: Homepage, https://github.com/NVDLuan/pgmini-migrate
8
- Project-URL: Issues, https://github.com/NVDLuan/pgmini-migrate/issues
9
- Requires-Python: >=3.8
10
- Description-Content-Type: text/markdown
11
- License-File: LICENSE
12
- Requires-Dist: psycopg[binary]>=3.1.8
13
- Requires-Dist: dotenv<0.10.0,>=0.9.9
14
- Dynamic: license-file
15
-
16
- # pgmini-migrate
17
-
18
- A minimal PostgreSQL migration tool using psycopg3.
19
-
20
- ## Install
21
- ```bash
22
- pip install pgmini-migrate
File without changes
File without changes