Skip to content

Commit

Permalink
Merge pull request #22 from piercefreeman/feature/improve-docs
Browse files Browse the repository at this point in the history
Improve docs for new website
  • Loading branch information
piercefreeman authored Oct 22, 2024
2 parents 279dd7a + be7f31b commit be8d5ef
Show file tree
Hide file tree
Showing 7 changed files with 311 additions and 28 deletions.
12 changes: 8 additions & 4 deletions iceaxe/__tests__/test_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,11 +131,15 @@ def test_group_by():


def test_update():
new_query = QueryBuilder().update(UserDemo).where(UserDemo.id == 1)
new_query.update_values = {"name": "New Name"}
new_query = (
QueryBuilder()
.update(UserDemo)
.set(UserDemo.name, "John")
.where(UserDemo.id == 1)
)
assert new_query.build() == (
'UPDATE "userdemo" SET name = %s WHERE "userdemo"."id" = $1',
[1],
'UPDATE "userdemo" SET "userdemo"."name" = $1 WHERE "userdemo"."id" = $2',
["John", 1],
)


Expand Down
28 changes: 25 additions & 3 deletions iceaxe/migrations/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,28 @@ async def handle_generate(
Creates a new migration definition file, comparing the previous version
(if it exists) with the current schema.
:param package: The current python package name. This should match the name of the
project that's specified in pyproject.toml or setup.py.
:param message: An optional message to include in the migration file. Helps
with describing changes and searching for past migration logic over time.
```python {{sticky: True}}
from iceaxe.migrations.cli import handle_generate
from click import command, option
@command()
@option("--message", help="A message to include in the migration file.")
def generate_migration(message: str):
db_connection = DBConnection(...)
handle_generate("my_project", db_connection, message=message)
```
"""

CONSOLE.print("[bold blue]Generating migration to current schema")

CONSOLE.print(
"[grey58]Note that Mountaineer's migration support is well tested but still in beta."
"[grey58]Note that Iceaxe's migration support is well tested but still in beta."
)
CONSOLE.print(
"[grey58]File an issue @ https://github.com/piercefreeman/iceaxe/issues if you encounter any problems."
Expand Down Expand Up @@ -102,6 +118,9 @@ async def handle_apply(
"""
Applies all migrations that have not been applied to the database.
:param package: The current python package name. This should match the name of the
project that's specified in pyproject.toml or setup.py.
"""

migrations_path = resolve_package_path(package) / "migrations"
Expand Down Expand Up @@ -141,7 +160,7 @@ async def handle_apply(
f"[bold blue]Applying {migration.up_revision}...", spinner="dots"
):
start = monotonic_ns()
await migration.handle_up(db_connection)
await migration._handle_up(db_connection)

CONSOLE.print(
f"[bold green]🚀 Applied {migration.up_revision} in {(monotonic_ns() - start) / 1e9:.2f}s"
Expand All @@ -155,6 +174,9 @@ async def handle_rollback(
"""
Rolls back the last migration that was applied to the database.
:param package: The current python package name. This should match the name of the
project that's specified in pyproject.toml or setup.py.
"""

migrations_path = resolve_package_path(package) / "migrations"
Expand Down Expand Up @@ -193,7 +215,7 @@ async def handle_rollback(
spinner="dots",
):
start = monotonic_ns()
await this_migration.handle_down(db_connection)
await this_migration._handle_down(db_connection)

CONSOLE.print(
f"[bold green]🪃 Rolled back migration to {this_migration.down_revision} in {(monotonic_ns() - start) / 1e9:.2f}s"
Expand Down
10 changes: 2 additions & 8 deletions iceaxe/migrations/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,10 @@ class MigrationRevision(MigrationRevisionBase):
up_revision: str = {rev}
down_revision: str | None = {prev_rev}
async def up(
self,
migrator: Migrator = Depends(MigrationDependencies.get_migrator),
):
async def up(self, migrator: Migrator):
{up_code}
async def down(
self,
migrator: Migrator = Depends(MigrationDependencies.get_migrator),
):
async def down(self, migrator: Migrator):
{down_code}
"""

Expand Down
28 changes: 20 additions & 8 deletions iceaxe/migrations/migration.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@

class MigrationRevisionBase:
"""
Base class for all revisions. Both the "up" and the "down"
also accepts all dependency injection values.
Base class for all revisions. This class is most often automatically
generated by the `migrate` CLI command, which automatically determines
the proper up and down revisions for your migration class.
Once added to your project, you can modify the up/down migration methods
however you see fit.
"""

Expand All @@ -16,7 +20,7 @@ class MigrationRevisionBase:
up_revision: str
down_revision: str | None

async def handle_up(self, db_connection: DBConnection):
async def _handle_up(self, db_connection: DBConnection):
"""
Internal method to handle the up migration.
"""
Expand All @@ -26,7 +30,7 @@ async def handle_up(self, db_connection: DBConnection):
await self.up(migrator)
await migrator.set_active_revision(self.up_revision)

async def handle_down(self, db_connection: DBConnection):
async def _handle_down(self, db_connection: DBConnection):
"""
Internal method to handle the down migration.
"""
Expand All @@ -38,17 +42,25 @@ async def handle_down(self, db_connection: DBConnection):
@abstractmethod
async def up(self, migrator: Migrator):
"""
Perform the migration "up" action. Clients should place their
migration logic here.
Perform the migration "up" action. This converts your old database schema to the new
schema that's found in your code definition. Add any other migration rules to your
data in this function as well.
It's good practice to make sure any up migrations don't immediately drop data. Instead,
consider moving to a temporary table.
Support both raw SQL execution and helper functions to manipulate the tables and
columns that you have defined. See the Migrator class for more information.
"""
pass

@abstractmethod
async def down(self, migrator: Migrator):
"""
Perform the migration "down" action. Clients should place their
migration logic here.
Perform the migration "down" action. This converts the current database state to the
previous snapshot. It should be used in any automatic rollback pipelines if you
had a feature that was rolled out and then rolled back.
"""
pass
22 changes: 22 additions & 0 deletions iceaxe/migrations/migrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ class Migrator:
"""

actor: DatabaseActions
"""
The main interface for client migrations. Add tables, columns, and more using this wrapper.
"""

db_connection: DBConnection
"""
The main database connection for the migration. Use this to run raw SQL queries. We auto-wrap
this connection in a transaction block for you, so successful migrations will be
automatically committed when completed and unsuccessful migrations will be rolled back.
"""

def __init__(self, db_connection: DBConnection):
self.actor = DatabaseActions(dry_run=False, db_connection=db_connection)
self.db_connection = db_connection
Expand Down Expand Up @@ -47,6 +60,10 @@ async def init_db(self):
)

async def set_active_revision(self, value: str | None):
"""
Sets the active revision in the migration_info table.
"""
LOGGER.info(f"Setting active revision to {value}")

query = """
Expand All @@ -58,6 +75,11 @@ async def set_active_revision(self, value: str | None):
LOGGER.info("Active revision set")

async def get_active_revision(self) -> str | None:
"""
Gets the active revision from the migration_info table.
Requires that the migration_info table has been initialized.
"""
query = """
SELECT active_revision FROM migration_info
"""
Expand Down
Loading

0 comments on commit be8d5ef

Please sign in to comment.