././@PaxHeader0000000000000000000000000000003200000000000010210 xustar0026 mtime=1698450453.12319 sqlite-migrate-0.1b0/0000755000175100001770000000000014517046025014134 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698450434.0 sqlite-migrate-0.1b0/LICENSE0000644000175100001770000002613514517046002015143 0ustar00runnerdocker Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ././@PaxHeader0000000000000000000000000000003200000000000010210 xustar0026 mtime=1698450453.12319 sqlite-migrate-0.1b0/PKG-INFO0000644000175100001770000001242414517046025015234 0ustar00runnerdockerMetadata-Version: 2.1 Name: sqlite-migrate Version: 0.1b0 Summary: A simple database migration system for SQLite, based on sqlite-utils Author: Simon Willison License: Apache-2.0 Project-URL: Homepage, https://github.com/simonw/sqlite-migrate Project-URL: Changelog, https://github.com/simonw/sqlite-migrate/releases Project-URL: Issues, https://github.com/simonw/sqlite-migrate/issues Classifier: Development Status :: 2 - Pre-Alpha Description-Content-Type: text/markdown License-File: LICENSE Requires-Dist: sqlite-utils Provides-Extra: test Requires-Dist: pytest; extra == "test" Requires-Dist: mypy; extra == "test" Requires-Dist: black; extra == "test" Requires-Dist: ruff; extra == "test" # sqlite-migrate [![PyPI](https://img.shields.io/pypi/v/sqlite-migrate.svg)](https://pypi.org/project/sqlite-migrate/) [![Changelog](https://img.shields.io/github/v/release/simonw/sqlite-migrate?include_prereleases&label=changelog)](https://sqlite-migrate.datasette.io/en/stable/changelog.html) [![Tests](https://github.com/simonw/sqlite-migrate/workflows/Test/badge.svg)](https://github.com/simonw/sqlite-migrate/actions?query=workflow%3ATest) [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/simonw/sqlite-migrate/blob/main/LICENSE) A simple database migration system for SQLite, based on [sqlite-utils](https://sqlite-utils.datasette.io/). **This project is an early alpha. Expect breaking changes.** ## Installation This tool works as a plugin for `sqlite-utils`. First [install that](https://sqlite-utils.datasette.io/en/stable/installation.html): ```bash pip install sqlite-utils ``` Then install this plugin like so: ```bash sqlite-utils install sqlite-migrate ``` ## Migration files This tool works against migration files. A migration file looks like this: ```python from sqlite_migrate import Migrations # Pick a unique name here - it must not clash with other migration sets that # the user might run against the same database. migration = Migrations("creatures") # Use this decorator against functions that implement migrations @migration() def m001_create_table(db): # db is a sqlite-utils Database instance db["creatures"].create( {"id": int, "name": str, "species": str}, pk="id" ) @migration() def m002_add_weight(db): # db is a sqlite-utils Database instance db["creatures"].add_column("weight", float) ``` Here is [documentation on the Database instance](https://sqlite-utils.datasette.io/en/stable/python-api.html) passed to each migration function. ## Running migrations Running this command will execute those migrations in sequence against the specified database file. Call `migrate` with a path to your database and a path to the migrations file you want to apply: ```bash sqlite-utils migrate creatures.db path/to/migrations.py ``` Running this multiple times will have no additional affect, unless you add more migration functions to the file. If you call it without arguments it will search for and apply any `migrations.py` files in the current directory or any of its subdirectories. You can also pass the path to a directory, in which case all `migrations.py` files in that directory and its subdirectories will be applied: ```bash sqlite-utils migrate creatures.db path/to/parent/ ``` When applying a single migrations file you can use the `--stop-before` option to apply all migrations up to but excluding the specified migration: ```bash sqlite-utils migrate creatures.db path/to/migrations.py --stop-before m002_add_weight ``` ## Listing migrations Add `--list` to list migrations without running them, for example: ```bash sqlite-utils migrate creatures.db --list ``` The output will look something like this: ``` Migrations for: creatures Applied: m001_create_table - 2023-07-23 04:09:40.324002 m002_add_weight - 2023-07-23 04:09:40.324649 m003_add_age - 2023-07-23 04:09:44.441616 m003_cleanup - 2023-07-23 04:09:44.443394 m004_cleanup - 2023-07-23 04:09:44.444184 m005_cleanup - 2023-07-23 04:09:44.445389 m006_cleanup - 2023-07-23 04:09:44.446742 m007_cleanup - 2023-07-23 04:16:02.529983 Pending: m008_cleanup ``` ## Verbose mode Add `-v` or `--verbose` for verbose output, which will show the schema before and after the migrations were applied along with a diff: ```bash sqlite-utils migrate creatures.db --verbose ``` Example output: ``` Migrating creatures.db Schema before: CREATE TABLE "_sqlite_migrations" ( [migration_set] TEXT, [name] TEXT, [applied_at] TEXT, PRIMARY KEY ([migration_set], [name]) ); CREATE TABLE [creatures] ( [id] INTEGER PRIMARY KEY, [name] TEXT, [species] TEXT , [weight] FLOAT); Schema after: CREATE TABLE "_sqlite_migrations" ( [migration_set] TEXT, [name] TEXT, [applied_at] TEXT, PRIMARY KEY ([migration_set], [name]) ); CREATE TABLE "creatures" ( [id] INTEGER PRIMARY KEY, [name] TEXT, [species] TEXT, [weight] FLOAT, [age] INTEGER, [shoe_size] INTEGER ); Schema diff: [applied_at] TEXT, PRIMARY KEY ([migration_set], [name]) ); -CREATE TABLE [creatures] ( +CREATE TABLE "creatures" ( [id] INTEGER PRIMARY KEY, [name] TEXT, - [species] TEXT -, [weight] FLOAT); + [species] TEXT, + [weight] FLOAT, + [age] INTEGER, + [shoe_size] INTEGER +); ``` ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698450434.0 sqlite-migrate-0.1b0/README.md0000644000175100001770000001113314517046002015405 0ustar00runnerdocker# sqlite-migrate [![PyPI](https://img.shields.io/pypi/v/sqlite-migrate.svg)](https://pypi.org/project/sqlite-migrate/) [![Changelog](https://img.shields.io/github/v/release/simonw/sqlite-migrate?include_prereleases&label=changelog)](https://sqlite-migrate.datasette.io/en/stable/changelog.html) [![Tests](https://github.com/simonw/sqlite-migrate/workflows/Test/badge.svg)](https://github.com/simonw/sqlite-migrate/actions?query=workflow%3ATest) [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/simonw/sqlite-migrate/blob/main/LICENSE) A simple database migration system for SQLite, based on [sqlite-utils](https://sqlite-utils.datasette.io/). **This project is an early alpha. Expect breaking changes.** ## Installation This tool works as a plugin for `sqlite-utils`. First [install that](https://sqlite-utils.datasette.io/en/stable/installation.html): ```bash pip install sqlite-utils ``` Then install this plugin like so: ```bash sqlite-utils install sqlite-migrate ``` ## Migration files This tool works against migration files. A migration file looks like this: ```python from sqlite_migrate import Migrations # Pick a unique name here - it must not clash with other migration sets that # the user might run against the same database. migration = Migrations("creatures") # Use this decorator against functions that implement migrations @migration() def m001_create_table(db): # db is a sqlite-utils Database instance db["creatures"].create( {"id": int, "name": str, "species": str}, pk="id" ) @migration() def m002_add_weight(db): # db is a sqlite-utils Database instance db["creatures"].add_column("weight", float) ``` Here is [documentation on the Database instance](https://sqlite-utils.datasette.io/en/stable/python-api.html) passed to each migration function. ## Running migrations Running this command will execute those migrations in sequence against the specified database file. Call `migrate` with a path to your database and a path to the migrations file you want to apply: ```bash sqlite-utils migrate creatures.db path/to/migrations.py ``` Running this multiple times will have no additional affect, unless you add more migration functions to the file. If you call it without arguments it will search for and apply any `migrations.py` files in the current directory or any of its subdirectories. You can also pass the path to a directory, in which case all `migrations.py` files in that directory and its subdirectories will be applied: ```bash sqlite-utils migrate creatures.db path/to/parent/ ``` When applying a single migrations file you can use the `--stop-before` option to apply all migrations up to but excluding the specified migration: ```bash sqlite-utils migrate creatures.db path/to/migrations.py --stop-before m002_add_weight ``` ## Listing migrations Add `--list` to list migrations without running them, for example: ```bash sqlite-utils migrate creatures.db --list ``` The output will look something like this: ``` Migrations for: creatures Applied: m001_create_table - 2023-07-23 04:09:40.324002 m002_add_weight - 2023-07-23 04:09:40.324649 m003_add_age - 2023-07-23 04:09:44.441616 m003_cleanup - 2023-07-23 04:09:44.443394 m004_cleanup - 2023-07-23 04:09:44.444184 m005_cleanup - 2023-07-23 04:09:44.445389 m006_cleanup - 2023-07-23 04:09:44.446742 m007_cleanup - 2023-07-23 04:16:02.529983 Pending: m008_cleanup ``` ## Verbose mode Add `-v` or `--verbose` for verbose output, which will show the schema before and after the migrations were applied along with a diff: ```bash sqlite-utils migrate creatures.db --verbose ``` Example output: ``` Migrating creatures.db Schema before: CREATE TABLE "_sqlite_migrations" ( [migration_set] TEXT, [name] TEXT, [applied_at] TEXT, PRIMARY KEY ([migration_set], [name]) ); CREATE TABLE [creatures] ( [id] INTEGER PRIMARY KEY, [name] TEXT, [species] TEXT , [weight] FLOAT); Schema after: CREATE TABLE "_sqlite_migrations" ( [migration_set] TEXT, [name] TEXT, [applied_at] TEXT, PRIMARY KEY ([migration_set], [name]) ); CREATE TABLE "creatures" ( [id] INTEGER PRIMARY KEY, [name] TEXT, [species] TEXT, [weight] FLOAT, [age] INTEGER, [shoe_size] INTEGER ); Schema diff: [applied_at] TEXT, PRIMARY KEY ([migration_set], [name]) ); -CREATE TABLE [creatures] ( +CREATE TABLE "creatures" ( [id] INTEGER PRIMARY KEY, [name] TEXT, - [species] TEXT -, [weight] FLOAT); + [species] TEXT, + [weight] FLOAT, + [age] INTEGER, + [shoe_size] INTEGER +); ``` ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698450434.0 sqlite-migrate-0.1b0/pyproject.toml0000644000175100001770000000125014517046002017041 0ustar00runnerdocker[project] name = "sqlite-migrate" version = "0.1b0" description = "A simple database migration system for SQLite, based on sqlite-utils" readme = "README.md" authors = [{name = "Simon Willison"}] license = {text = "Apache-2.0"} classifiers = [ "Development Status :: 2 - Pre-Alpha" ] dependencies = [ "sqlite-utils" ] [project.urls] Homepage = "https://github.com/simonw/sqlite-migrate" Changelog = "https://github.com/simonw/sqlite-migrate/releases" Issues = "https://github.com/simonw/sqlite-migrate/issues" [project.optional-dependencies] test = ["pytest", "mypy", "black", "ruff"] [project.entry-points.sqlite_utils] migrate = "sqlite_migrate.sqlite_utils_plugin" ././@PaxHeader0000000000000000000000000000003200000000000010210 xustar0026 mtime=1698450453.12319 sqlite-migrate-0.1b0/setup.cfg0000644000175100001770000000004614517046025015755 0ustar00runnerdocker[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000003200000000000010210 xustar0026 mtime=1698450453.12319 sqlite-migrate-0.1b0/sqlite_migrate/0000755000175100001770000000000014517046025017145 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698450434.0 sqlite-migrate-0.1b0/sqlite_migrate/__init__.py0000644000175100001770000000670514517046002021261 0ustar00runnerdockerfrom dataclasses import dataclass import datetime from typing import cast, Callable, List, Optional from typing import TYPE_CHECKING if TYPE_CHECKING: from sqlite_utils.db import Database, Table class Migrations: migrations_table = "_sqlite_migrations" @dataclass class _Migration: name: str fn: Callable @dataclass class _AppliedMigration: name: str applied_at: datetime.datetime def __init__(self, name: str): """ :param name: The name of the migration set. This should be unique. """ self.name = name self._migrations: List[Migrations._Migration] = [] def __call__(self, *, name: Optional[str] = None) -> Callable: """ :param name: The name to use for this migration - if not provided, the name of the function will be used """ def inner(func: Callable) -> Callable: self._migrations.append(self._Migration(name or func.__name__, func)) return func return inner def pending(self, db: "Database") -> List["Migrations._Migration"]: """ Return a list of pending migrations. """ self.ensure_migrations_table(db) already_applied = { r["name"] for r in db[self.migrations_table].rows_where( "migration_set = ?", [self.name] ) } return [ migration for migration in self._migrations if migration.name not in already_applied ] def applied(self, db: "Database") -> List["Migrations._AppliedMigration"]: """ Return a list of applied migrations. """ self.ensure_migrations_table(db) return [ self._AppliedMigration(name=row["name"], applied_at=row["applied_at"]) for row in db[self.migrations_table].rows_where( "migration_set = ?", [self.name] ) ] def apply(self, db: "Database", *, stop_before: Optional[str] = None): """ Apply any pending migrations to the database. """ self.ensure_migrations_table(db) for migration in self.pending(db): name = migration.name if name == stop_before: return migration.fn(db) _table(db, self.migrations_table).insert( { "migration_set": self.name, "name": name, "applied_at": str(datetime.datetime.now(datetime.timezone.utc)), } ) def ensure_migrations_table(self, db: "Database"): """ Ensure _sqlite_migrations table exists and has the correct schema """ table = _table(db, self.migrations_table) if not table.exists(): table.create( { "migration_set": str, "name": str, "applied_at": str, }, pk=("migration_set", "name"), ) elif table.pks != ["migration_set", "name"]: # This has the old primary key scheme, upgrade it table.transform(pk=("migration_set", "name")) def __repr__(self): return "".format( self.name, ", ".join(m.name for m in self._migrations) ) def _table(db: "Database", name: str) -> "Table": # mypy workaround return cast("Table", db[name]) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698450434.0 sqlite-migrate-0.1b0/sqlite_migrate/sqlite_utils_plugin.py0000644000175100001770000001014714517046002023614 0ustar00runnerdockerimport click import difflib import pathlib import sqlite_utils from sqlite_migrate import Migrations import textwrap @sqlite_utils.hookimpl def register_commands(cli): @cli.command() @click.argument( "db_path", type=click.Path(dir_okay=False, readable=True, writable=True) ) @click.argument("migrations", type=click.Path(dir_okay=True, exists=True), nargs=-1) @click.option("--stop-before", help="Stop before applying this migration") @click.option( "list_", "--list", is_flag=True, help="List migrations without running them" ) @click.option("-v", "--verbose", is_flag=True, help="Show verbose output") def migrate(db_path, migrations, stop_before, list_, verbose): """ Apply pending database migrations. Usage: sqlite-utils migrate database.db This will find the migrations.py file in the current directory or subdirectories and apply any pending migrations. Or pass paths to one or more migrations.py files directly: sqlite-utils migrate database.db path/to/migrations.py Pass --list to see a list of applied and pending migrations without applying them. """ if not migrations: # Scan current directory for migrations.py files migrations = [pathlib.Path(".").resolve()] files = set() for path_str in migrations: path = pathlib.Path(path_str) if path.is_dir(): files.update(path.rglob("migrations.py")) else: files.add(path) migration_sets = [] for filepath in files: code = filepath.read_text() namespace = {} exec(code, namespace) # Find all instances of Migrations for obj in namespace.values(): if isinstance(obj, Migrations): migration_sets.append(obj) if not migration_sets: raise click.ClickException("No migrations.py files found") if stop_before and len(migration_sets) > 1: raise click.ClickException( "--stop-before can only be used with a single migrations.py file" ) db = sqlite_utils.Database(db_path) if list_: display_list(db, migration_sets) return prev_schema = db.schema if verbose: click.echo("Migrating {}".format(db_path)) click.echo("\nSchema before:\n") click.echo(textwrap.indent(prev_schema, " ") or " (empty)") click.echo() for migration_set in migration_sets: migration_set.apply(db, stop_before=stop_before) if verbose: click.echo("Schema after:\n") post_schema = db.schema if post_schema == prev_schema: click.echo(" (unchanged)") else: click.echo(textwrap.indent(post_schema, " ")) click.echo("\nSchema diff:\n") # Calculate and display a diff diff = list( difflib.unified_diff( prev_schema.splitlines(), post_schema.splitlines() ) ) # Skipping the first two lines since they only make # sense if we provided filenames, and the next one # because it is just @@ -0,0 +1,15 @@ click.echo("\n".join(diff[3:])) def display_list(db, migration_sets): applied = set() for migration_set in migration_sets: print("Migrations for: {}".format(migration_set.name)) print() print(" Applied:") for migration in migration_set.applied(db): print(" {} - {}".format(migration.name, migration.applied_at)) applied.add(migration.name) print() print(" Pending:") output = False for migration in migration_set.pending(db): output = True if migration.name not in applied: print(" {}".format(migration.name)) if not output: print(" (none)") print() ././@PaxHeader0000000000000000000000000000003200000000000010210 xustar0026 mtime=1698450453.12319 sqlite-migrate-0.1b0/sqlite_migrate.egg-info/0000755000175100001770000000000014517046025020637 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698450453.0 sqlite-migrate-0.1b0/sqlite_migrate.egg-info/PKG-INFO0000644000175100001770000001242414517046025021737 0ustar00runnerdockerMetadata-Version: 2.1 Name: sqlite-migrate Version: 0.1b0 Summary: A simple database migration system for SQLite, based on sqlite-utils Author: Simon Willison License: Apache-2.0 Project-URL: Homepage, https://github.com/simonw/sqlite-migrate Project-URL: Changelog, https://github.com/simonw/sqlite-migrate/releases Project-URL: Issues, https://github.com/simonw/sqlite-migrate/issues Classifier: Development Status :: 2 - Pre-Alpha Description-Content-Type: text/markdown License-File: LICENSE Requires-Dist: sqlite-utils Provides-Extra: test Requires-Dist: pytest; extra == "test" Requires-Dist: mypy; extra == "test" Requires-Dist: black; extra == "test" Requires-Dist: ruff; extra == "test" # sqlite-migrate [![PyPI](https://img.shields.io/pypi/v/sqlite-migrate.svg)](https://pypi.org/project/sqlite-migrate/) [![Changelog](https://img.shields.io/github/v/release/simonw/sqlite-migrate?include_prereleases&label=changelog)](https://sqlite-migrate.datasette.io/en/stable/changelog.html) [![Tests](https://github.com/simonw/sqlite-migrate/workflows/Test/badge.svg)](https://github.com/simonw/sqlite-migrate/actions?query=workflow%3ATest) [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/simonw/sqlite-migrate/blob/main/LICENSE) A simple database migration system for SQLite, based on [sqlite-utils](https://sqlite-utils.datasette.io/). **This project is an early alpha. Expect breaking changes.** ## Installation This tool works as a plugin for `sqlite-utils`. First [install that](https://sqlite-utils.datasette.io/en/stable/installation.html): ```bash pip install sqlite-utils ``` Then install this plugin like so: ```bash sqlite-utils install sqlite-migrate ``` ## Migration files This tool works against migration files. A migration file looks like this: ```python from sqlite_migrate import Migrations # Pick a unique name here - it must not clash with other migration sets that # the user might run against the same database. migration = Migrations("creatures") # Use this decorator against functions that implement migrations @migration() def m001_create_table(db): # db is a sqlite-utils Database instance db["creatures"].create( {"id": int, "name": str, "species": str}, pk="id" ) @migration() def m002_add_weight(db): # db is a sqlite-utils Database instance db["creatures"].add_column("weight", float) ``` Here is [documentation on the Database instance](https://sqlite-utils.datasette.io/en/stable/python-api.html) passed to each migration function. ## Running migrations Running this command will execute those migrations in sequence against the specified database file. Call `migrate` with a path to your database and a path to the migrations file you want to apply: ```bash sqlite-utils migrate creatures.db path/to/migrations.py ``` Running this multiple times will have no additional affect, unless you add more migration functions to the file. If you call it without arguments it will search for and apply any `migrations.py` files in the current directory or any of its subdirectories. You can also pass the path to a directory, in which case all `migrations.py` files in that directory and its subdirectories will be applied: ```bash sqlite-utils migrate creatures.db path/to/parent/ ``` When applying a single migrations file you can use the `--stop-before` option to apply all migrations up to but excluding the specified migration: ```bash sqlite-utils migrate creatures.db path/to/migrations.py --stop-before m002_add_weight ``` ## Listing migrations Add `--list` to list migrations without running them, for example: ```bash sqlite-utils migrate creatures.db --list ``` The output will look something like this: ``` Migrations for: creatures Applied: m001_create_table - 2023-07-23 04:09:40.324002 m002_add_weight - 2023-07-23 04:09:40.324649 m003_add_age - 2023-07-23 04:09:44.441616 m003_cleanup - 2023-07-23 04:09:44.443394 m004_cleanup - 2023-07-23 04:09:44.444184 m005_cleanup - 2023-07-23 04:09:44.445389 m006_cleanup - 2023-07-23 04:09:44.446742 m007_cleanup - 2023-07-23 04:16:02.529983 Pending: m008_cleanup ``` ## Verbose mode Add `-v` or `--verbose` for verbose output, which will show the schema before and after the migrations were applied along with a diff: ```bash sqlite-utils migrate creatures.db --verbose ``` Example output: ``` Migrating creatures.db Schema before: CREATE TABLE "_sqlite_migrations" ( [migration_set] TEXT, [name] TEXT, [applied_at] TEXT, PRIMARY KEY ([migration_set], [name]) ); CREATE TABLE [creatures] ( [id] INTEGER PRIMARY KEY, [name] TEXT, [species] TEXT , [weight] FLOAT); Schema after: CREATE TABLE "_sqlite_migrations" ( [migration_set] TEXT, [name] TEXT, [applied_at] TEXT, PRIMARY KEY ([migration_set], [name]) ); CREATE TABLE "creatures" ( [id] INTEGER PRIMARY KEY, [name] TEXT, [species] TEXT, [weight] FLOAT, [age] INTEGER, [shoe_size] INTEGER ); Schema diff: [applied_at] TEXT, PRIMARY KEY ([migration_set], [name]) ); -CREATE TABLE [creatures] ( +CREATE TABLE "creatures" ( [id] INTEGER PRIMARY KEY, [name] TEXT, - [species] TEXT -, [weight] FLOAT); + [species] TEXT, + [weight] FLOAT, + [age] INTEGER, + [shoe_size] INTEGER +); ``` ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698450453.0 sqlite-migrate-0.1b0/sqlite_migrate.egg-info/SOURCES.txt0000644000175100001770000000061714517046025022527 0ustar00runnerdockerLICENSE README.md pyproject.toml sqlite_migrate/__init__.py sqlite_migrate/sqlite_utils_plugin.py sqlite_migrate.egg-info/PKG-INFO sqlite_migrate.egg-info/SOURCES.txt sqlite_migrate.egg-info/dependency_links.txt sqlite_migrate.egg-info/entry_points.txt sqlite_migrate.egg-info/requires.txt sqlite_migrate.egg-info/top_level.txt tests/test_sqlite_migrate.py tests/test_sqlite_utils_migrate_command.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698450453.0 sqlite-migrate-0.1b0/sqlite_migrate.egg-info/dependency_links.txt0000644000175100001770000000000114517046025024705 0ustar00runnerdocker ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698450453.0 sqlite-migrate-0.1b0/sqlite_migrate.egg-info/entry_points.txt0000644000175100001770000000007414517046025024136 0ustar00runnerdocker[sqlite_utils] migrate = sqlite_migrate.sqlite_utils_plugin ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698450453.0 sqlite-migrate-0.1b0/sqlite_migrate.egg-info/requires.txt0000644000175100001770000000005414517046025023236 0ustar00runnerdockersqlite-utils [test] pytest mypy black ruff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698450453.0 sqlite-migrate-0.1b0/sqlite_migrate.egg-info/top_level.txt0000644000175100001770000000001714517046025023367 0ustar00runnerdockersqlite_migrate ././@PaxHeader0000000000000000000000000000003200000000000010210 xustar0026 mtime=1698450453.12319 sqlite-migrate-0.1b0/tests/0000755000175100001770000000000014517046025015276 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698450434.0 sqlite-migrate-0.1b0/tests/test_sqlite_migrate.py0000644000175100001770000000351414517046002021716 0ustar00runnerdockerfrom sqlite_migrate import Migrations import sqlite_utils import pytest @pytest.fixture def migrations(): migrations = Migrations("test") @migrations() def m001(db): db["dogs"].insert({"name": "Cleo"}) @migrations() def m002(db): db["cats"].create({"name": str}) return migrations @pytest.fixture def migrations2(): migrations = Migrations("test2") @migrations() def m001(db): db["dogs2"].insert({"name": "Cleo"}) return migrations def test_basic(migrations): db = sqlite_utils.Database(memory=True) assert db.table_names() == [] migrations.apply(db) assert set(db.table_names()) == {"_sqlite_migrations", "dogs", "cats"} def test_stop_before(migrations): db = sqlite_utils.Database(memory=True) assert db.table_names() == [] migrations.apply(db, stop_before="m002") assert set(db.table_names()) == {"_sqlite_migrations", "dogs"} # Apply the rest migrations.apply(db) assert set(db.table_names()) == {"_sqlite_migrations", "dogs", "cats"} def test_two_migration_sets(migrations, migrations2): db = sqlite_utils.Database(memory=True) assert db.table_names() == [] migrations.apply(db) migrations2.apply(db) assert set(db.table_names()) == {"_sqlite_migrations", "dogs", "cats", "dogs2"} def test_upgrades_sqlite_migrations_from_one_to_two_primary_keys(migrations): db = sqlite_utils.Database(memory=True) db["_sqlite_migrations"].create( { "migration_set": str, "name": str, "applied_at": str, }, pk="name", ) # Applying migrations should fix that assert db.table_names() == ["_sqlite_migrations"] assert db["_sqlite_migrations"].pks == ["name"] migrations.apply(db) assert db["_sqlite_migrations"].pks == ["migration_set", "name"] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698450434.0 sqlite-migrate-0.1b0/tests/test_sqlite_utils_migrate_command.py0000644000175100001770000001166614517046002024643 0ustar00runnerdockerimport sqlite_utils.cli import pathlib from click.testing import CliRunner import pytest TWO_MIGRATIONS = """ from sqlite_migrate import Migrations m = Migrations("hello") @m() def foo(db): db["foo"].insert({"hello": "world"}) @m() def bar(db): db["bar"].insert({"hello": "world"}) """ @pytest.fixture def two_migrations(tmpdir): path = pathlib.Path(tmpdir) (path / "foo").mkdir() migrations_py = path / "foo" / "migrations.py" migrations_py.write_text(TWO_MIGRATIONS, "utf-8") return path, migrations_py @pytest.mark.parametrize("arg", ("TMPDIR", "TMPDIR/foo/migrations.py", "TMPDIR/foo/")) def test_basic(two_migrations, arg): path, _ = two_migrations db_path = str(path / "test.db") runner = CliRunner() def _list(): list_result = runner.invoke( sqlite_utils.cli.cli, ["migrate", db_path, "--list", arg.replace("TMPDIR", str(path))], ) assert list_result.exit_code == 0 return list_result.output assert _list() == ( "Migrations for: hello\n\n" " Applied:\n\n" " Pending:\n" " foo\n" " bar\n\n" ) result = runner.invoke( sqlite_utils.cli.cli, ["migrate", db_path, arg.replace("TMPDIR", str(path))] ) assert result.exit_code == 0, result.output list_output = _list() assert "Migrations for: hello\n\n Applied:\n " in list_output prior_to_pending = list_output.split(" Pending")[0] assert " foo" in prior_to_pending assert " bar" in prior_to_pending assert " Pending:\n (none)" in list_output db = sqlite_utils.Database(db_path) assert db["foo"].exists() assert db["bar"].exists() assert db["_sqlite_migrations"].exists() rows = list(db["_sqlite_migrations"].rows) assert len(rows) == 2 assert rows[0]["name"] == "foo" assert rows[1]["name"] == "bar" def test_verbose(tmpdir): path = pathlib.Path(tmpdir) (path / "foo").mkdir() migrations_py = path / "foo" / "migrations.py" migrations_py.write_text( """ from sqlite_migrate import Migrations m = Migrations("hello") @m() def foo(db): db["dogs"].insert({"id": 1, "name": "Cleo"}) """, "utf-8", ) db_path = str(path / "test.db") runner = CliRunner() result = runner.invoke( sqlite_utils.cli.cli, ["migrate", db_path, str(migrations_py)] ) assert result.exit_code == 0 # Now run again with --verbose, should be no changes result = runner.invoke( sqlite_utils.cli.cli, ["migrate", db_path, str(migrations_py), "--verbose"] ) assert result.exit_code == 0 expected = """ Schema before: CREATE TABLE [_sqlite_migrations] ( [migration_set] TEXT, [name] TEXT, [applied_at] TEXT, PRIMARY KEY ([migration_set], [name]) ); CREATE TABLE [dogs] ( [id] INTEGER, [name] TEXT ); Schema after: (unchanged) """.strip() assert expected in result.output # Now append to the migration and run it new_migration = """ @m() def bar(db): db["dogs"].add_column("age", int) db["dogs"].add_column("weight", float) db["dogs"].transform() """ # Append that to migrations.py migrations_py.write_text(migrations_py.read_text("utf-8") + new_migration) # And run it result = runner.invoke( sqlite_utils.cli.cli, ["migrate", db_path, str(migrations_py), "--verbose"] ) assert result.exit_code == 0 expected_diff = """ Schema diff: [applied_at] TEXT, PRIMARY KEY ([migration_set], [name]) ); -CREATE TABLE [dogs] ( +CREATE TABLE "dogs" ( [id] INTEGER, - [name] TEXT + [name] TEXT, + [age] INTEGER, + [weight] FLOAT ); """.strip() assert expected_diff in result.output def test_stop_before(two_migrations): path, _ = two_migrations db_path = str(path / "test.db") runner = CliRunner() result = runner.invoke( sqlite_utils.cli.cli, [ "migrate", db_path, str(path / "foo" / "migrations.py"), "--stop-before", "bar", ], ) assert result.exit_code == 0 db = sqlite_utils.Database(db_path) assert db["foo"].exists() assert not db["bar"].exists() def test_stop_before_error(two_migrations): path, _ = two_migrations db_path = str(path / "test.db") (path / "foo" / "migrations2.py").write_text( """ from sqlite_migrate import Migrations m = Migrations("hello2") @m() def foo(db): db["foo"].insert({"hello": "world"}) """, "utf-8", ) runner = CliRunner() result = runner.invoke( sqlite_utils.cli.cli, [ "migrate", db_path, str(path / "foo" / "migrations.py"), str(path / "foo" / "migrations2.py"), "--stop-before", "foo", ], ) assert result.exit_code == 1 assert ( "--stop-before can only be used with a single migrations.py file" in result.output )