LSST Applications g063fba187b+cac8b7c890,g0f08755f38+6aee506743,g1653933729+a8ce1bb630,g168dd56ebc+a8ce1bb630,g1a2382251a+b4475c5878,g1dcb35cd9c+8f9bc1652e,g20f6ffc8e0+6aee506743,g217e2c1bcf+73dee94bd0,g28da252d5a+1f19c529b9,g2bbee38e9b+3f2625acfc,g2bc492864f+3f2625acfc,g3156d2b45e+6e55a43351,g32e5bea42b+1bb94961c2,g347aa1857d+3f2625acfc,g35bb328faa+a8ce1bb630,g3a166c0a6a+3f2625acfc,g3e281a1b8c+c5dd892a6c,g3e8969e208+a8ce1bb630,g414038480c+5927e1bc1e,g41af890bb2+8a9e676b2a,g7af13505b9+809c143d88,g80478fca09+6ef8b1810f,g82479be7b0+f568feb641,g858d7b2824+6aee506743,g89c8672015+f4add4ffd5,g9125e01d80+a8ce1bb630,ga5288a1d22+2903d499ea,gb58c049af0+d64f4d3760,gc28159a63d+3f2625acfc,gcab2d0539d+b12535109e,gcf0d15dbbd+46a3f46ba9,gda6a2b7d83+46a3f46ba9,gdaeeff99f8+1711a396fd,ge79ae78c31+3f2625acfc,gef2f8181fd+0a71e47438,gf0baf85859+c1f95f4921,gfa517265be+6aee506743,gfa999e8aa5+17cd334064,w.2024.51
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)