From a562173019163174a57c9a1c9801d8f2b6df3866 Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 20:27:59 +0100 Subject: [PATCH] fix: run only the missing schema changes on startup ALTER TABLE and CREATE INDEX require owning the table even with IF NOT EXISTS, and CREATE TABLE IF NOT EXISTS requires the CREATE privilege on the schema. So startup failed for an application role that only has DML privileges, even when the table and indexes had been prepared in advance; for CREATE TABLE this was already the case before. Check which parts already exist (to_regclass, pg_attribute) under the schema lock and run DDL only for the missing ones. --- src/taskiq_pg/_internal/broker.py | 18 ++++++ src/taskiq_pg/aiopg/broker.py | 35 +++++++++-- src/taskiq_pg/asyncpg/broker.py | 30 +++++++-- src/taskiq_pg/psqlpy/broker.py | 26 ++++++-- src/taskiq_pg/psycopg/broker.py | 43 ++++++++++--- tests/integration/test_schema_privileges.py | 67 +++++++++++++++++++++ 6 files changed, 195 insertions(+), 24 deletions(-) create mode 100644 tests/integration/test_schema_privileges.py diff --git a/src/taskiq_pg/_internal/broker.py b/src/taskiq_pg/_internal/broker.py index 00e621a..946efde 100644 --- a/src/taskiq_pg/_internal/broker.py +++ b/src/taskiq_pg/_internal/broker.py @@ -108,3 +108,21 @@ def schema_lock_query(table_name: str) -> str: """ digest = hashlib.sha256(f"taskiq_pg:messages:{table_name}".encode()).digest() return f"SELECT pg_advisory_xact_lock({int.from_bytes(digest[:8], 'big', signed=True)})" + + +SCHEMA_STATUS_QUERY = """ +SELECT + to_regclass({table}) IS NOT NULL AS has_table, + ( + SELECT count(*) FROM pg_attribute + WHERE attrelid = to_regclass({table}) AND attname IN ('claimed_at', 'attempts') AND NOT attisdropped + ) = 2 AS has_delivery_columns, + to_regclass({pending_index}) IS NOT NULL AS has_pending_index, + to_regclass({processing_index}) IS NOT NULL AS has_processing_index +""" +""" +Query that tells which parts of the messages table already exist. + +Brokers run DDL only for the missing parts: `ALTER TABLE` and `CREATE INDEX` require owning the table even with +`IF NOT EXISTS`, so a role with only DML privileges can use a table that was prepared in advance. +""" diff --git a/src/taskiq_pg/aiopg/broker.py b/src/taskiq_pg/aiopg/broker.py index 274981c..c0600c6 100644 --- a/src/taskiq_pg/aiopg/broker.py +++ b/src/taskiq_pg/aiopg/broker.py @@ -7,7 +7,13 @@ import aiopg from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker, schema_lock_query +from taskiq_pg._internal.broker import ( + LISTEN_KEEPALIVE_QUERY, + POLL_NOW, + SCHEMA_STATUS_QUERY, + BasePostgresBroker, + schema_lock_query, +) from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait, run_until_first_done from taskiq_pg.aiopg.queries import ( @@ -197,12 +203,31 @@ async def startup(self) -> None: await cursor.execute("BEGIN") try: await cursor.execute(schema_lock_query(self.table_name)) - await cursor.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) - await cursor.execute(ADD_DELIVERY_COLUMNS_QUERY.format(table=self.table_name)) await cursor.execute( - CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), + SCHEMA_STATUS_QUERY.format( + table="%(table)s", + pending_index="%(pending_index)s", + processing_index="%(processing_index)s", + ), + { + "table": self.table_name, + "pending_index": f"{self.table_name}_pending_idx", + "processing_index": f"{self.table_name}_processing_idx", + }, ) - if self.processing_timeout is not None: + has_table, has_delivery_columns, has_pending_index, has_processing_index = await cursor.fetchone() + if not has_table: + await cursor.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) + if not has_delivery_columns: + await cursor.execute(ADD_DELIVERY_COLUMNS_QUERY.format(table=self.table_name)) + if not has_pending_index: + await cursor.execute( + CREATE_PENDING_INDEX_QUERY.format( + index=f"{self.table_name}_pending_idx", + table=self.table_name, + ), + ) + if self.processing_timeout is not None and not has_processing_index: await cursor.execute( CREATE_PROCESSING_INDEX_QUERY.format( index=f"{self.table_name}_processing_idx", diff --git a/src/taskiq_pg/asyncpg/broker.py b/src/taskiq_pg/asyncpg/broker.py index 5945a79..e5f38d8 100644 --- a/src/taskiq_pg/asyncpg/broker.py +++ b/src/taskiq_pg/asyncpg/broker.py @@ -7,7 +7,13 @@ import asyncpg from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker, schema_lock_query +from taskiq_pg._internal.broker import ( + LISTEN_KEEPALIVE_QUERY, + POLL_NOW, + SCHEMA_STATUS_QUERY, + BasePostgresBroker, + schema_lock_query, +) from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait from taskiq_pg.asyncpg.queries import ( @@ -193,12 +199,24 @@ async def startup(self) -> None: self._write_pool = await asyncpg.create_pool(self.dsn, **self.write_kwargs) async with self._write_pool.acquire() as conn, conn.transaction(): await conn.execute(schema_lock_query(self.table_name)) - await conn.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) - await conn.execute(ADD_DELIVERY_COLUMNS_QUERY.format(table=self.table_name)) - await conn.execute( - CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), + status = await conn.fetchrow( + SCHEMA_STATUS_QUERY.format(table="$1", pending_index="$2", processing_index="$3"), + self.table_name, + f"{self.table_name}_pending_idx", + f"{self.table_name}_processing_idx", ) - if self.processing_timeout is not None: + if status is None: + msg = "schema status query returned no row" + raise RuntimeError(msg) + if not status["has_table"]: + await conn.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) + if not status["has_delivery_columns"]: + await conn.execute(ADD_DELIVERY_COLUMNS_QUERY.format(table=self.table_name)) + if not status["has_pending_index"]: + await conn.execute( + CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), + ) + if self.processing_timeout is not None and not status["has_processing_index"]: await conn.execute( CREATE_PROCESSING_INDEX_QUERY.format( index=f"{self.table_name}_processing_idx", diff --git a/src/taskiq_pg/psqlpy/broker.py b/src/taskiq_pg/psqlpy/broker.py index a615393..4a0bd36 100644 --- a/src/taskiq_pg/psqlpy/broker.py +++ b/src/taskiq_pg/psqlpy/broker.py @@ -11,7 +11,13 @@ from psqlpy.extra_types import JSONB from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker, schema_lock_query +from taskiq_pg._internal.broker import ( + LISTEN_KEEPALIVE_QUERY, + POLL_NOW, + SCHEMA_STATUS_QUERY, + BasePostgresBroker, + schema_lock_query, +) from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait, run_until_first_done from taskiq_pg.psqlpy.queries import ( @@ -126,12 +132,20 @@ async def startup(self) -> None: # create messages table if it doesn't exist async with self._write_pool.acquire() as conn, conn.transaction() as transaction: await transaction.execute(schema_lock_query(self.table_name)) - await transaction.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) - await transaction.execute(ADD_DELIVERY_COLUMNS_QUERY.format(table=self.table_name)) - await transaction.execute( - CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), + result = await transaction.fetch( + SCHEMA_STATUS_QUERY.format(table="$1", pending_index="$2", processing_index="$3"), + [self.table_name, f"{self.table_name}_pending_idx", f"{self.table_name}_processing_idx"], ) - if self.processing_timeout is not None: + status = result.result()[0] + if not status["has_table"]: + await transaction.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) + if not status["has_delivery_columns"]: + await transaction.execute(ADD_DELIVERY_COLUMNS_QUERY.format(table=self.table_name)) + if not status["has_pending_index"]: + await transaction.execute( + CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), + ) + if self.processing_timeout is not None and not status["has_processing_index"]: await transaction.execute( CREATE_PROCESSING_INDEX_QUERY.format( index=f"{self.table_name}_processing_idx", diff --git a/src/taskiq_pg/psycopg/broker.py b/src/taskiq_pg/psycopg/broker.py index 6ae3741..b54d8e0 100644 --- a/src/taskiq_pg/psycopg/broker.py +++ b/src/taskiq_pg/psycopg/broker.py @@ -10,7 +10,13 @@ from psycopg_pool import AsyncConnectionPool from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker, schema_lock_query +from taskiq_pg._internal.broker import ( + LISTEN_KEEPALIVE_QUERY, + POLL_NOW, + SCHEMA_STATUS_QUERY, + BasePostgresBroker, + schema_lock_query, +) from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait from taskiq_pg.psycopg.queries import ( @@ -217,15 +223,38 @@ async def startup(self) -> None: connection.cursor() as cursor, ): await cursor.execute(schema_lock_query(self.table_name)) - await cursor.execute(sql.SQL(CREATE_MESSAGE_TABLE_QUERY).format(sql.Identifier(self.table_name))) - await cursor.execute(sql.SQL(ADD_DELIVERY_COLUMNS_QUERY).format(table=sql.Identifier(self.table_name))) + # psycopg quotes the names in DDL, so they are quoted here too await cursor.execute( - sql.SQL(CREATE_PENDING_INDEX_QUERY).format( - index=sql.Identifier(f"{self.table_name}_pending_idx"), - table=sql.Identifier(self.table_name), + SCHEMA_STATUS_QUERY.format( + table="quote_ident(%(table)s)", + pending_index="quote_ident(%(pending_index)s)", + processing_index="quote_ident(%(processing_index)s)", ), + { + "table": self.table_name, + "pending_index": f"{self.table_name}_pending_idx", + "processing_index": f"{self.table_name}_processing_idx", + }, ) - if self.processing_timeout is not None: + status = await cursor.fetchone() + if status is None: + msg = "schema status query returned no row" + raise RuntimeError(msg) + has_table, has_delivery_columns, has_pending_index, has_processing_index = status + if not has_table: + await cursor.execute(sql.SQL(CREATE_MESSAGE_TABLE_QUERY).format(sql.Identifier(self.table_name))) + if not has_delivery_columns: + await cursor.execute( + sql.SQL(ADD_DELIVERY_COLUMNS_QUERY).format(table=sql.Identifier(self.table_name)), + ) + if not has_pending_index: + await cursor.execute( + sql.SQL(CREATE_PENDING_INDEX_QUERY).format( + index=sql.Identifier(f"{self.table_name}_pending_idx"), + table=sql.Identifier(self.table_name), + ), + ) + if self.processing_timeout is not None and not has_processing_index: await cursor.execute( sql.SQL(CREATE_PROCESSING_INDEX_QUERY).format( index=sql.Identifier(f"{self.table_name}_processing_idx"), diff --git a/tests/integration/test_schema_privileges.py b/tests/integration/test_schema_privileges.py new file mode 100644 index 0000000..a56f3c5 --- /dev/null +++ b/tests/integration/test_schema_privileges.py @@ -0,0 +1,67 @@ +import asyncio +import typing as tp +import uuid +from urllib.parse import urlsplit, urlunsplit + +import asyncpg +import pytest +from taskiq import BrokerMessage + +from taskiq_pg.aiopg import AiopgBroker +from taskiq_pg.asyncpg import AsyncpgBroker +from taskiq_pg.asyncpg.queries import ( + ADD_DELIVERY_COLUMNS_QUERY, + CREATE_MESSAGE_TABLE_QUERY, + CREATE_PENDING_INDEX_QUERY, + CREATE_PROCESSING_INDEX_QUERY, +) +from taskiq_pg.psqlpy import PSQLPyBroker +from taskiq_pg.psycopg import PsycopgBroker + + +@pytest.fixture +async def dml_only_dsn(pg_dsn: str, connection: asyncpg.Connection) -> tp.AsyncGenerator[tuple[str, str], None]: + """Prepare a messages table as its owner and return a DSN for a role that may only read and write it.""" + role = f"dml_only_{uuid.uuid4().hex[:8]}" + table = f"prepared_{uuid.uuid4().hex[:8]}" + await connection.execute(CREATE_MESSAGE_TABLE_QUERY.format(table)) + await connection.execute(ADD_DELIVERY_COLUMNS_QUERY.format(table=table)) + await connection.execute(CREATE_PENDING_INDEX_QUERY.format(index=f"{table}_pending_idx", table=table)) + await connection.execute(CREATE_PROCESSING_INDEX_QUERY.format(index=f"{table}_processing_idx", table=table)) + await connection.execute(f"CREATE ROLE {role} LOGIN PASSWORD 'dml_only'") + await connection.execute(f"GRANT SELECT, INSERT, UPDATE, DELETE ON {table} TO {role}") + await connection.execute(f"GRANT USAGE ON SEQUENCE {table}_id_seq TO {role}") + await connection.execute(f"REVOKE CREATE ON SCHEMA public FROM {role}") + parts = urlsplit(pg_dsn) + dsn = urlunsplit(parts._replace(netloc=f"{role}:dml_only@{parts.hostname}:{parts.port}")) + try: + yield dsn, table + finally: + await connection.execute(f"DROP TABLE {table}") + await connection.execute(f"DROP OWNED BY {role}") + await connection.execute(f"DROP ROLE {role}") + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", [AsyncpgBroker, PsycopgBroker, PSQLPyBroker, AiopgBroker]) +async def test_when_table_is_prepared_in_advance__then_role_without_ddl_privileges_can_use_it( + dml_only_dsn: tuple[str, str], + broker_class: type[tp.Any], +) -> None: + # given + dsn, table = dml_only_dsn + broker = broker_class(dsn=dsn, table_name=table, channel_name=table, processing_timeout=60) + + # when + await broker.startup() + listener = broker.listen() + try: + message = BrokerMessage(task_id=uuid.uuid4().hex, task_name="example:dml", message=b'{"ok":true}', labels={}) + await broker.kick(message) + received = await asyncio.wait_for(anext(listener), timeout=5) + + # then + assert received.data == message.message + finally: + await listener.aclose() + await broker.shutdown()