Repository navigation
feat(subscriptions): add postgres connection and alembic migrations #8563
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ldelvoye
wants to merge
1
commit into
master
Choose a base branch
from
ldelvoye/feat/subscriptions-postgres-tooling
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import click | ||
|
|
||
| from snuba.subscriptions.postgres.database import migrate_to_head | ||
|
|
||
|
|
||
| @click.group() | ||
| def subscriptions_postgres() -> None: | ||
| pass | ||
|
|
||
|
|
||
| @subscriptions_postgres.command() | ||
| def migrate() -> None: | ||
| """Upgrade the subscriptions Postgres database to the latest migration.""" | ||
| migrate_to_head() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| [alembic] | ||
| script_location = %(here)s/migrations | ||
| file_template = %%(rev)s_%%(slug)s |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| from alembic import command | ||
| from alembic.config import Config | ||
| from sqlalchemy import Engine, create_engine, make_url, text | ||
|
|
||
| ALEMBIC_INI = Path(__file__).parent / "alembic.ini" | ||
|
|
||
| CONNECT_ARGS: dict[str, Any] = { | ||
| # pgbouncer runs the app role in transaction mode, which breaks prepared statements. | ||
| "prepare_threshold": None, | ||
| "connect_timeout": 5, | ||
| # Detect a dead connection in under a minute instead of the OS default of 2 hours. | ||
| "keepalives_idle": 10, | ||
| "tcp_user_timeout": 30000, | ||
| } | ||
|
|
||
|
|
||
| def build_engine(url: str) -> Engine: | ||
| return create_engine(url, pool_pre_ping=True, connect_args=CONNECT_ARGS) | ||
|
|
||
|
|
||
| def create_database_if_missing(url: str) -> None: | ||
| """Create the URL's database if absent; dev and test only, prod's comes from alloydb-init.""" | ||
| target = make_url(url) | ||
| maintenance_url = target.set(database="postgres") | ||
| engine = create_engine(maintenance_url, isolation_level="AUTOCOMMIT") | ||
| query = text("SELECT 1 FROM pg_database WHERE datname = :name") | ||
| with engine.connect() as connection: | ||
| result = connection.execute(query, {"name": target.database}) | ||
| exists = result.scalar() | ||
| if exists is None: | ||
| create = text(f'CREATE DATABASE "{target.database}"') | ||
| connection.execute(create) | ||
| engine.dispose() | ||
|
|
||
|
|
||
| def migrate_to_head() -> None: | ||
| config = Config(str(ALEMBIC_INI)) | ||
| command.upgrade(config, "head") |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| from alembic import context | ||
|
|
||
| from snuba import settings | ||
| from snuba.subscriptions.postgres.database import build_engine | ||
|
|
||
| if context.is_offline_mode(): | ||
| raise RuntimeError("Offline migrations are not supported") | ||
|
|
||
| url = settings.SUBSCRIPTIONS_POSTGRES_MIGRATIONS_URL | ||
| if url is None: | ||
| raise RuntimeError("SUBSCRIPTIONS_POSTGRES_MIGRATIONS_URL is not set") | ||
|
|
||
| engine = build_engine(url) | ||
| with engine.connect() as connection: | ||
| context.configure(connection=connection, target_metadata=None) | ||
| with context.begin_transaction(): | ||
| context.run_migrations() | ||
| engine.dispose() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| """${message} | ||
|
|
||
| Revision ID: ${up_revision} | ||
| Revises: ${down_revision | comma,n} | ||
| Create Date: ${create_date} | ||
|
|
||
| """ | ||
|
|
||
| from collections.abc import Sequence | ||
|
|
||
| import sqlalchemy as sa | ||
| from alembic import op | ||
| ${imports if imports else ""} | ||
|
|
||
| revision: str = ${repr(up_revision)} | ||
| down_revision: str | Sequence[str] | None = ${repr(down_revision)} | ||
| branch_labels: str | Sequence[str] | None = ${repr(branch_labels)} | ||
| depends_on: str | Sequence[str] | None = ${repr(depends_on)} | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| ${upgrades if upgrades else "pass"} | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| ${downgrades if downgrades else "pass"} |
38 changes: 38 additions & 0 deletions
38
snuba/subscriptions/postgres/migrations/versions/0001_create_subscriptions.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| """Create the subscriptions table. | ||
|
|
||
| Revision ID: 0001 | ||
| Revises: | ||
| Create Date: 2026-10-16 | ||
|
|
||
| """ | ||
|
|
||
| from collections.abc import Sequence | ||
|
|
||
| import sqlalchemy as sa | ||
| from alembic import op | ||
| from sqlalchemy.dialects import postgresql | ||
|
|
||
| revision: str = "0001" | ||
| down_revision: str | Sequence[str] | None = None | ||
| branch_labels: str | Sequence[str] | None = None | ||
| depends_on: str | Sequence[str] | None = None | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| op.create_table( | ||
| "subscriptions", | ||
| sa.Column("id", postgresql.UUID(), primary_key=True), | ||
| sa.Column("entity", sa.Text(), nullable=False), | ||
| sa.Column("partition", sa.Integer(), nullable=False), | ||
| sa.Column("data", postgresql.JSONB(), nullable=False), | ||
| ) | ||
| op.create_index( | ||
| "subscriptions_entity_partition_idx", | ||
| "subscriptions", | ||
| ["entity", "partition"], | ||
| ) | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| op.drop_index("subscriptions_entity_partition_idx", table_name="subscriptions") | ||
| op.drop_table("subscriptions") |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| from collections.abc import Generator | ||
|
|
||
| import psycopg | ||
| import pytest | ||
| from sqlalchemy import Engine, inspect | ||
|
|
||
| from snuba import settings | ||
| from snuba.subscriptions.postgres.database import ( | ||
| build_engine, | ||
| create_database_if_missing, | ||
| migrate_to_head, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def engine() -> Generator[Engine]: | ||
| url = settings.SUBSCRIPTIONS_POSTGRES_URL | ||
| assert url is not None | ||
| create_database_if_missing(url) | ||
| migrate_to_head() | ||
| engine = build_engine(url) | ||
| yield engine | ||
| engine.dispose() | ||
|
|
||
|
|
||
| def test_subscriptions_table_schema(engine: Engine) -> None: | ||
| inspector = inspect(engine) | ||
| columns = inspector.get_columns("subscriptions") | ||
| shapes = {column["name"]: (str(column["type"]), column["nullable"]) for column in columns} | ||
| assert shapes == { | ||
| "id": ("UUID", False), | ||
| "entity": ("TEXT", False), | ||
| "partition": ("INTEGER", False), | ||
| "data": ("JSONB", False), | ||
| } | ||
|
|
||
| primary_key = inspector.get_pk_constraint("subscriptions") | ||
| assert primary_key["constrained_columns"] == ["id"] | ||
|
|
||
| indexes = inspector.get_indexes("subscriptions") | ||
| index_columns = {index["name"]: index["column_names"] for index in indexes} | ||
| assert index_columns == {"subscriptions_entity_partition_idx": ["entity", "partition"]} | ||
|
|
||
|
|
||
| def test_engine_disables_prepared_statements(engine: Engine) -> None: | ||
| with engine.connect() as connection: | ||
| dbapi_connection = connection.connection.dbapi_connection | ||
| assert isinstance(dbapi_connection, psycopg.Connection) | ||
| assert dbapi_connection.prepare_threshold is None |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
While we are currently using postgres for subscriptions; we shouldn't bake that into the name. I'd much prefer if we dropped teh
subscriptionsprefix.