LSST Applications g0603fd7c41+501e3db9f9,g0aad566f14+23d8574c86,g0dd44d6229+a1a4c8b791,g2079a07aa2+86d27d4dc4,g2305ad1205+a62672bbc1,g2bbee38e9b+047b288a59,g337abbeb29+047b288a59,g33d1c0ed96+047b288a59,g3a166c0a6a+047b288a59,g3d1719c13e+23d8574c86,g487adcacf7+cb7fd919b2,g4be5004598+23d8574c86,g50ff169b8f+96c6868917,g52b1c1532d+585e252eca,g591dd9f2cf+4a9e435310,g63cd9335cc+585e252eca,g858d7b2824+23d8574c86,g88963caddf+0cb8e002cc,g99cad8db69+43388bcaec,g9ddcbc5298+9a081db1e4,ga1e77700b3+a912195c07,gae0086650b+585e252eca,gb0e22166c9+60f28cb32d,gb2522980b2+793639e996,gb3a676b8dc+b4feba26a1,gb4b16eec92+63f8520565,gba4ed39666+c2a2e4ac27,gbb8dafda3b+a5d255a82e,gc120e1dc64+d820f8acdb,gc28159a63d+047b288a59,gc3e9b769f7+f4f1cc6b50,gcf0d15dbbd+a1a4c8b791,gdaeeff99f8+f9a426f77a,gdb0af172c8+b6d5496702,ge79ae78c31+047b288a59,w.2024.19
LSST Data Management Base Package
Loading...
Searching...
No Matches
apdbSqlReplica.py
Go to the documentation of this file.
1# This file is part of dax_apdb.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
21
22"""Module defining Apdb class and related methods.
23"""
24
25from __future__ import annotations
26
27__all__ = ["ApdbSqlReplica"]
28
29import logging
30from collections.abc import Collection, Iterable, Mapping, Sequence
31from typing import TYPE_CHECKING, cast
32
33import astropy.time
34import sqlalchemy
35from sqlalchemy import sql
36
37from ..apdbReplica import ApdbReplica, ApdbTableData, ReplicaChunk
38from ..apdbSchema import ApdbTables
39from ..monitor import MonAgent
40from ..timer import Timer
41from ..versionTuple import VersionTuple
42from .apdbSqlSchema import ExtraTables
43
44if TYPE_CHECKING:
45 from .apdbSqlSchema import ApdbSqlSchema
46
47
48_LOG = logging.getLogger(__name__)
49
50_MON = MonAgent(__name__)
51
52VERSION = VersionTuple(1, 0, 0)
53"""Version for the code controlling replication tables. This needs to be
54updated following compatibility rules when schema produced by this code
55changes.
56"""
57
58
60 """Implementation of ApdbTableData that wraps sqlalchemy Result."""
61
62 def __init__(self, result: sqlalchemy.engine.Result):
63 self._keys = list(result.keys())
64 self._rows: list[tuple] = cast(list[tuple], list(result.fetchall()))
65
66 def column_names(self) -> Sequence[str]:
67 return self._keys
68
69 def rows(self) -> Collection[tuple]:
70 return self._rows
71
72
74 """Implementation of `ApdbReplica` for SQL backend.
75
76 Parameters
77 ----------
78 schema : `ApdbSqlSchema`
79 Instance of `ApdbSqlSchema` class for APDB database.
80 engine : `sqlalchemy.engine.Engine`
81 Engine for database access.
82 timer : `bool`, optional
83 If `True` then log timing information.
84 """
85
86 def __init__(self, schema: ApdbSqlSchema, engine: sqlalchemy.engine.Engine, timer: bool = False):
87 self._schema = schema
88 self._engine = engine
89
90 self._timer_args: list[MonAgent | logging.Logger] = [_MON]
91 if timer:
92 self._timer_args.append(_LOG)
93
94 def _timer(self, name: str, *, tags: Mapping[str, str | int] | None = None) -> Timer:
95 """Create `Timer` instance given its name."""
96 return Timer(name, *self._timer_args, tags=tags)
97
98 @classmethod
99 def apdbReplicaImplementationVersion(cls) -> VersionTuple:
100 # Docstring inherited from base class.
101 return VERSION
102
103 def getReplicaChunks(self) -> list[ReplicaChunk] | None:
104 # docstring is inherited from a base class
105 if not self._schema.has_replica_chunks:
106 return None
107
108 table = self._schema.get_table(ExtraTables.ApdbReplicaChunks)
109 assert table is not None, "has_replica_chunks=True means it must be defined"
110 query = sql.select(
111 table.columns["apdb_replica_chunk"], table.columns["last_update_time"], table.columns["unique_id"]
112 ).order_by(table.columns["last_update_time"])
113 with self._timer("chunks_select_time"):
114 with self._engine.connect() as conn:
115 result = conn.execution_options(stream_results=True, max_row_buffer=10000).execute(query)
116 ids = []
117 for row in result:
118 last_update_time = astropy.time.Time(row[1].timestamp(), format="unix_tai")
119 ids.append(ReplicaChunk(id=row[0], last_update_time=last_update_time, unique_id=row[2]))
120 return ids
121
122 def deleteReplicaChunks(self, chunks: Iterable[int]) -> None:
123 # docstring is inherited from a base class
124 if not self._schema.has_replica_chunks:
125 raise ValueError("APDB is not configured for replication")
126
127 table = self._schema.get_table(ExtraTables.ApdbReplicaChunks)
128 where_clause = table.columns["apdb_replica_chunk"].in_(chunks)
129 stmt = table.delete().where(where_clause)
130 with self._timer("chunks_delete_time"):
131 with self._engine.begin() as conn:
132 conn.execute(stmt)
133
134 def getDiaObjectsChunks(self, chunks: Iterable[int]) -> ApdbTableData:
135 # docstring is inherited from a base class
136 return self._get_chunks(chunks, ApdbTables.DiaObject, ExtraTables.DiaObjectChunks)
137
138 def getDiaSourcesChunks(self, chunks: Iterable[int]) -> ApdbTableData:
139 # docstring is inherited from a base class
140 return self._get_chunks(chunks, ApdbTables.DiaSource, ExtraTables.DiaSourceChunks)
141
142 def getDiaForcedSourcesChunks(self, chunks: Iterable[int]) -> ApdbTableData:
143 # docstring is inherited from a base class
144 return self._get_chunks(chunks, ApdbTables.DiaForcedSource, ExtraTables.DiaForcedSourceChunks)
145
147 self,
148 chunks: Iterable[int],
149 table_enum: ApdbTables,
150 chunk_table_enum: ExtraTables,
151 ) -> ApdbTableData:
152 """Return catalog of records for given insert identifiers, common
153 implementation for all DIA tables.
154 """
155 if not self._schema.has_replica_chunks:
156 raise ValueError("APDB is not configured for replication")
157
158 table = self._schema.get_table(table_enum)
159 chunk_table = self._schema.get_table(chunk_table_enum)
160
161 join = table.join(chunk_table)
162 chunk_id_column = chunk_table.columns["apdb_replica_chunk"]
163 apdb_columns = self._schema.get_apdb_columns(table_enum)
164 where_clause = chunk_id_column.in_(chunks)
165 query = sql.select(chunk_id_column, *apdb_columns).select_from(join).where(where_clause)
166
167 # execute select
168 with self._timer("table_chunk_select_time", tags={"table": table.name}):
169 with self._engine.begin() as conn:
170 result = conn.execution_options(stream_results=True, max_row_buffer=10000).execute(query)
171 return ApdbSqlTableData(result)
list[ReplicaChunk]|None getReplicaChunks(self)
ApdbTableData getDiaSourcesChunks(self, Iterable[int] chunks)
None deleteReplicaChunks(self, Iterable[int] chunks)
ApdbTableData _get_chunks(self, Iterable[int] chunks, ApdbTables table_enum, ExtraTables chunk_table_enum)
ApdbTableData getDiaObjectsChunks(self, Iterable[int] chunks)
__init__(self, ApdbSqlSchema schema, sqlalchemy.engine.Engine engine, bool timer=False)
ApdbTableData getDiaForcedSourcesChunks(self, Iterable[int] chunks)
Timer _timer(self, str name, *Mapping[str, str|int]|None tags=None)
__init__(self, sqlalchemy.engine.Result result)