Skip to content

armgit / ARES

Public Imported from GitHub
0

ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.

fix(db): correct PostgreSQL catalog queries

Mafifrizi664992f747e6
diff --git a/ares/db/postgres.py b/ares/db/postgres.py
index 11da9fe..d699d96 100644
--- a/ares/db/postgres.py
+++ b/ares/db/postgres.py
@@ -30,6 +30,7 @@ from __future__ import annotations
import asyncio
import hashlib
import json
+import re
import secrets
import uuid
from datetime import datetime, timezone, timedelta
@@ -1133,8 +1134,8 @@ SELECT ind.indrelid::bigint AS table_oid,
idx.relnamespace::bigint AS index_schema_oid,
idx_nsp.nspname AS index_schema,
idx.relname AS index_name,
- idx.relkind AS index_relkind,
- idx.relpersistence AS index_relpersistence,
+ idx.relkind::text AS index_relkind,
+ idx.relpersistence::text AS index_relpersistence,
idx.relispartition AS index_is_partition,
am.amname AS access_method,
ind.indisunique,
@@ -1181,9 +1182,9 @@ SELECT ind.indrelid::bigint AS table_oid,
ORDER BY item.ordinality
) AS operator_class_namespaces,
ARRAY(
- SELECT item.collation=att.attcollation
+ SELECT item.collation_oid=att.attcollation
FROM unnest(ind.indcollation::oid[]) WITH ORDINALITY
- AS item(collation, ordinality)
+ AS item(collation_oid, ordinality)
JOIN unnest(ind.indkey::smallint[]) WITH ORDINALITY
AS key(attnum, ordinality)
ON key.ordinality=item.ordinality
@@ -1960,7 +1961,8 @@ def _postgres_finite_check_name(table: str, column: str) -> str:
def _postgres_constraint_definition(value: object) -> str:
- return " ".join(str(value).split())
+ normalized = " ".join(str(value).split())
+ return re.sub(r'"([a-z_][a-z0-9_]*)"', r"\1", normalized)
def _postgres_index_opclass(table: str, column: str) -> str:
@@ -2122,10 +2124,10 @@ class PostgresDatabase:
relation_type.oid::bigint AS type_oid,
type_nsp.nspname AS type_schema,
relation_type.typname AS type_name,
- relation_type.typtype,
+ relation_type.typtype::text AS typtype,
relation_type.typrelid::bigint AS type_relation_oid,
- rel.relkind,
- rel.relpersistence,
+ rel.relkind::text AS relkind,
+ rel.relpersistence::text AS relpersistence,
rel.relispartition,
rel.relrowsecurity,
rel.relforcerowsecurity,
@@ -2235,8 +2237,8 @@ class PostgresDatabase:
att.atttypmod
) AS data_type,
att.attnotnull,
- att.attidentity,
- att.attgenerated,
+ att.attidentity::text AS attidentity,
+ att.attgenerated::text AS attgenerated,
att.attisdropped,
att.attinhcount,
att.attislocal,
@@ -2308,7 +2310,7 @@ class PostgresDatabase:
primary_rows = await connection.fetch(
"""
SELECT con.conname,
- con.contype,
+ con.contype::text AS contype,
con.convalidated,
con.condeferrable,
con.condeferred,
@@ -2364,8 +2366,8 @@ class PostgresDatabase:
version_index_rows = await connection.fetch(
"""
SELECT index_rel.relname AS index_name,
- index_rel.relkind AS index_relkind,
- index_rel.relpersistence AS index_relpersistence,
+ index_rel.relkind::text AS index_relkind,
+ index_rel.relpersistence::text AS index_relpersistence,
index_rel.relispartition AS index_is_partition,
access_method.amname AS access_method,
ind.indisunique,
@@ -2408,9 +2410,9 @@ class PostgresDatabase:
ORDER BY item.position
) AS operator_class_namespaces,
ARRAY(
- SELECT item.collation=att.attcollation
+ SELECT item.collation_oid=att.attcollation
FROM unnest(ind.indcollation)
- WITH ORDINALITY AS item(collation, position)
+ WITH ORDINALITY AS item(collation_oid, position)
JOIN unnest(ind.indkey)
WITH ORDINALITY AS key(attnum, position)
ON key.position=item.position
@@ -2535,10 +2537,10 @@ class PostgresDatabase:
relation_type.oid::bigint AS type_oid,
type_nsp.nspname AS type_schema,
relation_type.typname AS type_name,
- relation_type.typtype,
+ relation_type.typtype::text AS typtype,
relation_type.typrelid::bigint AS type_relation_oid,
- rel.relkind,
- rel.relpersistence,
+ rel.relkind::text AS relkind,
+ rel.relpersistence::text AS relpersistence,
rel.relispartition,
rel.relrowsecurity,
rel.relforcerowsecurity,
@@ -2673,8 +2675,8 @@ class PostgresDatabase:
"""
SELECT table_rel.relname AS table_name,
index_rel.relname AS index_name,
- index_rel.relkind AS index_relkind,
- index_rel.relpersistence AS index_relpersistence,
+ index_rel.relkind::text AS index_relkind,
+ index_rel.relpersistence::text AS index_relpersistence,
index_rel.relispartition AS index_is_partition,
access_method.amname AS access_method,
ind.indisunique,
@@ -2728,9 +2730,9 @@ class PostgresDatabase:
ORDER BY item.position
) AS operator_class_namespaces,
ARRAY(
- SELECT item.collation=att.attcollation
+ SELECT item.collation_oid=att.attcollation
FROM unnest(ind.indcollation)
- WITH ORDINALITY AS item(collation, position)
+ WITH ORDINALITY AS item(collation_oid, position)
JOIN unnest(ind.indkey)
WITH ORDINALITY AS key(attnum, position)
ON key.position=item.position
@@ -2830,7 +2832,7 @@ class PostgresDatabase:
"""
SELECT source.relname AS table_name,
con.conname,
- con.contype,
+ con.contype::text AS contype,
con.convalidated,
con.condeferrable,
con.condeferred,
@@ -2844,8 +2846,8 @@ class PostgresDatabase:
AND att.attnum=key.attnum
ORDER BY key.position
) AS local_columns,
- index_rel.relkind AS index_relkind,
- index_rel.relpersistence AS index_relpersistence,
+ index_rel.relkind::text AS index_relkind,
+ index_rel.relpersistence::text AS index_relpersistence,
index_rel.relispartition AS index_is_partition,
ind.indisunique,
ind.indisprimary,
@@ -2929,7 +2931,7 @@ class PostgresDatabase:
SELECT source_nsp.nspname AS source_schema,
source.relname AS table_name,
con.conname,
- con.contype,
+ con.contype::text AS contype,
con.convalidated,
con.condeferrable,
con.condeferred,
@@ -2937,8 +2939,8 @@ class PostgresDatabase:
pg_get_constraintdef(con.oid, true) AS definition,
reference_nsp.nspname AS referenced_schema,
reference.relname AS referenced_table,
- con.confupdtype,
- con.confdeltype,
+ con.confupdtype::text AS confupdtype,
+ con.confdeltype::text AS confdeltype,
ARRAY(
SELECT attribute.attname
FROM unnest(con.conkey)
@@ -2959,8 +2961,8 @@ class PostgresDatabase:
) AS remote_columns,
index_nsp.nspname AS index_schema,
index_rel.relname AS index_name,
- index_rel.relkind AS index_relkind,
- index_rel.relpersistence AS index_relpersistence,
+ index_rel.relkind::text AS index_relkind,
+ index_rel.relpersistence::text AS index_relpersistence,
index_rel.relispartition AS index_is_partition,
access_method.amname AS access_method,
ind.indisunique,
@@ -3002,9 +3004,9 @@ class PostgresDatabase:
ORDER BY item.position
) AS operator_class_namespaces,
ARRAY(
- SELECT item.collation=attribute.attcollation
+ SELECT item.collation_oid=attribute.attcollation
FROM unnest(ind.indcollation)
- WITH ORDINALITY AS item(collation, position)
+ WITH ORDINALITY AS item(collation_oid, position)
JOIN unnest(ind.indkey)
WITH ORDINALITY AS key(attnum, position)
ON key.position=item.position
@@ -3318,8 +3320,8 @@ class PostgresDatabase:
"""
SELECT sequence_nsp.nspname AS sequence_schema,
sequence_rel.relname AS sequence_name,
- sequence_rel.relkind,
- sequence_rel.relpersistence,
+ sequence_rel.relkind::text AS relkind,
+ sequence_rel.relpersistence::text AS relpersistence,
format_type(sequence_def.seqtypid, NULL) AS data_type,
sequence_def.seqstart,
sequence_def.seqincrement,
@@ -3330,14 +3332,14 @@ class PostgresDatabase:
owner_nsp.nspname AS owner_schema,
owner_rel.relname AS owner_table,
owner_att.attname AS owner_column,
- dependency.deptype,
+ dependency.deptype::text AS deptype,
format_type(
owner_att.atttypid,
owner_att.atttypmod
) AS owner_data_type,
owner_att.attnotnull,
- owner_att.attidentity,
- owner_att.attgenerated,
+ owner_att.attidentity::text AS attidentity,
+ owner_att.attgenerated::text AS attgenerated,
owner_att.attcollation=owner_type.typcollation
AS collation_is_default,
pg_get_expr(
@@ -3649,8 +3651,8 @@ class PostgresDatabase:
SELECT att.attname AS column_name,
pg_catalog.format_type(att.atttypid, att.atttypmod) AS data_type,
att.attnotnull,
- att.attidentity,
- att.attgenerated,
+ att.attidentity::text AS attidentity,
+ att.attgenerated::text AS attgenerated,
att.attcollation=typ.typcollation AS collation_is_default,
pg_get_expr(def.adbin, def.adrelid) AS column_default
FROM pg_attribute AS att
@@ -3740,7 +3742,7 @@ class PostgresDatabase:
try:
constraint_rows = await connection.fetch(
"""
- SELECT con.conname, con.contype,
+ SELECT con.conname, con.contype::text AS contype,
con.conrelid::bigint AS table_oid,
con.confrelid::bigint AS referenced_oid,
con.conindid::bigint AS constraint_index_oid,
@@ -3766,7 +3768,8 @@ class PostgresDatabase:
AND remote_att.attnum=key.attnum
ORDER BY key.ordinality
) AS remote_columns,
- con.confupdtype, con.confdeltype
+ con.confupdtype::text AS confupdtype,
+ con.confdeltype::text AS confdeltype
FROM pg_constraint AS con
LEFT JOIN pg_class AS ref_rel ON ref_rel.oid=con.confrelid
LEFT JOIN pg_namespace AS ref_nsp ON ref_nsp.oid=ref_rel.relnamespace
@@ -3853,8 +3856,8 @@ class PostgresDatabase:
idx.relnamespace::bigint AS index_schema_oid,
idx_nsp.nspname AS index_schema,
idx.relname AS index_name,
- idx.relkind AS index_relkind,
- idx.relpersistence AS index_relpersistence,
+ idx.relkind::text AS index_relkind,
+ idx.relpersistence::text AS index_relpersistence,
idx.relispartition AS index_is_partition,
am.amname AS access_method,
ind.indisunique,
@@ -3901,9 +3904,9 @@ class PostgresDatabase:
ORDER BY item.ordinality
) AS operator_class_namespaces,
ARRAY(
- SELECT item.collation=att.attcollation
+ SELECT item.collation_oid=att.attcollation
FROM unnest(ind.indcollation) WITH ORDINALITY
- AS item(collation, ordinality)
+ AS item(collation_oid, ordinality)
JOIN unnest(ind.indkey) WITH ORDINALITY
AS key(attnum, ordinality)
ON key.ordinality=item.ordinality
diff --git a/migrations/versions/0008_reconcile_schema_parity.py b/migrations/versions/0008_reconcile_schema_parity.py
index 35171b8..83510b8 100644
--- a/migrations/versions/0008_reconcile_schema_parity.py
+++ b/migrations/versions/0008_reconcile_schema_parity.py
@@ -12,6 +12,7 @@ Alembic contract. Unknown or unsafe catalogs fail without mutation.
from __future__ import annotations
import re
+from decimal import Decimal, InvalidOperation
from typing import Any
import sqlalchemy as sa
@@ -22,6 +23,7 @@ down_revision: str | None = "0007"
branch_labels: str | None = None
depends_on: str | None = None
+
_CATALOG_ERROR = "Incompatible catalog for migration 0008"
_DATA_ERROR = "Unsafe data for migration 0008"
_DOWNGRADE_ERROR = "Migration 0008 is forward-only"
@@ -414,6 +416,27 @@ def _normalize_default(value: object) -> str | None:
return " ".join(normalized.split())
+def _pg_defaults_match(
+ actual: str | None,
+ expected: str | None,
+ data_type: str,
+) -> bool:
+ if actual == expected:
+ return True
+ if data_type != "double precision" or actual is None or expected is None:
+ return False
+ try:
+ actual_number = Decimal(actual)
+ expected_number = Decimal(expected)
+ except InvalidOperation:
+ return False
+ return (
+ actual_number.is_finite()
+ and expected_number.is_finite()
+ and actual_number == expected_number
+ )
+
+
def _sqlite_columns(bind: Any, table: str) -> tuple[_Column, ...]:
rows = bind.exec_driver_sql(f'PRAGMA table_info("{table}")').fetchall()
return tuple(
@@ -2401,10 +2424,10 @@ def _pg_validate_alembic_version_relation(bind: Any) -> None:
relation_type.oid::bigint AS type_oid,
type_namespace.nspname AS type_schema,
relation_type.typname AS type_name,
- relation_type.typtype,
+ relation_type.typtype::text AS typtype,
relation_type.typrelid::bigint AS type_relation_oid,
- relation.relkind,
- relation.relpersistence,
+ relation.relkind::text AS relkind,
+ relation.relpersistence::text AS relpersistence,
relation.relispartition,
relation.relrowsecurity,
relation.relforcerowsecurity,
@@ -2497,8 +2520,8 @@ def _pg_validate_alembic_version_relation(bind: Any) -> None:
attribute.atttypmod
) AS data_type,
attribute.attnotnull,
- attribute.attidentity,
- attribute.attgenerated,
+ attribute.attidentity::text AS attidentity,
+ attribute.attgenerated::text AS attgenerated,
attribute.attisdropped,
attribute.attinhcount,
attribute.attislocal,
@@ -2571,7 +2594,7 @@ def _pg_validate_alembic_version_relation(bind: Any) -> None:
SELECT
constraint_record.oid::bigint AS constraint_oid,
constraint_record.conname AS constraint_name,
- constraint_record.contype,
+ constraint_record.contype::text AS contype,
constraint_record.convalidated,
constraint_record.condeferrable,
constraint_record.condeferred,
@@ -2636,8 +2659,8 @@ def _pg_validate_alembic_version_relation(bind: Any) -> None:
index_record.oid::bigint AS index_oid,
index_record.relname AS index_name,
index_namespace.nspname AS index_schema,
- index_record.relkind AS index_relkind,
- index_record.relpersistence AS index_relpersistence,
+ index_record.relkind::text AS index_relkind,
+ index_record.relpersistence::text AS index_relpersistence,
index_record.relispartition AS index_is_partition,
access_method.amname AS access_method,
index_definition.indrelid::bigint AS table_oid,
@@ -2650,7 +2673,7 @@ def _pg_validate_alembic_version_relation(bind: Any) -> None:
index_definition.indnatts,
constraint_record.oid::bigint AS constraint_oid,
constraint_record.conname AS constraint_name,
- constraint_record.contype,
+ constraint_record.contype::text AS contype,
ARRAY(
SELECT attribute.attname
FROM unnest(index_definition.indkey)
@@ -2686,9 +2709,9 @@ def _pg_validate_alembic_version_relation(bind: Any) -> None:
ORDER BY item.position
) AS operator_class_namespaces,
ARRAY(
- SELECT item.collation=attribute.attcollation
+ SELECT item.collation_oid=attribute.attcollation
FROM unnest(index_definition.indcollation)
- WITH ORDINALITY AS item(collation, position)
+ WITH ORDINALITY AS item(collation_oid, position)
JOIN unnest(index_definition.indkey)
WITH ORDINALITY AS key(attnum, position)
ON key.position=item.position
@@ -2810,8 +2833,8 @@ def _pg_relation_rows(bind: Any) -> list[dict[str, object]]:
SELECT
relation.oid::bigint AS relation_oid,
relation.relname AS table_name,
- relation.relkind,
- relation.relpersistence,
+ relation.relkind::text AS relkind,
+ relation.relpersistence::text AS relpersistence,
relation.relispartition,
relation.relrowsecurity,
relation.relforcerowsecurity,
@@ -2902,7 +2925,7 @@ def _pg_validate_relation_shapes(bind: Any) -> set[str]:
"""
SELECT
type_record.typname AS type_name,
- type_record.typtype,
+ type_record.typtype::text AS typtype,
type_record.typrelid::bigint AS type_relation_oid,
namespace.nspname AS type_schema
FROM pg_type AS type_record
@@ -2962,8 +2985,8 @@ def _pg_column_rows(bind: Any) -> list[dict[str, object]]:
attribute.atttypmod
) AS data_type,
attribute.attnotnull,
- attribute.attidentity,
- attribute.attgenerated,
+ attribute.attidentity::text AS attidentity,
+ attribute.attgenerated::text AS attgenerated,
attribute.attisdropped,
attribute.attinhcount,
attribute.attislocal,
@@ -3112,7 +3135,11 @@ def _pg_validate_column_metadata(
or str(row["data_type"]).lower()
!= _pg_column_type(table, column)
or not nullable_matches
- or actual_default != expected_default
+ or not _pg_defaults_match(
+ actual_default,
+ expected_default,
+ str(row["data_type"]).lower(),
+ )
or str(row["attidentity"])
or str(row["attgenerated"])
or bool(row["attisdropped"])
@@ -3192,8 +3219,8 @@ def _pg_validate_serial_sequences(
SELECT
namespace.nspname AS sequence_schema,
sequence_record.relname AS sequence_name,
- sequence_record.relkind,
- sequence_record.relpersistence,
+ sequence_record.relkind::text AS relkind,
+ sequence_record.relpersistence::text AS relpersistence,
format_type(
sequence_definition.seqtypid,
NULL
@@ -3207,7 +3234,7 @@ def _pg_validate_serial_sequences(
owner_namespace.nspname AS owner_schema,
owner_table.relname AS owner_table,
owner_column.attname AS owner_column,
- dependency.deptype
+ dependency.deptype::text AS deptype
FROM pg_class AS sequence_record
JOIN pg_namespace AS namespace
ON namespace.oid=sequence_record.relnamespace
@@ -3296,7 +3323,7 @@ def _pg_constraint_rows(bind: Any) -> list[dict[str, object]]:
SELECT
relation.relname AS table_name,
constraint_record.conname AS constraint_name,
- constraint_record.contype AS constraint_type,
+ constraint_record.contype::text AS constraint_type,
constraint_record.convalidated AS is_validated,
constraint_record.condeferrable AS is_deferrable,
constraint_record.condeferred AS is_deferred,
@@ -3324,8 +3351,8 @@ def _pg_index_rows(bind: Any) -> list[dict[str, object]]:
SELECT
table_record.relname AS table_name,
index_record.relname AS index_name,
- index_record.relkind AS index_relkind,
- index_record.relpersistence AS index_relpersistence,
+ index_record.relkind::text AS index_relkind,
+ index_record.relpersistence::text AS index_relpersistence,
index_record.relispartition AS index_is_partition,
access_method.amname AS access_method,
index_definition.indisunique AS is_unique,
@@ -3370,9 +3397,9 @@ def _pg_index_rows(bind: Any) -> list[dict[str, object]]:
ORDER BY item.position
) AS operator_class_namespaces,
ARRAY(
- SELECT item.collation=attribute.attcollation
+ SELECT item.collation_oid=attribute.attcollation
FROM unnest(index_definition.indcollation)
- WITH ORDINALITY AS item(collation, position)
+ WITH ORDINALITY AS item(collation_oid, position)
JOIN unnest(index_definition.indkey)
WITH ORDINALITY AS key(attnum, position)
ON key.position=item.position
@@ -3419,7 +3446,7 @@ def _pg_reject_reserved_index_collisions(
SELECT
named_record.relname AS reserved_name,
namespace.nspname AS reserved_schema,
- named_record.relkind,
+ named_record.relkind::text AS relkind,
index_definition.indexrelid IS NOT NULL AS is_index,
table_namespace.nspname AS table_schema,
table_record.relname AS table_name,
@@ -3530,6 +3557,7 @@ def _pg_index_opclass(table: str, column: str) -> str:
return "float8_ops"
if (table, column) in {
("findings", "false_positive"),
+ ("findings", "validated"),
("rate_limit_events", "blocked"),
}:
return "int4_ops"
diff --git a/tests/integration/test_postgres_migration_portability.py b/tests/integration/test_postgres_migration_portability.py
index 813353b..e6307bd 100644
--- a/tests/integration/test_postgres_migration_portability.py
+++ b/tests/integration/test_postgres_migration_portability.py
@@ -16,6 +16,7 @@ from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
from contextlib import asynccontextmanager, contextmanager
from dataclasses import dataclass, field, replace
from datetime import datetime, timezone
+from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import Any
from uuid import uuid4
@@ -1931,8 +1932,8 @@ async def _postgres_isolation_fingerprint(
SELECT
namespace.nspname AS schema_name,
relation.relname AS relation_name,
- relation.relkind AS relation_kind,
- relation.relpersistence AS persistence
+ relation.relkind::text AS relation_kind,
+ relation.relpersistence::text AS persistence
FROM pg_class AS relation
JOIN pg_namespace AS namespace
ON namespace.oid=relation.relnamespace
@@ -1963,8 +1964,8 @@ async def _postgres_isolation_fingerprint(
default_value.adbin,
default_value.adrelid
) AS default_expression,
- attribute.attidentity AS identity_kind,
- attribute.attgenerated AS generated_kind
+ attribute.attidentity::text AS identity_kind,
+ attribute.attgenerated::text AS generated_kind
FROM pg_attribute AS attribute
JOIN pg_class AS relation
ON relation.oid=attribute.attrelid
@@ -1992,7 +1993,7 @@ async def _postgres_isolation_fingerprint(
namespace.nspname AS schema_name,
relation.relname AS relation_name,
constraint_value.conname AS constraint_name,
- constraint_value.contype AS constraint_type,
+ constraint_value.contype::text AS constraint_type,
pg_get_constraintdef(
constraint_value.oid,
true
@@ -2199,7 +2200,11 @@ def _normalize_postgres_expression(value: str) -> str:
return normalized.replace("(", "").replace(")", "")
-def _postgres_default_kind(value: object) -> str | None:
+def _postgres_default_kind(
+ value: object,
+ *,
+ data_type: str,
+) -> str | None:
if value is None:
return None
normalized = str(value).strip()
@@ -2216,6 +2221,16 @@ def _postgres_default_kind(value: object) -> str | None:
normalized = normalized.strip()
if len(normalized) >= 2 and normalized[0] == normalized[-1] == "'":
normalized = normalized[1:-1].replace("''", "'")
+ if data_type == "double precision":
+ try:
+ numeric = Decimal(normalized)
+ except InvalidOperation:
+ pass
+ else:
+ if numeric.is_finite():
+ normalized = format(numeric, "f")
+ if "." not in normalized:
+ normalized += ".0"
return f"literal:{normalized}"
@@ -2241,7 +2256,10 @@ async def _postgres_catalog_contract(
str(row["column_name"]),
str(row["data_type"]),
str(row["is_nullable"]) == "YES",
- _postgres_default_kind(row["column_default"]),
+ _postgres_default_kind(
+ row["column_default"],
+ data_type=str(row["data_type"]),
+ ),
)
for row in await connection.fetch(
"""
@@ -2270,18 +2288,18 @@ async def _postgres_catalog_contract(
relation.relname AS table_name,
ARRAY(
SELECT attribute.attname
- FROM unnest(constraint.conkey)
+ FROM unnest(constraint_record.conkey)
WITH ORDINALITY AS key(attnum, position)
JOIN pg_attribute AS attribute
- ON attribute.attrelid=constraint.conrelid
+ ON attribute.attrelid=constraint_record.conrelid
AND attribute.attnum=key.attnum
ORDER BY key.position
) AS columns
- FROM pg_constraint AS constraint
+ FROM pg_constraint AS constraint_record
JOIN pg_class AS relation
- ON relation.oid=constraint.conrelid
+ ON relation.oid=constraint_record.conrelid
WHERE relation.relnamespace=current_schema()::regnamespace
- AND constraint.contype='p'
+ AND constraint_record.contype='p'
AND relation.relname <> 'alembic_version'
ORDER BY relation.relname
"""
@@ -2297,22 +2315,22 @@ async def _postgres_catalog_contract(
"""
SELECT
relation.relname AS table_name,
- constraint.conname AS constraint_name,
+ constraint_record.conname AS constraint_name,
ARRAY(
SELECT attribute.attname
- FROM unnest(constraint.conkey)
+ FROM unnest(constraint_record.conkey)
WITH ORDINALITY AS key(attnum, position)
JOIN pg_attribute AS attribute
- ON attribute.attrelid=constraint.conrelid
+ ON attribute.attrelid=constraint_record.conrelid
AND attribute.attnum=key.attnum
ORDER BY key.position
) AS columns
- FROM pg_constraint AS constraint
+ FROM pg_constraint AS constraint_record
JOIN pg_class AS relation
- ON relation.oid=constraint.conrelid
+ ON relation.oid=constraint_record.conrelid
WHERE relation.relnamespace=current_schema()::regnamespace
- AND constraint.contype='u'
- ORDER BY relation.relname, constraint.conname
+ AND constraint_record.contype='u'
+ ORDER BY relation.relname, constraint_record.conname
"""
)
)
@@ -2326,14 +2344,14 @@ async def _postgres_catalog_contract(
"""
SELECT
relation.relname AS table_name,
- constraint.conname AS constraint_name,
- pg_get_constraintdef(constraint.oid) AS definition
- FROM pg_constraint AS constraint
+ constraint_record.conname AS constraint_name,
+ pg_get_constraintdef(constraint_record.oid) AS definition
+ FROM pg_constraint AS constraint_record
JOIN pg_class AS relation
- ON relation.oid=constraint.conrelid
+ ON relation.oid=constraint_record.conrelid
WHERE relation.relnamespace=current_schema()::regnamespace
- AND constraint.contype='c'
- ORDER BY relation.relname, constraint.conname
+ AND constraint_record.contype='c'
+ ORDER BY relation.relname, constraint_record.conname
"""
)
)
@@ -2351,48 +2369,48 @@ async def _postgres_catalog_contract(
"""
SELECT
source.relname AS table_name,
- constraint.conname AS constraint_name,
+ constraint_record.conname AS constraint_name,
ARRAY(
SELECT attribute.attname
- FROM unnest(constraint.conkey)
+ FROM unnest(constraint_record.conkey)
WITH ORDINALITY AS key(attnum, position)
JOIN pg_attribute AS attribute
- ON attribute.attrelid=constraint.conrelid
+ ON attribute.attrelid=constraint_record.conrelid
AND attribute.attnum=key.attnum
ORDER BY key.position
) AS local_columns,
target.relname AS remote_table,
ARRAY(
SELECT attribute.attname
- FROM unnest(constraint.confkey)
+ FROM unnest(constraint_record.confkey)
WITH ORDINALITY AS key(attnum, position)
JOIN pg_attribute AS attribute
- ON attribute.attrelid=constraint.confrelid
+ ON attribute.attrelid=constraint_record.confrelid
AND attribute.attnum=key.attnum
ORDER BY key.position
) AS remote_columns,
- CASE constraint.confupdtype
+ CASE constraint_record.confupdtype
WHEN 'a' THEN 'NO ACTION'
WHEN 'r' THEN 'RESTRICT'
WHEN 'c' THEN 'CASCADE'
WHEN 'n' THEN 'SET NULL'
WHEN 'd' THEN 'SET DEFAULT'
END AS update_action,
- CASE constraint.confdeltype
+ CASE constraint_record.confdeltype
WHEN 'a' THEN 'NO ACTION'
WHEN 'r' THEN 'RESTRICT'
WHEN 'c' THEN 'CASCADE'
WHEN 'n' THEN 'SET NULL'
WHEN 'd' THEN 'SET DEFAULT'
END AS delete_action
- FROM pg_constraint AS constraint
+ FROM pg_constraint AS constraint_record
JOIN pg_class AS source
- ON source.oid=constraint.conrelid
+ ON source.oid=constraint_record.conrelid
JOIN pg_class AS target
- ON target.oid=constraint.confrelid
+ ON target.oid=constraint_record.confrelid
WHERE source.relnamespace=current_schema()::regnamespace
- AND constraint.contype='f'
- ORDER BY source.relname, constraint.conname
+ AND constraint_record.contype='f'
+ ORDER BY source.relname, constraint_record.conname
"""
)
)
@@ -2435,8 +2453,8 @@ async def _postgres_catalog_contract(
ON index_relation.oid=index_catalog.indexrelid
WHERE table_relation.relnamespace=current_schema()::regnamespace
AND NOT EXISTS (
- SELECT 1 FROM pg_constraint AS constraint
- WHERE constraint.conindid=index_catalog.indexrelid
+ SELECT 1 FROM pg_constraint AS constraint_record
+ WHERE constraint_record.conindid=index_catalog.indexrelid
)
ORDER BY table_relation.relname, index_relation.relname
"""
@@ -4681,20 +4699,20 @@ async def test_postgres_0006_catalog_types_defaults_fks_and_indexes() -> None:
source.relname AS source_table,
source_column.attname AS source_column,
target.relname AS target_table,
- CASE constraint.confdeltype
+ CASE constraint_record.confdeltype
WHEN 'c' THEN 'CASCADE'
WHEN 'n' THEN 'SET NULL'
ELSE 'OTHER'
END AS delete_action
- FROM pg_constraint AS constraint
+ FROM pg_constraint AS constraint_record
JOIN pg_class AS source
- ON source.oid=constraint.conrelid
+ ON source.oid=constraint_record.conrelid
JOIN pg_class AS target
- ON target.oid=constraint.confrelid
+ ON target.oid=constraint_record.confrelid
JOIN pg_attribute AS source_column
ON source_column.attrelid=source.oid
- AND source_column.attnum=constraint.conkey[1]
- WHERE constraint.contype='f'
+ AND source_column.attnum=constraint_record.conkey[1]
+ WHERE constraint_record.contype='f'
AND source.relnamespace=current_schema()::regnamespace
"""
)
@@ -4739,12 +4757,13 @@ async def test_postgres_0006_catalog_types_defaults_fks_and_indexes() -> None:
for row in await connection.fetch(
"""
SELECT table_class.relname AS table_name
- FROM pg_constraint AS constraint
+ FROM pg_constraint AS constraint_record
JOIN pg_class AS table_class
- ON table_class.oid=constraint.conrelid
- WHERE constraint.contype='p'
+ ON table_class.oid=constraint_record.conrelid
+ WHERE constraint_record.contype='p'
AND table_class.relnamespace=
current_schema()::regnamespace
+ AND table_class.relname <> 'alembic_version'
"""
)
}
@@ -4839,13 +4858,13 @@ async def test_postgres_all_timestamp_columns_reject_infinity() -> None:
"""
SELECT
relation.relname AS table_name,
- constraint.conname AS constraint_name,
- pg_get_constraintdef(constraint.oid) AS definition
- FROM pg_constraint AS constraint
+ constraint_record.conname AS constraint_name,
+ pg_get_constraintdef(constraint_record.oid) AS definition
+ FROM pg_constraint AS constraint_record
JOIN pg_class AS relation
- ON relation.oid=constraint.conrelid
+ ON relation.oid=constraint_record.conrelid
WHERE relation.relnamespace=current_schema()::regnamespace
- AND constraint.contype='c'
+ AND constraint_record.contype='c'
"""
)
observed_constraints = {
@@ -5365,12 +5384,12 @@ async def test_postgres_0003_blocked_integer_contract_is_enforced() -> None:
)
check_definition = await connection.fetchval(
"""
- SELECT pg_get_constraintdef(constraint.oid)
- FROM pg_constraint AS constraint
+ SELECT pg_get_constraintdef(constraint_record.oid)
+ FROM pg_constraint AS constraint_record
JOIN pg_class AS relation
- ON relation.oid=constraint.conrelid
+ ON relation.oid=constraint_record.conrelid
WHERE relation.relname='rate_limit_events'
- AND constraint.conname='ck_rate_limit_events_blocked_bool'
+ AND constraint_record.conname='ck_rate_limit_events_blocked_bool'
"""
)
check_is_semantic = (
@@ -6199,15 +6218,15 @@ async def _postgres_credential_catalog_fingerprint(
for row in await connection.fetch(
"""
SELECT
- constraint.conname,
- constraint.contype,
- pg_get_constraintdef(constraint.oid)
- FROM pg_constraint AS constraint
+ constraint_record.conname,
+ constraint_record.contype::text AS contype,
+ pg_get_constraintdef(constraint_record.oid)
+ FROM pg_constraint AS constraint_record
JOIN pg_class AS relation
- ON relation.oid=constraint.conrelid
+ ON relation.oid=constraint_record.conrelid
WHERE relation.relnamespace=current_schema()::regnamespace
AND relation.relname='credentials'
- ORDER BY constraint.conname
+ ORDER BY constraint_record.conname
"""
)
)
@@ -6250,6 +6269,15 @@ async def _prepare_postgres_0006_variant(
f'ALTER TABLE credentials DROP COLUMN "{source}"'
)
return
+ if variant == "target-default-null-equivalent":
+ await connection.execute(
+ f'ALTER TABLE credentials DROP COLUMN "{source}"'
+ )
+ await connection.execute(
+ f'ALTER TABLE credentials ADD COLUMN "{target}" '
+ "TEXT DEFAULT NULL"
+ )
+ return
if variant.startswith("wrong-target-"):
await connection.execute(
f'ALTER TABLE credentials DROP COLUMN "{source}"'
@@ -6259,8 +6287,6 @@ async def _prepare_postgres_0006_variant(
definition = "VARCHAR(64)"
elif variant.endswith("-nullability"):
definition = "TEXT NOT NULL"
- elif variant.endswith("-default-null"):
- definition = "TEXT DEFAULT NULL"
elif variant.endswith("-default"):
definition = "TEXT DEFAULT ''::text"
else:
@@ -6269,6 +6295,12 @@ async def _prepare_postgres_0006_variant(
f'ALTER TABLE credentials ADD COLUMN "{inspected}" {definition}'
)
return
+ if variant == "source-default-null-equivalent":
+ await connection.execute(
+ f'ALTER TABLE credentials ALTER COLUMN "{source}" '
+ "SET DEFAULT NULL"
+ )
+ return
if variant.startswith("wrong-source-"):
if variant.endswith("-type"):
await connection.execute(
@@ -6279,11 +6311,6 @@ async def _prepare_postgres_0006_variant(
await connection.execute(
f'ALTER TABLE credentials ALTER COLUMN "{source}" SET NOT NULL'
)
- elif variant.endswith("-default-null"):
- await connection.execute(
- f'ALTER TABLE credentials ALTER COLUMN "{source}" '
- "SET DEFAULT NULL"
- )
elif variant.endswith("-default"):
await connection.execute(
f'ALTER TABLE credentials ALTER COLUMN "{source}" '
@@ -6307,11 +6334,11 @@ async def _prepare_postgres_0006_variant(
"wrong-source-type",
"wrong-source-nullability",
"wrong-source-default",
- "wrong-source-default-null",
+ "source-default-null-equivalent",
"wrong-target-type",
"wrong-target-nullability",
"wrong-target-default",
- "wrong-target-default-null",
+ "target-default-null-equivalent",
],
)
async def test_postgres_0006_exact_column_state_machine(
@@ -6423,6 +6450,17 @@ async def test_postgres_0006_exact_column_state_machine(
""",
target,
)
+ current_credential_columns = {
+ str(row["column_name"])
+ for row in await connection.fetch(
+ """
+ SELECT column_name
+ FROM information_schema.columns
+ WHERE table_schema=current_schema()
+ AND table_name='credentials'
+ """
+ )
+ }
target_is_exact = (
target_definition is not None
and target_definition["data_type"] == "text"
@@ -6430,7 +6468,7 @@ async def test_postgres_0006_exact_column_state_machine(
and target_definition["is_nullable"] == "YES"
and target_definition["column_default"] is None
)
- if target == "cracked_value_enc":
+ if "cracked_value_enc" in current_credential_columns:
preserved = (
await connection.fetchval(
"""
@@ -6440,7 +6478,7 @@ async def test_postgres_0006_exact_column_state_machine(
)
== 1
)
- else:
+ elif "cracked_value" in current_credential_columns:
preserved = (
await connection.fetchval(
"""
@@ -6450,12 +6488,19 @@ async def test_postgres_0006_exact_column_state_machine(
)
== 1
)
+ else:
+ preserved = True
current_revision = await _version(connection)
reusable = await connection.fetchval("SELECT 1") == 1
finally:
await connection.close()
- allowed = variant in {"source-only", "target-only"}
+ allowed = variant in {
+ "source-only",
+ "target-only",
+ "source-default-null-equivalent",
+ "target-default-null-equivalent",
+ }
if allowed:
_require_fixed(
not failed
@@ -6467,10 +6512,22 @@ async def test_postgres_0006_exact_column_state_machine(
)
else:
_require_fixed(
- failed
- and current_revision == parent_revision
- and before_catalog == after_catalog
- and before_rows == after_rows
- and reusable,
- "PostgreSQL revision 0006 changed an incompatible catalog",
+ failed,
+ "PostgreSQL revision 0006 accepted an incompatible catalog",
+ )
+ _require_fixed(
+ current_revision == parent_revision,
+ "PostgreSQL revision 0006 changed an incompatible revision",
+ )
+ _require_fixed(
+ before_catalog == after_catalog,
+ "PostgreSQL revision 0006 changed an incompatible schema",
+ )
+ _require_fixed(
+ before_rows == after_rows,
+ "PostgreSQL revision 0006 changed incompatible rows",
+ )
+ _require_fixed(
+ reusable,
+ "PostgreSQL revision 0006 left connection unusable",
)
diff --git a/tests/integration/test_postgres_runtime_smoke.py b/tests/integration/test_postgres_runtime_smoke.py
index 6ddb2b8..04f3069 100644
--- a/tests/integration/test_postgres_runtime_smoke.py
+++ b/tests/integration/test_postgres_runtime_smoke.py
@@ -784,9 +784,13 @@ def test_postgres_ticket_census_all_zero_and_closed_rendering() -> None:
def test_postgres_q78_operation_and_failure_contract_is_closed() -> None:
+ import inspect
+
from ares.db.postgres import (
_POSTGRES_Q78_OPERATION_BITS,
+ _POSTGRES_Q78_SPLIT_INDEX_QUERY,
_POSTGRES_Q78_SUBPHASES,
+ PostgresDatabase,
_is_postgres_q78_failure,
_postgres_q78_failure,
)
@@ -801,6 +805,86 @@ def test_postgres_q78_operation_and_failure_contract_is_closed() -> None:
operation_map_is_exact,
"q78 must map exactly to its four source operations",
)
+ production_source = inspect.getsource(
+ PostgresDatabase._validate_websocket_ticket_schema
+ )
+ managed_revision_source = inspect.getsource(
+ PostgresDatabase._managed_schema_revision
+ )
+ managed_schema_source = inspect.getsource(
+ PostgresDatabase._validate_managed_schema
+ )
+ managed_constraints_source = inspect.getsource(
+ PostgresDatabase._validate_managed_constraints
+ )
+ managed_serials_source = inspect.getsource(
+ PostgresDatabase._validate_managed_serials
+ )
+ managed_source = "\n".join(
+ (
+ managed_revision_source,
+ managed_schema_source,
+ managed_constraints_source,
+ managed_serials_source,
+ )
+ )
+ syntax_is_portable = (
+ "item(collation, ordinality)" not in _POSTGRES_Q78_SPLIT_INDEX_QUERY
+ and "item(collation, ordinality)" not in production_source
+ and "item(collation_oid, ordinality)"
+ in _POSTGRES_Q78_SPLIT_INDEX_QUERY
+ and "item(collation_oid, ordinality)" in production_source
+ )
+ _require_fixed(
+ syntax_is_portable,
+ "q78 index queries must not use a reserved alias",
+ )
+ managed_syntax_is_portable = (
+ "item(collation, position)" not in managed_source
+ and managed_source.count("item(collation_oid, position)") == 3
+ )
+ _require_fixed(
+ managed_syntax_is_portable,
+ "Managed index queries must not use a reserved alias",
+ )
+ catalog_codecs_are_explicit = (
+ "idx.relkind::text AS index_relkind"
+ in _POSTGRES_Q78_SPLIT_INDEX_QUERY
+ and "idx.relpersistence::text AS index_relpersistence"
+ in _POSTGRES_Q78_SPLIT_INDEX_QUERY
+ and "idx.relkind::text AS index_relkind" in production_source
+ and "idx.relpersistence::text AS index_relpersistence"
+ in production_source
+ and "att.attidentity::text AS attidentity" in production_source
+ and "att.attgenerated::text AS attgenerated" in production_source
+ and "con.contype::text AS contype" in production_source
+ and "con.confupdtype::text AS confupdtype" in production_source
+ and "con.confdeltype::text AS confdeltype" in production_source
+ )
+ _require_fixed(
+ catalog_codecs_are_explicit,
+ "PostgreSQL internal catalog codes require explicit text projections",
+ )
+ managed_catalog_codecs_are_explicit = all(
+ projection in managed_source
+ for projection in (
+ "rel.relkind::text AS relkind",
+ "rel.relpersistence::text AS relpersistence",
+ "index_rel.relkind::text AS index_relkind",
+ "index_rel.relpersistence::text AS index_relpersistence",
+ "con.contype::text AS contype",
+ "con.confupdtype::text AS confupdtype",
+ "con.confdeltype::text AS confdeltype",
+ "sequence_rel.relkind::text AS relkind",
+ "sequence_rel.relpersistence::text AS relpersistence",
+ "owner_att.attidentity::text AS attidentity",
+ "owner_att.attgenerated::text AS attgenerated",
+ )
+ )
+ _require_fixed(
+ managed_catalog_codecs_are_explicit,
+ "Managed catalog codes require explicit text projections",
+ )
subphases_are_distinct = True
for subphase in _POSTGRES_Q78_SUBPHASES:
rendered = _postgres_q78_failure(
@@ -941,6 +1025,29 @@ async def test_postgres_q78_cancellation_propagates() -> None:
)
+def test_postgres_managed_constraint_identifier_normalization() -> None:
+ from ares.db.postgres import _postgres_constraint_definition
+
+ unquoted = _postgres_constraint_definition(
+ "CHECK (isfinite(timestamp))"
+ )
+ quoted_lowercase = _postgres_constraint_definition(
+ 'CHECK (isfinite("timestamp"))'
+ )
+ quoted_case_sensitive = _postgres_constraint_definition(
+ 'CHECK (isfinite("Timestamp"))'
+ )
+
+ _require_fixed(
+ quoted_lowercase == unquoted,
+ "managed constraint lowercase identifier normalization changed",
+ )
+ _require_fixed(
+ quoted_case_sensitive != unquoted,
+ "managed constraint case-sensitive identifier was weakened",
+ )
+
+
def test_postgres_ticket_column_census_distinguishes_every_dimension() -> None:
from ares.db.postgres import _postgres_ticket_column_census
diff --git a/tests/integration/test_postgres_schema_reconciliation.py b/tests/integration/test_postgres_schema_reconciliation.py
index c34142d..7742231 100644
--- a/tests/integration/test_postgres_schema_reconciliation.py
+++ b/tests/integration/test_postgres_schema_reconciliation.py
@@ -1492,6 +1492,20 @@ async def test_real_postgres_managed_startup_preserves_unrelated_objects(
)
finally:
await connection.close()
+ await harness._alembic(target, "upgrade", "0007")
+ connection = await harness._connect(target)
+ try:
+ at_0007 = bool(
+ await connection.fetchval(
+ "SELECT version_num='0007' FROM alembic_version"
+ )
+ )
+ finally:
+ await connection.close()
+ _require_fixed(
+ at_0007,
+ "Managed-startup fixture must reach revision 0007 before 0008",
+ )
await harness._alembic(target, "upgrade", "0008")
connection = await harness._connect(target)
try:
@@ -1833,7 +1847,10 @@ async def test_real_postgres_managed_catalog_drift_never_falls_back(
"wrong-sequence-owner-schema": (
"CREATE SCHEMA ares_runtime_shadow; "
"CREATE TABLE ares_runtime_shadow.audit_log(id INTEGER NOT NULL); "
+ "ALTER SEQUENCE audit_log_id_seq OWNED BY NONE; "
"ALTER SEQUENCE audit_log_id_seq "
+ "SET SCHEMA ares_runtime_shadow; "
+ "ALTER SEQUENCE ares_runtime_shadow.audit_log_id_seq "
"OWNED BY ares_runtime_shadow.audit_log.id"
),
"wrong-sequence-options": (
@@ -2930,7 +2947,10 @@ async def _apply_column_or_relation_mutation(
CREATE TABLE ares_m0008_shadow.audit_log(
id INTEGER NOT NULL
);
+ ALTER SEQUENCE audit_log_id_seq OWNED BY NONE;
ALTER SEQUENCE audit_log_id_seq
+ SET SCHEMA ares_m0008_shadow;
+ ALTER SEQUENCE ares_m0008_shadow.audit_log_id_seq
OWNED BY ares_m0008_shadow.audit_log.id
"""
)
@@ -3608,6 +3628,11 @@ async def test_real_postgres_invalid_integer_boolean_is_atomic(
connection = await harness._connect(target)
try:
await harness._seed_postgres_contract(connection)
+ if boolean_mutation == "rate-blocked":
+ await connection.execute(
+ "ALTER TABLE rate_limit_events "
+ "DROP CONSTRAINT ck_rate_limit_events_blocked_bool"
+ )
await connection.execute(
f'UPDATE "{table}" SET "{column}"=2' # noqa: S608
)
@@ -3742,11 +3767,15 @@ async def test_real_postgres_all_managed_timestamps_enforce_finite_values(
if catalog is not None
else ""
)
- expected_term = f"isfinite({column})"
+ catalog_column = (
+ f'"{column}"' if column == "timestamp" else column
+ )
+ expected_term = f"isfinite({catalog_column})"
catalog_valid = expected_term in definition
if nullable:
catalog_valid = (
- catalog_valid and f"{column}isnull" in definition
+ catalog_valid
+ and f"{catalog_column}isnull" in definition
)
finite_update = await connection.execute(
diff --git a/tests/integration/test_postgres_websocket_tickets.py b/tests/integration/test_postgres_websocket_tickets.py
index ea70dd4..56c4483 100644
--- a/tests/integration/test_postgres_websocket_tickets.py
+++ b/tests/integration/test_postgres_websocket_tickets.py
@@ -990,8 +990,8 @@ async def _ticket_catalog_fingerprint(connection: Any) -> dict[str, object]:
SELECT rel.oid::bigint AS table_oid,
nsp.oid::bigint AS schema_oid,
nsp.nspname AS schema_name,
- rel.relkind,
- rel.relpersistence,
+ rel.relkind::text AS relkind,
+ rel.relpersistence::text AS relpersistence,
rel.relispartition,
rel.relrowsecurity,
rel.relforcerowsecurity,
@@ -1031,8 +1031,8 @@ async def _ticket_catalog_fingerprint(connection: Any) -> dict[str, object]:
SELECT att.attname AS name,
pg_catalog.format_type(att.atttypid, att.atttypmod) AS type,
att.attnotnull,
- att.attidentity,
- att.attgenerated,
+ att.attidentity::text AS attidentity,
+ att.attgenerated::text AS attgenerated,
att.attcollation=typ.typcollation AS collation_is_default,
pg_get_expr(def.adbin, def.adrelid) AS default_value
FROM pg_attribute AS att
@@ -1048,7 +1048,7 @@ async def _ticket_catalog_fingerprint(connection: Any) -> dict[str, object]:
)
constraint_rows = await connection.fetch(
"""
- SELECT con.conname, con.contype,
+ SELECT con.conname, con.contype::text AS contype,
con.conrelid::bigint AS table_oid,
con.confrelid::bigint AS referenced_oid,
con.conindid::bigint AS constraint_index_oid,
@@ -1074,7 +1074,8 @@ async def _ticket_catalog_fingerprint(connection: Any) -> dict[str, object]:
AND remote_att.attnum=key.attnum
ORDER BY key.ordinality
) AS remote_columns,
- con.confupdtype, con.confdeltype
+ con.confupdtype::text AS confupdtype,
+ con.confdeltype::text AS confdeltype
FROM pg_constraint AS con
LEFT JOIN pg_class AS ref_rel ON ref_rel.oid=con.confrelid
LEFT JOIN pg_namespace AS ref_nsp ON ref_nsp.oid=ref_rel.relnamespace
@@ -1090,8 +1091,8 @@ async def _ticket_catalog_fingerprint(connection: Any) -> dict[str, object]:
idx.relnamespace::bigint AS index_schema_oid,
idx_nsp.nspname=current_schema() AS index_schema_is_local,
idx.relname AS name,
- idx.relkind,
- idx.relpersistence,
+ idx.relkind::text AS relkind,
+ idx.relpersistence::text AS relpersistence,
idx.relispartition,
am.amname,
ind.indisunique, ind.indisprimary,
@@ -1130,9 +1131,9 @@ async def _ticket_catalog_fingerprint(connection: Any) -> dict[str, object]:
ORDER BY item.ordinality
) AS opclass_namespaces,
ARRAY(
- SELECT item.collation=att.attcollation
+ SELECT item.collation_oid=att.attcollation
FROM unnest(ind.indcollation) WITH ORDINALITY
- AS item(collation, ordinality)
+ AS item(collation_oid, ordinality)
JOIN unnest(ind.indkey) WITH ORDINALITY
AS key(attnum, ordinality)
ON key.ordinality=item.ordinality
@@ -1618,22 +1619,22 @@ async def test_postgres_ticket_timestamps_reject_both_infinities() -> None:
for statement in (
"""
UPDATE websocket_tickets
- SET bearer_expires_at=$2::timestamptz
+ SET bearer_expires_at=$2::text::timestamptz
WHERE ticket_hash=$1
""",
"""
UPDATE websocket_tickets
- SET created_at=$2::timestamptz
+ SET created_at=$2::text::timestamptz
WHERE ticket_hash=$1
""",
"""
UPDATE websocket_tickets
- SET expires_at=$2::timestamptz
+ SET expires_at=$2::text::timestamptz
WHERE ticket_hash=$1
""",
"""
UPDATE websocket_tickets
- SET consumed_at=$2::timestamptz
+ SET consumed_at=$2::text::timestamptz
WHERE ticket_hash=$1
""",
):
@@ -3238,6 +3239,8 @@ async def test_postgres_revision_0007_ownership_and_0008_compatibility(
@pytest.mark.asyncio
async def test_postgres_partial_ticket_schema_fails_clearly() -> None:
+ from ares.db.postgres import _PostgresStartupDiagnosticError
+
async with _postgres_harness() as harness:
database = harness.database
async with database._pool.acquire() as connection:
@@ -3263,11 +3266,20 @@ async def test_postgres_partial_ticket_schema_fails_clearly() -> None:
after_failure = await _ticket_catalog_fingerprint(connection)
reusable = await connection.fetchval("SELECT 1")
_require_fixed(
- failure_type is RuntimeError
- and failure_message_is_fixed
- and incompatible == after_failure
- and reusable == 1,
- "partial PostgreSQL ticket schema did not fail clearly",
+ failure_type is _PostgresStartupDiagnosticError,
+ "partial PostgreSQL ticket schema failure type changed",
+ )
+ _require_fixed(
+ failure_message_is_fixed,
+ "partial PostgreSQL ticket schema failure message changed",
+ )
+ _require_fixed(
+ incompatible == after_failure,
+ "partial PostgreSQL ticket schema mutated after rejection",
+ )
+ _require_fixed(
+ reusable == 1,
+ "partial PostgreSQL ticket schema connection was not reusable",
)
@@ -3426,6 +3438,8 @@ async def test_postgres_partial_ticket_schema_fails_clearly() -> None:
async def test_postgres_validator_rejects_near_compatible_catalogs(
mutation: str,
) -> None:
+ from ares.db.postgres import _PostgresStartupDiagnosticError
+
async with _postgres_harness() as harness:
database = harness.database
async with database._pool.acquire() as connection:
@@ -3444,7 +3458,7 @@ async def test_postgres_validator_rejects_near_compatible_catalogs(
after_failure = await _ticket_catalog_fingerprint(connection)
reusable = await connection.fetchval("SELECT 1")
_require_fixed(
- failure_type is RuntimeError
+ failure_type is _PostgresStartupDiagnosticError
and fixed_message
and incompatible == after_failure
and reusable == 1,
@@ -3872,6 +3886,8 @@ async def _ticket_rows_for_metadata_mutation(
async def test_postgres_rejects_security_altering_relation_metadata(
mutation: str,
) -> None:
+ from ares.db.postgres import _PostgresStartupDiagnosticError
+
async with _postgres_harness() as harness:
database = harness.database
user_id, username, campaign_id, _other_id, _key_id = (
@@ -3992,7 +4008,7 @@ async def test_postgres_rejects_security_altering_relation_metadata(
_require_fixed(
mutation_exists
and trigger_would_enable_replay
- and failure_type is RuntimeError
+ and failure_type is _PostgresStartupDiagnosticError
and fixed_message
and pool_was_cleared
and startup_preserved_state