LSST Applications g0f08755f38+82efc23009,g12f32b3c4e+e7bdf1200e,g1653933729+a8ce1bb630,g1a0ca8cf93+50eff2b06f,g28da252d5a+52db39f6a5,g2bbee38e9b+37c5a29d61,g2bc492864f+37c5a29d61,g2cdde0e794+c05ff076ad,g3156d2b45e+41e33cbcdc,g347aa1857d+37c5a29d61,g35bb328faa+a8ce1bb630,g3a166c0a6a+37c5a29d61,g3e281a1b8c+fb992f5633,g414038480c+7f03dfc1b0,g41af890bb2+11b950c980,g5fbc88fb19+17cd334064,g6b1c1869cb+12dd639c9a,g781aacb6e4+a8ce1bb630,g80478fca09+72e9651da0,g82479be7b0+04c31367b4,g858d7b2824+82efc23009,g9125e01d80+a8ce1bb630,g9726552aa6+8047e3811d,ga5288a1d22+e532dc0a0b,gae0086650b+a8ce1bb630,gb58c049af0+d64f4d3760,gc28159a63d+37c5a29d61,gcf0d15dbbd+2acd6d4d48,gd7358e8bfb+778a810b6e,gda3e153d99+82efc23009,gda6a2b7d83+2acd6d4d48,gdaeeff99f8+1711a396fd,ge2409df99d+6b12de1076,ge79ae78c31+37c5a29d61,gf0baf85859+d0a5978c5a,gf3967379c6+4954f8c433,gfb92a5be7c+82efc23009,gfec2e1e490+2aaed99252,w.2024.46
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") as timer:
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 timer.add_values(row_count=len(ids))
121 return ids
122
123 def deleteReplicaChunks(self, chunks: Iterable[int]) -> None:
124 # docstring is inherited from a base class
125 if not self._schema.has_replica_chunks:
126 raise ValueError("APDB is not configured for replication")
127
128 table = self._schema.get_table(ExtraTables.ApdbReplicaChunks)
129 chunk_list = list(chunks)
130 where_clause = table.columns["apdb_replica_chunk"].in_(chunk_list)
131 stmt = table.delete().where(where_clause)
132 with self._timer("chunks_delete_time") as timer:
133 with self._engine.begin() as conn:
134 conn.execute(stmt)
135 timer.add_values(row_count=len(chunk_list))
136
137 def getDiaObjectsChunks(self, chunks: Iterable[int]) -> ApdbTableData:
138 # docstring is inherited from a base class
139 return self._get_chunks(chunks, ApdbTables.DiaObject, ExtraTables.DiaObjectChunks)
140
141 def getDiaSourcesChunks(self, chunks: Iterable[int]) -> ApdbTableData:
142 # docstring is inherited from a base class
143 return self._get_chunks(chunks, ApdbTables.DiaSource, ExtraTables.DiaSourceChunks)
144
145 def getDiaForcedSourcesChunks(self, chunks: Iterable[int]) -> ApdbTableData:
146 # docstring is inherited from a base class
147 return self._get_chunks(chunks, ApdbTables.DiaForcedSource, ExtraTables.DiaForcedSourceChunks)
148
150 self,
151 chunks: Iterable[int],
152 table_enum: ApdbTables,
153 chunk_table_enum: ExtraTables,
154 ) -> ApdbTableData:
155 """Return catalog of records for given insert identifiers, common
156 implementation for all DIA tables.
157 """
158 if not self._schema.has_replica_chunks:
159 raise ValueError("APDB is not configured for replication")
160
161 table = self._schema.get_table(table_enum)
162 chunk_table = self._schema.get_table(chunk_table_enum)
163
164 join = table.join(chunk_table)
165 chunk_id_column = chunk_table.columns["apdb_replica_chunk"]
166 apdb_columns = self._schema.get_apdb_columns(table_enum)
167 where_clause = chunk_id_column.in_(chunks)
168 query = sql.select(chunk_id_column, *apdb_columns).select_from(join).where(where_clause)
169
170 # execute select
171 with self._timer("table_chunk_select_time", tags={"table": table.name}) as timer:
172 with self._engine.begin() as conn:
173 result = conn.execution_options(stream_results=True, max_row_buffer=10000).execute(query)
174 table_data = ApdbSqlTableData(result)
175 timer.add_values(row_count=len(table_data.rows()))
176 return table_data
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)