|
| 1 | +# tests/rhosocial/activerecord_postgres_test/feature/backend/postgres/ |
| 2 | +# test_postgres_seconds_between.py |
| 3 | +"""Signed, fractional seconds between two instants on PostgreSQL. |
| 4 | +
|
| 5 | +What matters here is what a calendar-component sum gets wrong: the sign, |
| 6 | +the zero, the fraction, and the boundaries where a month or a year changes. |
| 7 | +``EXTRACT(EPOCH FROM (end - start))`` is a ``numeric``, so the value keeps the |
| 8 | +microseconds PostgreSQL stores and turns negative when the end is earlier. |
| 9 | +""" |
| 10 | + |
| 11 | +import pytest |
| 12 | + |
| 13 | +from rhosocial.activerecord.backend.expression import ( |
| 14 | + Column, |
| 15 | + Literal, |
| 16 | + QueryStatement, |
| 17 | + seconds_between, |
| 18 | +) |
| 19 | +from rhosocial.activerecord.backend.expression.datetime import SecondsBetweenExpression |
| 20 | +from rhosocial.activerecord.backend.expression.value_types import NumericValue |
| 21 | +from rhosocial.activerecord.backend.options import ExecutionOptions |
| 22 | +from rhosocial.activerecord.backend.schema import StatementType |
| 23 | + |
| 24 | +_SPANS = [ |
| 25 | + ("2026-06-04 10:00:00", "2026-06-04 10:00:00", 0.0), |
| 26 | + ("2026-06-04 10:00:00", "2026-06-04 11:00:00", 3600.0), |
| 27 | + ("2026-06-04 11:00:00", "2026-06-04 10:00:00", -3600.0), |
| 28 | + ("2026-01-31 23:59:59", "2026-02-01 00:00:00", 1.0), |
| 29 | + ("2025-12-31 12:00:00", "2026-01-01 12:00:00", 86400.0), |
| 30 | + ("2026-06-04 10:00:00.000", "2026-06-04 10:00:00.500", 0.5), |
| 31 | + ("2026-06-04 10:00:00.250", "2026-06-04 10:00:00.000", -0.25), |
| 32 | +] |
| 33 | + |
| 34 | +_TABLE = "postgres_seconds_between_spans" |
| 35 | + |
| 36 | + |
| 37 | +def _setup_statements() -> list: |
| 38 | + statements = [f"DROP TABLE IF EXISTS {_TABLE} CASCADE"] |
| 39 | + statements.append( |
| 40 | + f""" |
| 41 | + CREATE TABLE {_TABLE} ( |
| 42 | + id INTEGER PRIMARY KEY, |
| 43 | + started_at TIMESTAMP NOT NULL, |
| 44 | + ended_at TIMESTAMP NOT NULL |
| 45 | + ) |
| 46 | + """ |
| 47 | + ) |
| 48 | + for index, (start, end, _) in enumerate(_SPANS, start=1): |
| 49 | + statements.append( |
| 50 | + f"INSERT INTO {_TABLE} (id, started_at, ended_at) VALUES " |
| 51 | + f"({index}, TIMESTAMP '{start}', TIMESTAMP '{end}')" |
| 52 | + ) |
| 53 | + return statements |
| 54 | + |
| 55 | + |
| 56 | +_CLEANUP = f"DROP TABLE IF EXISTS {_TABLE} CASCADE" |
| 57 | +_DQL_OPTIONS = ExecutionOptions(stmt_type=StatementType.DQL) |
| 58 | + |
| 59 | + |
| 60 | +def _seconds_query(dialect) -> QueryStatement: |
| 61 | + return QueryStatement( |
| 62 | + dialect, |
| 63 | + select=[ |
| 64 | + seconds_between( |
| 65 | + dialect, |
| 66 | + Column(dialect, "started_at"), |
| 67 | + Column(dialect, "ended_at"), |
| 68 | + ).as_("seconds"), |
| 69 | + Column(dialect, "id"), |
| 70 | + ], |
| 71 | + from_=_TABLE, |
| 72 | + ) |
| 73 | + |
| 74 | + |
| 75 | +class TestPostgresSecondsBetweenExpression: |
| 76 | + """The SQL PostgreSQL renders for the node.""" |
| 77 | + |
| 78 | + def test_columns(self, postgres_dialect): |
| 79 | + expr = seconds_between( |
| 80 | + postgres_dialect, |
| 81 | + Column(postgres_dialect, "started_at"), |
| 82 | + Column(postgres_dialect, "ended_at"), |
| 83 | + ) |
| 84 | + |
| 85 | + sql, params = expr.to_sql() |
| 86 | + |
| 87 | + assert sql == 'EXTRACT(EPOCH FROM ("ended_at" - "started_at"))' |
| 88 | + assert params == () |
| 89 | + |
| 90 | + def test_literal_params_follow_sql_order(self, postgres_dialect): |
| 91 | + expr = seconds_between( |
| 92 | + postgres_dialect, |
| 93 | + Literal(postgres_dialect, "2026-01-01 00:00:00"), |
| 94 | + Literal(postgres_dialect, "2026-01-02 00:00:00"), |
| 95 | + ) |
| 96 | + |
| 97 | + sql, params = expr.to_sql() |
| 98 | + |
| 99 | + assert sql == "EXTRACT(EPOCH FROM (%s - %s))" |
| 100 | + # ``end`` is written first, so its parameter binds first. |
| 101 | + assert params == ("2026-01-02 00:00:00", "2026-01-01 00:00:00") |
| 102 | + |
| 103 | + def test_factory_coerces_string_to_column(self, postgres_dialect): |
| 104 | + expr = seconds_between(postgres_dialect, "started_at", "ended_at") |
| 105 | + |
| 106 | + sql, params = expr.to_sql() |
| 107 | + |
| 108 | + assert sql == 'EXTRACT(EPOCH FROM ("ended_at" - "started_at"))' |
| 109 | + assert params == () |
| 110 | + |
| 111 | + def test_alias(self, postgres_dialect): |
| 112 | + expr = seconds_between( |
| 113 | + postgres_dialect, |
| 114 | + Column(postgres_dialect, "started_at"), |
| 115 | + Column(postgres_dialect, "ended_at"), |
| 116 | + ).as_("elapsed") |
| 117 | + |
| 118 | + sql, params = expr.to_sql() |
| 119 | + |
| 120 | + assert sql == ( |
| 121 | + 'EXTRACT(EPOCH FROM ("ended_at" - "started_at")) AS "elapsed"' |
| 122 | + ) |
| 123 | + assert params == () |
| 124 | + |
| 125 | + def test_is_a_signed_fractional_number(self, postgres_dialect): |
| 126 | + expr = seconds_between( |
| 127 | + postgres_dialect, |
| 128 | + Column(postgres_dialect, "started_at"), |
| 129 | + Column(postgres_dialect, "ended_at"), |
| 130 | + ) |
| 131 | + |
| 132 | + assert isinstance(expr, SecondsBetweenExpression) |
| 133 | + assert isinstance(expr, NumericValue) |
| 134 | + assert expr.format_method == "format_seconds_between_expression" |
| 135 | + |
| 136 | + def test_query_integration(self, postgres_dialect): |
| 137 | + query = QueryStatement( |
| 138 | + postgres_dialect, |
| 139 | + select=[ |
| 140 | + seconds_between( |
| 141 | + postgres_dialect, |
| 142 | + Column(postgres_dialect, "started_at"), |
| 143 | + Column(postgres_dialect, "ended_at"), |
| 144 | + ).as_("seconds") |
| 145 | + ], |
| 146 | + from_="spans", |
| 147 | + ) |
| 148 | + |
| 149 | + sql, params = query.to_sql() |
| 150 | + |
| 151 | + assert 'EXTRACT(EPOCH FROM ("ended_at" - "started_at")) AS "seconds"' in sql |
| 152 | + assert params == () |
| 153 | + |
| 154 | + |
| 155 | +class TestSyncPostgresSecondsBetweenExecution: |
| 156 | + """The value the PostgreSQL spelling actually produces.""" |
| 157 | + |
| 158 | + def test_signed_fractional_semantics(self, postgres_backend_single): |
| 159 | + backend = postgres_backend_single |
| 160 | + try: |
| 161 | + for statement in _setup_statements(): |
| 162 | + backend.execute(statement) |
| 163 | + |
| 164 | + query = _seconds_query(backend.dialect) |
| 165 | + sql, params = query.to_sql() |
| 166 | + result = backend.execute(sql, params, options=_DQL_OPTIONS) |
| 167 | + |
| 168 | + rows = {row["id"]: row["seconds"] for row in result.data} |
| 169 | + for index, (_, _, expected) in enumerate(_SPANS, start=1): |
| 170 | + assert float(rows[index]) == pytest.approx(expected, abs=1e-6) |
| 171 | + finally: |
| 172 | + backend.execute(_CLEANUP) |
| 173 | + |
| 174 | + |
| 175 | +class TestAsyncPostgresSecondsBetweenExecution: |
| 176 | + """The same value asked through the async backend.""" |
| 177 | + |
| 178 | + @pytest.mark.asyncio |
| 179 | + async def test_signed_fractional_semantics( |
| 180 | + self, async_postgres_backend_single |
| 181 | + ): |
| 182 | + backend = async_postgres_backend_single |
| 183 | + try: |
| 184 | + for statement in _setup_statements(): |
| 185 | + await backend.execute(statement) |
| 186 | + |
| 187 | + query = _seconds_query(backend.dialect) |
| 188 | + sql, params = query.to_sql() |
| 189 | + result = await backend.execute(sql, params, options=_DQL_OPTIONS) |
| 190 | + |
| 191 | + rows = {row["id"]: row["seconds"] for row in result.data} |
| 192 | + for index, (_, _, expected) in enumerate(_SPANS, start=1): |
| 193 | + assert float(rows[index]) == pytest.approx(expected, abs=1e-6) |
| 194 | + finally: |
| 195 | + await backend.execute(_CLEANUP) |
0 commit comments