LSST Applications g042eb84c57+730a74494b,g04e9c324dd+8c5ae1fdc5,g134cb467dc+1f1e3e7524,g199a45376c+0ba108daf9,g1fd858c14a+fa7d31856b,g210f2d0738+f66ac109ec,g262e1987ae+83a3acc0e5,g29ae962dfc+d856a2cb1f,g2cef7863aa+aef1011c0b,g35bb328faa+8c5ae1fdc5,g3fd5ace14f+a1e0c9f713,g47891489e3+0d594cb711,g4d44eb3520+c57ec8f3ed,g4d7b6aa1c5+f66ac109ec,g53246c7159+8c5ae1fdc5,g56a1a4eaf3+fd7ad03fde,g64539dfbff+f66ac109ec,g67b6fd64d1+0d594cb711,g67fd3c3899+f66ac109ec,g6985122a63+0d594cb711,g74acd417e5+3098891321,g786e29fd12+668abc6043,g81db2e9a8d+98e2ab9f28,g87389fa792+8856018cbb,g89139ef638+0d594cb711,g8d7436a09f+80fda9ce03,g8ea07a8fe4+760ca7c3fc,g90f42f885a+033b1d468d,g97be763408+a8a29bda4b,g99822b682c+e3ec3c61f9,g9d5c6a246b+0d5dac0c3d,ga41d0fce20+9243b26dd2,gbf99507273+8c5ae1fdc5,gd7ef33dd92+0d594cb711,gdab6d2f7ff+3098891321,ge410e46f29+0d594cb711,geaed405ab2+c4bbc419c6,gf9a733ac38+8c5ae1fdc5,w.2025.38
LSST Data Management Base Package
Loading...
Searching...
No Matches
apdbSql.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
24from __future__ import annotations
25
26__all__ = ["ApdbSql"]
27
28import datetime
29import logging
30import urllib.parse
31import warnings
32from collections.abc import Iterable, Mapping, MutableMapping
33from contextlib import closing
34from typing import TYPE_CHECKING, Any, cast
35
36import astropy.time
37import numpy as np
38import pandas
39import sqlalchemy
40import sqlalchemy.dialects.postgresql
41import sqlalchemy.dialects.sqlite
42from sqlalchemy import func, sql
43from sqlalchemy.pool import NullPool
44
45from lsst.sphgeom import HtmPixelization, LonLat, Region, UnitVector3d
46from lsst.utils.db_auth import DbAuth, DbAuthNotFoundError
47from lsst.utils.iteration import chunk_iterable
48
49from ..apdb import Apdb
50from ..apdbConfigFreezer import ApdbConfigFreezer
51from ..apdbReplica import ReplicaChunk
52from ..apdbSchema import ApdbTables
53from ..config import ApdbConfig
54from ..monitor import MonAgent
55from ..schema_model import Table
56from ..timer import Timer
57from ..versionTuple import IncompatibleVersionError, VersionTuple
58from .apdbMetadataSql import ApdbMetadataSql
59from .apdbSqlAdmin import ApdbSqlAdmin
60from .apdbSqlReplica import ApdbSqlReplica
61from .apdbSqlSchema import ApdbSqlSchema, ExtraTables
62from .config import ApdbSqlConfig
63
64if TYPE_CHECKING:
65 import sqlite3
66
67 from ..apdbMetadata import ApdbMetadata
68
69_LOG = logging.getLogger(__name__)
70
71_MON = MonAgent(__name__)
72
73VERSION = VersionTuple(1, 1, 0)
74"""Version for the code controlling non-replication tables. This needs to be
75updated following compatibility rules when schema produced by this code
76changes.
77"""
78
79
80def _coerce_uint64(df: pandas.DataFrame) -> pandas.DataFrame:
81 """Change the type of uint64 columns to int64, and return copy of data
82 frame.
83 """
84 names = [c[0] for c in df.dtypes.items() if c[1] == np.uint64]
85 return df.astype(dict.fromkeys(names, np.int64))
86
87
88def _make_midpointMjdTai_start(visit_time: astropy.time.Time, months: int) -> float:
89 """Calculate starting point for time-based source search.
90
91 Parameters
92 ----------
93 visit_time : `astropy.time.Time`
94 Time of current visit.
95 months : `int`
96 Number of months in the sources history.
97
98 Returns
99 -------
100 time : `float`
101 A ``midpointMjdTai`` starting point, MJD time.
102 """
103 # TODO: Use of MJD must be consistent with the code in ap_association
104 # (see DM-31996)
105 return float(visit_time.mjd - months * 30)
106
107
109 dbapiConnection: sqlite3.Connection, connectionRecord: sqlalchemy.pool._ConnectionRecord
110) -> None:
111 # Enable foreign keys
112 with closing(dbapiConnection.cursor()) as cursor:
113 cursor.execute("PRAGMA foreign_keys=ON;")
114
115
117 """Implementation of APDB interface based on SQL database.
118
119 The implementation is configured via standard ``pex_config`` mechanism
120 using `ApdbSqlConfig` configuration class. For an example of different
121 configurations check ``config/`` folder.
122
123 Parameters
124 ----------
125 config : `ApdbSqlConfig`
126 Configuration object.
127 """
128
129 metadataSchemaVersionKey = "version:schema"
130 """Name of the metadata key to store schema version number."""
131
132 metadataCodeVersionKey = "version:ApdbSql"
133 """Name of the metadata key to store code version number."""
134
135 metadataReplicaVersionKey = "version:ApdbSqlReplica"
136 """Name of the metadata key to store replica code version number."""
137
138 metadataConfigKey = "config:apdb-sql.json"
139 """Name of the metadata key to store code version number."""
140
141 _frozen_parameters = (
142 "enable_replica",
143 "dia_object_index",
144 "pixelization.htm_level",
145 "pixelization.htm_index_column",
146 "ra_dec_columns",
147 )
148 """Names of the config parameters to be frozen in metadata table."""
149
150 def __init__(self, config: ApdbSqlConfig):
151 self._engine = self._makeEngine(config, create=False)
152
153 sa_metadata = sqlalchemy.MetaData(schema=config.namespace)
154 meta_table_name = ApdbTables.metadata.table_name(prefix=config.prefix)
155 meta_table = sqlalchemy.schema.Table(meta_table_name, sa_metadata, autoload_with=self._engine)
156 self._metadata = ApdbMetadataSql(self._engine, meta_table)
157
158 # Read frozen config from metadata.
159 config_json = self._metadata.get(self.metadataConfigKey)
160 if config_json is not None:
161 # Update config from metadata.
162 freezer = ApdbConfigFreezer[ApdbSqlConfig](self._frozen_parameters)
163 self.config = freezer.update(config, config_json)
164 else:
165 self.config = config
166
168 engine=self._engine,
169 dia_object_index=self.config.dia_object_index,
170 schema_file=self.config.schema_file,
171 schema_name=self.config.schema_name,
172 prefix=self.config.prefix,
173 namespace=self.config.namespace,
174 htm_index_column=self.config.pixelization.htm_index_column,
175 enable_replica=self.config.enable_replica,
176 )
177
179
180 self.pixelator = HtmPixelization(self.config.pixelization.htm_level)
181
182 if _LOG.isEnabledFor(logging.DEBUG):
183 _LOG.debug("ApdbSql Configuration: %s", self.config.model_dump())
184
185 def _timer(self, name: str, *, tags: Mapping[str, str | int] | None = None) -> Timer:
186 """Create `Timer` instance given its name."""
187 return Timer(name, _MON, tags=tags)
188
189 @classmethod
190 def _makeEngine(cls, config: ApdbSqlConfig, *, create: bool) -> sqlalchemy.engine.Engine:
191 """Make SQLALchemy engine based on configured parameters.
192
193 Parameters
194 ----------
195 config : `ApdbSqlConfig`
196 Configuration object.
197 create : `bool`
198 Whether to try to create new database file, only relevant for
199 SQLite backend which always creates new files by default.
200 """
201 # engine is reused between multiple processes, make sure that we don't
202 # share connections by disabling pool (by using NullPool class)
203 kw: MutableMapping[str, Any] = dict(config.connection_config.extra_parameters)
204 conn_args: dict[str, Any] = {}
205 if not config.connection_config.connection_pool:
206 kw.update(poolclass=NullPool)
207 if config.connection_config.isolation_level is not None:
208 kw.update(isolation_level=config.connection_config.isolation_level)
209 elif config.db_url.startswith("sqlite"):
210 # Use READ_UNCOMMITTED as default value for sqlite.
211 kw.update(isolation_level="READ_UNCOMMITTED")
212 if config.connection_config.connection_timeout is not None:
213 if config.db_url.startswith("sqlite"):
214 conn_args.update(timeout=config.connection_config.connection_timeout)
215 elif config.db_url.startswith(("postgresql", "mysql")):
216 conn_args.update(connect_timeout=int(config.connection_config.connection_timeout))
217 kw.update(connect_args=conn_args)
218 engine = sqlalchemy.create_engine(cls._connection_url(config.db_url, create=create), **kw)
219
220 if engine.dialect.name == "sqlite":
221 # Need to enable foreign keys on every new connection.
222 sqlalchemy.event.listen(engine, "connect", _onSqlite3Connect)
223
224 return engine
225
226 @classmethod
227 def _connection_url(cls, config_url: str, *, create: bool) -> sqlalchemy.engine.URL | str:
228 """Generate a complete URL for database with proper credentials.
229
230 Parameters
231 ----------
232 config_url : `str`
233 Database URL as specified in configuration.
234 create : `bool`
235 Whether to try to create new database file, only relevant for
236 SQLite backend which always creates new files by default.
237
238 Returns
239 -------
240 connection_url : `sqlalchemy.engine.URL` or `str`
241 Connection URL including credentials.
242 """
243 # Allow 3rd party authentication mechanisms by assuming connection
244 # string is correct when we can not recognize (dialect, host, database)
245 # matching keys.
246 components = urllib.parse.urlparse(config_url)
247 if all((components.scheme is not None, components.hostname is not None, components.path is not None)):
248 try:
249 db_auth = DbAuth()
250 config_url = db_auth.getUrl(config_url)
251 except DbAuthNotFoundError:
252 # Credentials file doesn't exist or no matching credentials,
253 # use default auth.
254 pass
255
256 # SQLite has a nasty habit creating empty databases when they do not
257 # exist, tell it not to do that unless we do need to create it.
258 if not create:
259 config_url = cls._update_sqlite_url(config_url)
260
261 return config_url
262
263 @classmethod
264 def _update_sqlite_url(cls, url_string: str) -> str:
265 """If URL refers to sqlite dialect, update it so that the backend does
266 not try to create database file if it does not exist already.
267
268 Parameters
269 ----------
270 url_string : `str`
271 Connection string.
272
273 Returns
274 -------
275 url_string : `str`
276 Possibly updated connection string.
277 """
278 try:
279 url = sqlalchemy.make_url(url_string)
280 except sqlalchemy.exc.SQLAlchemyError:
281 # If parsing fails it means some special format, likely not
282 # sqlite so we just return it unchanged.
283 return url_string
284
285 if url.get_backend_name() == "sqlite":
286 # Massage url so that database name starts with "file:" and
287 # option string has "mode=rw&uri=true". Database name
288 # should look like a path (:memory: is not supported by
289 # Apdb, but someone could still try to use it).
290 database = url.database
291 if database and not database.startswith((":", "file:")):
292 query = dict(url.query, mode="rw", uri="true")
293 # If ``database`` is an absolute path then original URL should
294 # include four slashes after "sqlite:". Humans are bad at
295 # counting things beyond four and sometimes an extra slash gets
296 # added unintentionally, which causes sqlite to treat initial
297 # element as "authority" and to complain. Strip extra slashes
298 # at the start of the path to avoid that (DM-46077).
299 if database.startswith("//"):
300 warnings.warn(
301 f"Database URL contains extra leading slashes which will be removed: {url}",
302 stacklevel=3,
303 )
304 database = "/" + database.lstrip("/")
305 url = url.set(database=f"file:{database}", query=query)
306 url_string = url.render_as_string()
307
308 return url_string
309
310 def _versionCheck(self, metadata: ApdbMetadataSql) -> VersionTuple:
311 """Check schema version compatibility and return the database schema
312 version.
313 """
314
315 def _get_version(key: str) -> VersionTuple:
316 """Retrieve version number from given metadata key."""
317 version_str = metadata.get(key)
318 if version_str is None:
319 # Should not happen with existing metadata table.
320 raise RuntimeError(f"Version key {key!r} does not exist in metadata table.")
321 return VersionTuple.fromString(version_str)
322
323 db_schema_version = _get_version(self.metadataSchemaVersionKey)
324 db_code_version = _get_version(self.metadataCodeVersionKey)
325
326 # For now there is no way to make read-only APDB instances, assume that
327 # any access can do updates.
328 if not self._schema.schemaVersion().checkCompatibility(db_schema_version):
330 f"Configured schema version {self._schema.schemaVersion()} "
331 f"is not compatible with database version {db_schema_version}"
332 )
333 if not self.apdbImplementationVersion().checkCompatibility(db_code_version):
335 f"Current code version {self.apdbImplementationVersion()} "
336 f"is not compatible with database version {db_code_version}"
337 )
338
339 # Check replica code version only if replica is enabled.
340 if self._schema.replication_enabled:
341 db_replica_version = _get_version(self.metadataReplicaVersionKey)
342 code_replica_version = ApdbSqlReplica.apdbReplicaImplementationVersion()
343 if not code_replica_version.checkCompatibility(db_replica_version):
345 f"Current replication code version {code_replica_version} "
346 f"is not compatible with database version {db_replica_version}"
347 )
348
349 return db_schema_version
350
351 @classmethod
352 def apdbImplementationVersion(cls) -> VersionTuple:
353 """Return version number for current APDB implementation.
354
355 Returns
356 -------
357 version : `VersionTuple`
358 Version of the code defined in implementation class.
359 """
360 return VERSION
361
362 @classmethod
364 cls,
365 db_url: str,
366 *,
367 schema_file: str | None = None,
368 schema_name: str | None = None,
369 read_sources_months: int | None = None,
370 read_forced_sources_months: int | None = None,
371 enable_replica: bool = False,
372 connection_timeout: int | None = None,
373 dia_object_index: str | None = None,
374 htm_level: int | None = None,
375 htm_index_column: str | None = None,
376 ra_dec_columns: tuple[str, str] | None = None,
377 prefix: str | None = None,
378 namespace: str | None = None,
379 drop: bool = False,
380 ) -> ApdbSqlConfig:
381 """Initialize new APDB instance and make configuration object for it.
382
383 Parameters
384 ----------
385 db_url : `str`
386 SQLAlchemy database URL.
387 schema_file : `str`, optional
388 Location of (YAML) configuration file with APDB schema. If not
389 specified then default location will be used.
390 schema_name : str | None
391 Name of the schema in YAML configuration file. If not specified
392 then default name will be used.
393 read_sources_months : `int`, optional
394 Number of months of history to read from DiaSource.
395 read_forced_sources_months : `int`, optional
396 Number of months of history to read from DiaForcedSource.
397 enable_replica : `bool`
398 If True, make additional tables used for replication to PPDB.
399 connection_timeout : `int`, optional
400 Database connection timeout in seconds.
401 dia_object_index : `str`, optional
402 Indexing mode for DiaObject table.
403 htm_level : `int`, optional
404 HTM indexing level.
405 htm_index_column : `str`, optional
406 Name of a HTM index column for DiaObject and DiaSource tables.
407 ra_dec_columns : `tuple` [`str`, `str`], optional
408 Names of ra/dec columns in DiaObject table.
409 prefix : `str`, optional
410 Optional prefix for all table names.
411 namespace : `str`, optional
412 Name of the database schema for all APDB tables. If not specified
413 then default schema is used.
414 drop : `bool`, optional
415 If `True` then drop existing tables before re-creating the schema.
416
417 Returns
418 -------
419 config : `ApdbSqlConfig`
420 Resulting configuration object for a created APDB instance.
421 """
422 config = ApdbSqlConfig(db_url=db_url, enable_replica=enable_replica)
423 if schema_file is not None:
424 config.schema_file = schema_file
425 if schema_name is not None:
426 config.schema_name = schema_name
427 if read_sources_months is not None:
428 config.read_sources_months = read_sources_months
429 if read_forced_sources_months is not None:
430 config.read_forced_sources_months = read_forced_sources_months
431 if connection_timeout is not None:
432 config.connection_config.connection_timeout = connection_timeout
433 if dia_object_index is not None:
434 config.dia_object_index = dia_object_index
435 if htm_level is not None:
436 config.pixelization.htm_level = htm_level
437 if htm_index_column is not None:
438 config.pixelization.htm_index_column = htm_index_column
439 if ra_dec_columns is not None:
440 config.ra_dec_columns = ra_dec_columns
441 if prefix is not None:
442 config.prefix = prefix
443 if namespace is not None:
444 config.namespace = namespace
445
446 cls._makeSchema(config, drop=drop)
447
448 # SQLite has a nasty habit of creating empty database by default,
449 # update URL in config file to disable that behavior.
450 config.db_url = cls._update_sqlite_url(config.db_url)
451
452 return config
453
454 def get_replica(self) -> ApdbSqlReplica:
455 """Return `ApdbReplica` instance for this database."""
456 return ApdbSqlReplica(self._schema, self._engine, self._db_schema_version)
457
458 def tableRowCount(self) -> dict[str, int]:
459 """Return dictionary with the table names and row counts.
460
461 Used by ``ap_proto`` to keep track of the size of the database tables.
462 Depending on database technology this could be expensive operation.
463
464 Returns
465 -------
466 row_counts : `dict`
467 Dict where key is a table name and value is a row count.
468 """
469 res = {}
470 tables = [ApdbTables.DiaObject, ApdbTables.DiaSource, ApdbTables.DiaForcedSource]
471 if self.config.dia_object_index == "last_object_table":
472 tables.append(ApdbTables.DiaObjectLast)
473 with self._engine.begin() as conn:
474 for table in tables:
475 sa_table = self._schema.get_table(table)
476 stmt = sql.select(func.count()).select_from(sa_table)
477 count: int = conn.execute(stmt).scalar_one()
478 res[table.name] = count
479
480 return res
481
482 def getConfig(self) -> ApdbSqlConfig:
483 # docstring is inherited from a base class
484 return self.config
485
486 def tableDef(self, table: ApdbTables) -> Table | None:
487 # docstring is inherited from a base class
488 return self._schema.tableSchemas.get(table)
489
490 @classmethod
491 def _makeSchema(cls, config: ApdbConfig, drop: bool = False) -> None:
492 # docstring is inherited from a base class
493
494 if not isinstance(config, ApdbSqlConfig):
495 raise TypeError(f"Unexpected type of configuration object: {type(config)}")
496
497 engine = cls._makeEngine(config, create=True)
498
499 # Ask schema class to create all tables.
500 schema = ApdbSqlSchema(
501 engine=engine,
502 dia_object_index=config.dia_object_index,
503 schema_file=config.schema_file,
504 schema_name=config.schema_name,
505 prefix=config.prefix,
506 namespace=config.namespace,
507 htm_index_column=config.pixelization.htm_index_column,
508 enable_replica=config.enable_replica,
509 )
510 schema.makeSchema(drop=drop)
511
512 # Need metadata table to store few items in it.
513 meta_table = schema.get_table(ApdbTables.metadata)
514 apdb_meta = ApdbMetadataSql(engine, meta_table)
515
516 # Fill version numbers, overwrite if they are already there.
517 apdb_meta.set(cls.metadataSchemaVersionKey, str(schema.schemaVersion()), force=True)
518 apdb_meta.set(cls.metadataCodeVersionKey, str(cls.apdbImplementationVersion()), force=True)
519 if config.enable_replica:
520 # Only store replica code version if replica is enabled.
521 apdb_meta.set(
523 str(ApdbSqlReplica.apdbReplicaImplementationVersion()),
524 force=True,
525 )
526
527 # Store frozen part of a configuration in metadata.
528 freezer = ApdbConfigFreezer[ApdbSqlConfig](cls._frozen_parameters)
529 apdb_meta.set(cls.metadataConfigKey, freezer.to_json(config), force=True)
530
531 def getDiaObjects(self, region: Region) -> pandas.DataFrame:
532 # docstring is inherited from a base class
533
534 # decide what columns we need
535 if self.config.dia_object_index == "last_object_table":
536 table_enum = ApdbTables.DiaObjectLast
537 else:
538 table_enum = ApdbTables.DiaObject
539 table = self._schema.get_table(table_enum)
540 if not self.config.dia_object_columns:
541 columns = self._schema.get_apdb_columns(table_enum)
542 else:
543 columns = [table.c[col] for col in self.config.dia_object_columns]
544 query = sql.select(*columns)
545
546 # build selection
547 query = query.where(self._filterRegion(table, region))
548
549 if self._schema.has_mjd_timestamps:
550 validity_end_column = "validityEndMjdTai"
551 else:
552 validity_end_column = "validityEnd"
553
554 # select latest version of objects
555 if self.config.dia_object_index != "last_object_table":
556 query = query.where(table.columns[validity_end_column] == None) # noqa: E711
557
558 # _LOG.debug("query: %s", query)
559
560 # execute select
561 with self._timer("select_time", tags={"table": "DiaObject"}) as timer:
562 with self._engine.begin() as conn:
563 objects = pandas.read_sql_query(query, conn)
564 timer.add_values(row_count=len(objects))
565 _LOG.debug("found %s DiaObjects", len(objects))
566 return self._fix_result_timestamps(objects)
567
569 self, region: Region, object_ids: Iterable[int] | None, visit_time: astropy.time.Time
570 ) -> pandas.DataFrame | None:
571 # docstring is inherited from a base class
572 if self.config.read_sources_months == 0:
573 _LOG.debug("Skip DiaSources fetching")
574 return None
575
576 if object_ids is None:
577 # region-based select
578 return self._getDiaSourcesInRegion(region, visit_time)
579 else:
580 return self._getDiaSourcesByIDs(list(object_ids), visit_time)
581
583 self, region: Region, object_ids: Iterable[int] | None, visit_time: astropy.time.Time
584 ) -> pandas.DataFrame | None:
585 # docstring is inherited from a base class
586 if self.config.read_forced_sources_months == 0:
587 _LOG.debug("Skip DiaForceSources fetching")
588 return None
589
590 if object_ids is None:
591 # This implementation does not support region-based selection.
592 raise NotImplementedError("Region-based selection is not supported")
593
594 # TODO: DateTime.MJD must be consistent with code in ap_association,
595 # alternatively we can fill midpointMjdTai ourselves in store()
596 midpointMjdTai_start = _make_midpointMjdTai_start(visit_time, self.config.read_forced_sources_months)
597 _LOG.debug("midpointMjdTai_start = %.6f", midpointMjdTai_start)
598
599 with self._timer("select_time", tags={"table": "DiaForcedSource"}) as timer:
600 sources = self._getSourcesByIDs(
601 ApdbTables.DiaForcedSource, list(object_ids), midpointMjdTai_start
602 )
603 timer.add_values(row_count=len(sources))
604
605 _LOG.debug("found %s DiaForcedSources", len(sources))
606 return sources
607
609 self,
610 visit: int,
611 detector: int,
612 region: Region,
613 visit_time: astropy.time.Time,
614 ) -> bool:
615 # docstring is inherited from a base class
616 src_table: sqlalchemy.schema.Table = self._schema.get_table(ApdbTables.DiaSource)
617 frcsrc_table: sqlalchemy.schema.Table = self._schema.get_table(ApdbTables.DiaForcedSource)
618 # Query should load only one leaf page of the index
619 query1 = sql.select(src_table.c.visit).filter_by(visit=visit, detector=detector).limit(1)
620
621 with self._engine.begin() as conn:
622 result = conn.execute(query1).scalar_one_or_none()
623 if result is not None:
624 return True
625 else:
626 # Backup query if an image was processed but had no diaSources
627 query2 = sql.select(frcsrc_table.c.visit).filter_by(visit=visit, detector=detector).limit(1)
628 result = conn.execute(query2).scalar_one_or_none()
629 return result is not None
630
631 def getSSObjects(self) -> pandas.DataFrame:
632 # docstring is inherited from a base class
633
634 columns = self._schema.get_apdb_columns(ApdbTables.SSObject)
635 query = sql.select(*columns)
636
637 # execute select
638 with self._timer("SSObject_select_time", tags={"table": "SSObject"}) as timer:
639 with self._engine.begin() as conn:
640 objects = pandas.read_sql_query(query, conn)
641 timer.add_values(row_count=len(objects))
642 _LOG.debug("found %s SSObjects", len(objects))
643 return self._fix_result_timestamps(objects)
644
645 def store(
646 self,
647 visit_time: astropy.time.Time,
648 objects: pandas.DataFrame,
649 sources: pandas.DataFrame | None = None,
650 forced_sources: pandas.DataFrame | None = None,
651 ) -> None:
652 # docstring is inherited from a base class
653 objects = self._fix_input_timestamps(objects)
654 if sources is not None:
655 sources = self._fix_input_timestamps(sources)
656 if forced_sources is not None:
657 forced_sources = self._fix_input_timestamps(forced_sources)
658
659 # We want to run all inserts in one transaction.
660 with self._engine.begin() as connection:
661 replica_chunk: ReplicaChunk | None = None
662 if self._schema.replication_enabled:
663 replica_chunk = ReplicaChunk.make_replica_chunk(visit_time, self.config.replica_chunk_seconds)
664 self._storeReplicaChunk(replica_chunk, visit_time, connection)
665
666 # fill pixelId column for DiaObjects
667 objects = self._add_spatial_index(objects)
668 self._storeDiaObjects(objects, visit_time, replica_chunk, connection)
669
670 if sources is not None:
671 # fill pixelId column for DiaSources
672 sources = self._add_spatial_index(sources)
673 self._storeDiaSources(sources, replica_chunk, connection)
674
675 if forced_sources is not None:
676 self._storeDiaForcedSources(forced_sources, replica_chunk, connection)
677
678 def storeSSObjects(self, objects: pandas.DataFrame) -> None:
679 # docstring is inherited from a base class
680 objects = self._fix_input_timestamps(objects)
681
682 idColumn = "ssObjectId"
683 table = self._schema.get_table(ApdbTables.SSObject)
684
685 # everything to be done in single transaction
686 with self._engine.begin() as conn:
687 # Find record IDs that already exist. Some types like np.int64 can
688 # cause issues with sqlalchemy, convert them to int.
689 ids = sorted(int(oid) for oid in objects[idColumn])
690
691 query = sql.select(table.columns[idColumn], table.columns[idColumn].in_(ids))
692 result = conn.execute(query)
693 knownIds = {row.ssObjectId for row in result}
694
695 filter = objects[idColumn].isin(knownIds)
696 toUpdate = cast(pandas.DataFrame, objects[filter])
697 toInsert = cast(pandas.DataFrame, objects[~filter])
698
699 # insert new records
700 if len(toInsert) > 0:
701 toInsert.to_sql(table.name, conn, if_exists="append", index=False, schema=table.schema)
702
703 # update existing records
704 if len(toUpdate) > 0:
705 whereKey = f"{idColumn}_param"
706 update = table.update().where(table.columns[idColumn] == sql.bindparam(whereKey))
707 toUpdate = toUpdate.rename({idColumn: whereKey}, axis="columns")
708 values = toUpdate.to_dict("records")
709 result = conn.execute(update, values)
710
711 def reassignDiaSources(self, idMap: Mapping[int, int]) -> None:
712 # docstring is inherited from a base class
713
714 reassignTime = datetime.datetime.now(tz=datetime.UTC)
715
716 table = self._schema.get_table(ApdbTables.DiaSource)
717 query = table.update().where(table.columns["diaSourceId"] == sql.bindparam("srcId"))
718
719 with self._engine.begin() as conn:
720 # Need to make sure that every ID exists in the database, but
721 # executemany may not support rowcount, so iterate and check what
722 # is missing.
723 missing_ids: list[int] = []
724 for key, value in idMap.items():
725 params = {
726 "srcId": key,
727 "diaObjectId": 0,
728 "ssObjectId": value,
729 "ssObjectReassocTime": reassignTime,
730 }
731 result = conn.execute(query, params)
732 if result.rowcount == 0:
733 missing_ids.append(key)
734 if missing_ids:
735 missing = ",".join(str(item) for item in missing_ids)
736 raise ValueError(f"Following DiaSource IDs do not exist in the database: {missing}")
737
738 def dailyJob(self) -> None:
739 # docstring is inherited from a base class
740 pass
741
742 def countUnassociatedObjects(self) -> int:
743 # docstring is inherited from a base class
744
745 # Retrieve the DiaObject table.
746 table: sqlalchemy.schema.Table = self._schema.get_table(ApdbTables.DiaObject)
747
748 if self._schema.has_mjd_timestamps:
749 validity_end_column = "validityEndMjdTai"
750 else:
751 validity_end_column = "validityEnd"
752
753 # Construct the sql statement.
754 stmt = sql.select(func.count()).select_from(table).where(table.c.nDiaSources == 1)
755 stmt = stmt.where(table.columns[validity_end_column] == None) # noqa: E711
756
757 # Return the count.
758 with self._engine.begin() as conn:
759 count = conn.execute(stmt).scalar_one()
760
761 return count
762
763 @property
764 def metadata(self) -> ApdbMetadata:
765 # docstring is inherited from a base class
766 return self._metadata
767
768 @property
769 def admin(self) -> ApdbSqlAdmin:
770 # docstring is inherited from a base class
771 return ApdbSqlAdmin(self.pixelator)
772
773 def _getDiaSourcesInRegion(self, region: Region, visit_time: astropy.time.Time) -> pandas.DataFrame:
774 """Return catalog of DiaSource instances from given region.
775
776 Parameters
777 ----------
778 region : `lsst.sphgeom.Region`
779 Region to search for DIASources.
780 visit_time : `astropy.time.Time`
781 Time of the current visit.
782
783 Returns
784 -------
785 catalog : `pandas.DataFrame`
786 Catalog containing DiaSource records.
787 """
788 # TODO: DateTime.MJD must be consistent with code in ap_association,
789 # alternatively we can fill midpointMjdTai ourselves in store()
790 midpointMjdTai_start = _make_midpointMjdTai_start(visit_time, self.config.read_sources_months)
791 _LOG.debug("midpointMjdTai_start = %.6f", midpointMjdTai_start)
792
793 table = self._schema.get_table(ApdbTables.DiaSource)
794 columns = self._schema.get_apdb_columns(ApdbTables.DiaSource)
795 query = sql.select(*columns)
796
797 # build selection
798 time_filter = table.columns["midpointMjdTai"] > midpointMjdTai_start
799 where = sql.expression.and_(self._filterRegion(table, region), time_filter)
800 query = query.where(where)
801
802 # execute select
803 with self._timer("DiaSource_select_time", tags={"table": "DiaSource"}) as timer:
804 with self._engine.begin() as conn:
805 sources = pandas.read_sql_query(query, conn)
806 timer.add_values(row_counts=len(sources))
807 _LOG.debug("found %s DiaSources", len(sources))
808 return self._fix_result_timestamps(sources)
809
810 def _getDiaSourcesByIDs(self, object_ids: list[int], visit_time: astropy.time.Time) -> pandas.DataFrame:
811 """Return catalog of DiaSource instances given set of DiaObject IDs.
812
813 Parameters
814 ----------
815 object_ids :
816 Collection of DiaObject IDs
817 visit_time : `astropy.time.Time`
818 Time of the current visit.
819
820 Returns
821 -------
822 catalog : `pandas.DataFrame`
823 Catalog contaning DiaSource records.
824 """
825 # TODO: DateTime.MJD must be consistent with code in ap_association,
826 # alternatively we can fill midpointMjdTai ourselves in store()
827 midpointMjdTai_start = _make_midpointMjdTai_start(visit_time, self.config.read_sources_months)
828 _LOG.debug("midpointMjdTai_start = %.6f", midpointMjdTai_start)
829
830 with self._timer("select_time", tags={"table": "DiaSource"}) as timer:
831 sources = self._getSourcesByIDs(ApdbTables.DiaSource, object_ids, midpointMjdTai_start)
832 timer.add_values(row_count=len(sources))
833
834 _LOG.debug("found %s DiaSources", len(sources))
835 return sources
836
838 self, table_enum: ApdbTables, object_ids: list[int], midpointMjdTai_start: float
839 ) -> pandas.DataFrame:
840 """Return catalog of DiaSource or DiaForcedSource instances given set
841 of DiaObject IDs.
842
843 Parameters
844 ----------
845 table : `sqlalchemy.schema.Table`
846 Database table.
847 object_ids :
848 Collection of DiaObject IDs
849 midpointMjdTai_start : `float`
850 Earliest midpointMjdTai to retrieve.
851
852 Returns
853 -------
854 catalog : `pandas.DataFrame`
855 Catalog contaning DiaSource records. `None` is returned if
856 ``read_sources_months`` configuration parameter is set to 0 or
857 when ``object_ids`` is empty.
858 """
859 table = self._schema.get_table(table_enum)
860 columns = self._schema.get_apdb_columns(table_enum)
861
862 sources: pandas.DataFrame | None = None
863 if len(object_ids) <= 0:
864 _LOG.debug("ID list is empty, just fetch empty result")
865 query = sql.select(*columns).where(sql.literal(False))
866 with self._engine.begin() as conn:
867 sources = pandas.read_sql_query(query, conn)
868 else:
869 data_frames: list[pandas.DataFrame] = []
870 for ids in chunk_iterable(sorted(object_ids), 1000):
871 query = sql.select(*columns)
872
873 # Some types like np.int64 can cause issues with
874 # sqlalchemy, convert them to int.
875 int_ids = [int(oid) for oid in ids]
876
877 # select by object id
878 query = query.where(
879 sql.expression.and_(
880 table.columns["diaObjectId"].in_(int_ids),
881 table.columns["midpointMjdTai"] > midpointMjdTai_start,
882 )
883 )
884
885 # execute select
886 with self._engine.begin() as conn:
887 data_frames.append(pandas.read_sql_query(query, conn))
888
889 if len(data_frames) == 1:
890 sources = data_frames[0]
891 else:
892 sources = pandas.concat(data_frames)
893 assert sources is not None, "Catalog cannot be None"
894 return self._fix_result_timestamps(sources)
895
897 self,
898 replica_chunk: ReplicaChunk,
899 visit_time: astropy.time.Time,
900 connection: sqlalchemy.engine.Connection,
901 ) -> None:
902 # `visit_time.datetime` returns naive datetime, even though all astropy
903 # times are in UTC. Add UTC timezone to timestampt so that database
904 # can store a correct value.
905 dt = datetime.datetime.fromtimestamp(visit_time.unix_tai, tz=datetime.UTC)
906
907 table = self._schema.get_table(ExtraTables.ApdbReplicaChunks)
908
909 # We need UPSERT which is dialect-specific construct
910 values = {"last_update_time": dt, "unique_id": replica_chunk.unique_id}
911 row = {"apdb_replica_chunk": replica_chunk.id} | values
912 if connection.dialect.name == "sqlite":
913 insert_sqlite = sqlalchemy.dialects.sqlite.insert(table)
914 insert_sqlite = insert_sqlite.on_conflict_do_update(index_elements=table.primary_key, set_=values)
915 connection.execute(insert_sqlite, row)
916 elif connection.dialect.name == "postgresql":
917 insert_pg = sqlalchemy.dialects.postgresql.dml.insert(table)
918 insert_pg = insert_pg.on_conflict_do_update(constraint=table.primary_key, set_=values)
919 connection.execute(insert_pg, row)
920 else:
921 raise TypeError(f"Unsupported dialect {connection.dialect.name} for upsert.")
922
924 self,
925 objs: pandas.DataFrame,
926 visit_time: astropy.time.Time,
927 replica_chunk: ReplicaChunk | None,
928 connection: sqlalchemy.engine.Connection,
929 ) -> None:
930 """Store catalog of DiaObjects from current visit.
931
932 Parameters
933 ----------
934 objs : `pandas.DataFrame`
935 Catalog with DiaObject records.
936 visit_time : `astropy.time.Time`
937 Time of the visit.
938 replica_chunk : `ReplicaChunk`
939 Insert identifier.
940 """
941 if len(objs) == 0:
942 _LOG.debug("No objects to write to database.")
943 return
944
945 # Some types like np.int64 can cause issues with sqlalchemy, convert
946 # them to int.
947 ids = sorted(int(oid) for oid in objs["diaObjectId"])
948 _LOG.debug("first object ID: %d", ids[0])
949
950 if self._schema.has_mjd_timestamps:
951 validity_start_column = "validityStartMjdTai"
952 validity_end_column = "validityEndMjdTai"
953 timestamp = float(visit_time.tai.mjd)
954 else:
955 validity_start_column = "validityStart"
956 validity_end_column = "validityEnd"
957 timestamp = visit_time.datetime
958
959 # everything to be done in single transaction
960 if self.config.dia_object_index == "last_object_table":
961 # Insert and replace all records in LAST table.
962 table = self._schema.get_table(ApdbTables.DiaObjectLast)
963
964 # Drop the previous objects (pandas cannot upsert).
965 query = table.delete().where(table.columns["diaObjectId"].in_(ids))
966
967 with self._timer("delete_time", tags={"table": table.name}) as timer:
968 res = connection.execute(query)
969 timer.add_values(row_count=res.rowcount)
970 _LOG.debug("deleted %s objects", res.rowcount)
971
972 # DiaObjectLast is a subset of DiaObject, strip missing columns
973 last_column_names = [column.name for column in table.columns]
974 last_objs = objs[last_column_names]
975 last_objs = _coerce_uint64(last_objs)
976
977 with self._timer("insert_time", tags={"table": "DiaObjectLast"}) as timer:
978 last_objs.to_sql(
979 table.name,
980 connection,
981 if_exists="append",
982 index=False,
983 schema=table.schema,
984 )
985 timer.add_values(row_count=len(last_objs))
986 else:
987 # truncate existing validity intervals
988 table = self._schema.get_table(ApdbTables.DiaObject)
989
990 update = (
991 table.update()
992 .values(**{validity_end_column: timestamp})
993 .where(
994 sql.expression.and_(
995 table.columns["diaObjectId"].in_(ids),
996 table.columns[validity_end_column].is_(None),
997 )
998 )
999 )
1000
1001 with self._timer("truncate_time", tags={"table": table.name}) as timer:
1002 res = connection.execute(update)
1003 timer.add_values(row_count=res.rowcount)
1004 _LOG.debug("truncated %s intervals", res.rowcount)
1005
1006 objs = _coerce_uint64(objs)
1007
1008 # Fill additional columns
1009 extra_columns: list[pandas.Series] = []
1010 if validity_start_column in objs.columns:
1011 objs[validity_start_column] = timestamp
1012 else:
1013 extra_columns.append(pandas.Series([timestamp] * len(objs), name=validity_start_column))
1014 if validity_end_column in objs.columns:
1015 objs[validity_end_column] = None
1016 else:
1017 extra_columns.append(pandas.Series([None] * len(objs), name=validity_end_column))
1018 if extra_columns:
1019 objs.set_index(extra_columns[0].index, inplace=True)
1020 objs = pandas.concat([objs] + extra_columns, axis="columns")
1021
1022 # Insert replica data
1023 table = self._schema.get_table(ApdbTables.DiaObject)
1024 replica_data: list[dict] = []
1025 replica_stmt: Any = None
1026 replica_table_name = ""
1027 if replica_chunk is not None:
1028 pk_names = [column.name for column in table.primary_key]
1029 replica_data = objs[pk_names].to_dict("records")
1030 for row in replica_data:
1031 row["apdb_replica_chunk"] = replica_chunk.id
1032 replica_table = self._schema.get_table(ExtraTables.DiaObjectChunks)
1033 replica_table_name = replica_table.name
1034 replica_stmt = replica_table.insert()
1035
1036 # insert new versions
1037 with self._timer("insert_time", tags={"table": table.name}) as timer:
1038 objs.to_sql(table.name, connection, if_exists="append", index=False, schema=table.schema)
1039 timer.add_values(row_count=len(objs))
1040 if replica_stmt is not None:
1041 with self._timer("insert_time", tags={"table": replica_table_name}) as timer:
1042 connection.execute(replica_stmt, replica_data)
1043 timer.add_values(row_count=len(replica_data))
1044
1046 self,
1047 sources: pandas.DataFrame,
1048 replica_chunk: ReplicaChunk | None,
1049 connection: sqlalchemy.engine.Connection,
1050 ) -> None:
1051 """Store catalog of DiaSources from current visit.
1052
1053 Parameters
1054 ----------
1055 sources : `pandas.DataFrame`
1056 Catalog containing DiaSource records
1057 """
1058 table = self._schema.get_table(ApdbTables.DiaSource)
1059
1060 # Insert replica data
1061 replica_data: list[dict] = []
1062 replica_stmt: Any = None
1063 replica_table_name = ""
1064 if replica_chunk is not None:
1065 pk_names = [column.name for column in table.primary_key]
1066 replica_data = sources[pk_names].to_dict("records")
1067 for row in replica_data:
1068 row["apdb_replica_chunk"] = replica_chunk.id
1069 replica_table = self._schema.get_table(ExtraTables.DiaSourceChunks)
1070 replica_table_name = replica_table.name
1071 replica_stmt = replica_table.insert()
1072
1073 # everything to be done in single transaction
1074 with self._timer("insert_time", tags={"table": table.name}) as timer:
1075 sources = _coerce_uint64(sources)
1076 sources.to_sql(table.name, connection, if_exists="append", index=False, schema=table.schema)
1077 timer.add_values(row_count=len(sources))
1078 if replica_stmt is not None:
1079 with self._timer("replica_insert_time", tags={"table": replica_table_name}) as timer:
1080 connection.execute(replica_stmt, replica_data)
1081 timer.add_values(row_count=len(replica_data))
1082
1084 self,
1085 sources: pandas.DataFrame,
1086 replica_chunk: ReplicaChunk | None,
1087 connection: sqlalchemy.engine.Connection,
1088 ) -> None:
1089 """Store a set of DiaForcedSources from current visit.
1090
1091 Parameters
1092 ----------
1093 sources : `pandas.DataFrame`
1094 Catalog containing DiaForcedSource records
1095 """
1096 table = self._schema.get_table(ApdbTables.DiaForcedSource)
1097
1098 # Insert replica data
1099 replica_data: list[dict] = []
1100 replica_stmt: Any = None
1101 replica_table_name = ""
1102 if replica_chunk is not None:
1103 pk_names = [column.name for column in table.primary_key]
1104 replica_data = sources[pk_names].to_dict("records")
1105 for row in replica_data:
1106 row["apdb_replica_chunk"] = replica_chunk.id
1107 replica_table = self._schema.get_table(ExtraTables.DiaForcedSourceChunks)
1108 replica_table_name = replica_table.name
1109 replica_stmt = replica_table.insert()
1110
1111 # everything to be done in single transaction
1112 with self._timer("insert_time", tags={"table": table.name}) as timer:
1113 sources = _coerce_uint64(sources)
1114 sources.to_sql(table.name, connection, if_exists="append", index=False, schema=table.schema)
1115 timer.add_values(row_count=len(sources))
1116 if replica_stmt is not None:
1117 with self._timer("insert_time", tags={"table": replica_table_name}):
1118 connection.execute(replica_stmt, replica_data)
1119 timer.add_values(row_count=len(replica_data))
1120
1121 def _htm_indices(self, region: Region) -> list[tuple[int, int]]:
1122 """Generate a set of HTM indices covering specified region.
1123
1124 Parameters
1125 ----------
1126 region: `sphgeom.Region`
1127 Region that needs to be indexed.
1128
1129 Returns
1130 -------
1131 Sequence of ranges, range is a tuple (minHtmID, maxHtmID).
1132 """
1133 _LOG.debug("region: %s", region)
1134 indices = self.pixelator.envelope(region, self.config.pixelization.htm_max_ranges)
1135
1136 return indices.ranges()
1137
1138 def _filterRegion(self, table: sqlalchemy.schema.Table, region: Region) -> sql.ColumnElement:
1139 """Make SQLAlchemy expression for selecting records in a region."""
1140 htm_index_column = table.columns[self.config.pixelization.htm_index_column]
1141 exprlist = []
1142 pixel_ranges = self._htm_indices(region)
1143 for low, upper in pixel_ranges:
1144 upper -= 1
1145 if low == upper:
1146 exprlist.append(htm_index_column == low)
1147 else:
1148 exprlist.append(sql.expression.between(htm_index_column, low, upper))
1149
1150 return sql.expression.or_(*exprlist)
1151
1152 def _add_spatial_index(self, df: pandas.DataFrame) -> pandas.DataFrame:
1153 """Calculate spatial index for each record and add it to a DataFrame.
1154
1155 Parameters
1156 ----------
1157 df : `pandas.DataFrame`
1158 DataFrame which has to contain ra/dec columns, names of these
1159 columns are defined by configuration ``ra_dec_columns`` field.
1160
1161 Returns
1162 -------
1163 df : `pandas.DataFrame`
1164 DataFrame with ``pixelId`` column which contains pixel index
1165 for ra/dec coordinates.
1166
1167 Notes
1168 -----
1169 This overrides any existing column in a DataFrame with the same name
1170 (pixelId). Original DataFrame is not changed, copy of a DataFrame is
1171 returned.
1172 """
1173 # calculate HTM index for every DiaObject
1174 htm_index = np.zeros(df.shape[0], dtype=np.int64)
1175 ra_col, dec_col = self.config.ra_dec_columns
1176 for i, (ra, dec) in enumerate(zip(df[ra_col], df[dec_col])):
1177 uv3d = UnitVector3d(LonLat.fromDegrees(ra, dec))
1178 idx = self.pixelator.index(uv3d)
1179 htm_index[i] = idx
1180 df = df.copy()
1181 df[self.config.pixelization.htm_index_column] = htm_index
1182 return df
1183
1184 def _fix_input_timestamps(self, df: pandas.DataFrame) -> pandas.DataFrame:
1185 """Update timestamp columns in input DataFrame to be aware datetime
1186 type in in UTC.
1187
1188 AP pipeline generates naive datetime instances, we want them to be
1189 aware before they go to database. All naive timestamps are assumed to
1190 be in UTC timezone (they should be TAI).
1191 """
1192 # Find all columns with aware non-UTC timestamps and convert to UTC.
1193 columns = [
1194 column
1195 for column, dtype in df.dtypes.items()
1196 if isinstance(dtype, pandas.DatetimeTZDtype) and dtype.tz is not datetime.UTC
1197 ]
1198 for column in columns:
1199 df[column] = df[column].dt.tz_convert(datetime.UTC)
1200 # Find all columns with naive timestamps and add UTC timezone.
1201 columns = [
1202 column for column, dtype in df.dtypes.items() if pandas.api.types.is_datetime64_dtype(dtype)
1203 ]
1204 for column in columns:
1205 df[column] = df[column].dt.tz_localize(datetime.UTC)
1206 return df
1207
1208 def _fix_result_timestamps(self, df: pandas.DataFrame) -> pandas.DataFrame:
1209 """Update timestamp columns to be naive datetime type in returned
1210 DataFrame.
1211
1212 AP pipeline code expects DataFrames to contain naive datetime columns,
1213 while Postgres queries return timezone-aware type. This method converts
1214 those columns to naive datetime in UTC timezone.
1215 """
1216 # Find all columns with aware timestamps.
1217 columns = [column for column, dtype in df.dtypes.items() if isinstance(dtype, pandas.DatetimeTZDtype)]
1218 for column in columns:
1219 # tz_convert(None) will convert to UTC and drop timezone.
1220 df[column] = df[column].dt.tz_convert(None)
1221 return df
__init__(self, ApdbSqlConfig config)
Definition apdbSql.py:150
ApdbSqlConfig init_database(cls, str db_url, *, str|None schema_file=None, str|None schema_name=None, int|None read_sources_months=None, int|None read_forced_sources_months=None, bool enable_replica=False, int|None connection_timeout=None, str|None dia_object_index=None, int|None htm_level=None, str|None htm_index_column=None, tuple[str, str]|None ra_dec_columns=None, str|None prefix=None, str|None namespace=None, bool drop=False)
Definition apdbSql.py:380
pandas.DataFrame getSSObjects(self)
Definition apdbSql.py:631
pandas.DataFrame|None getDiaSources(self, Region region, Iterable[int]|None object_ids, astropy.time.Time visit_time)
Definition apdbSql.py:570
pandas.DataFrame _fix_result_timestamps(self, pandas.DataFrame df)
Definition apdbSql.py:1208
pandas.DataFrame|None getDiaForcedSources(self, Region region, Iterable[int]|None object_ids, astropy.time.Time visit_time)
Definition apdbSql.py:584
None _storeDiaForcedSources(self, pandas.DataFrame sources, ReplicaChunk|None replica_chunk, sqlalchemy.engine.Connection connection)
Definition apdbSql.py:1088
pandas.DataFrame getDiaObjects(self, Region region)
Definition apdbSql.py:531
str _update_sqlite_url(cls, str url_string)
Definition apdbSql.py:264
VersionTuple apdbImplementationVersion(cls)
Definition apdbSql.py:352
VersionTuple _versionCheck(self, ApdbMetadataSql metadata)
Definition apdbSql.py:310
None _storeReplicaChunk(self, ReplicaChunk replica_chunk, astropy.time.Time visit_time, sqlalchemy.engine.Connection connection)
Definition apdbSql.py:901
pandas.DataFrame _add_spatial_index(self, pandas.DataFrame df)
Definition apdbSql.py:1152
sqlalchemy.engine.Engine _makeEngine(cls, ApdbSqlConfig config, *, bool create)
Definition apdbSql.py:190
pandas.DataFrame _getDiaSourcesInRegion(self, Region region, astropy.time.Time visit_time)
Definition apdbSql.py:773
ApdbSqlConfig getConfig(self)
Definition apdbSql.py:482
sqlalchemy.engine.Engine _engine
Definition apdbSql.py:151
pandas.DataFrame _fix_input_timestamps(self, pandas.DataFrame df)
Definition apdbSql.py:1184
sqlalchemy.engine.URL|str _connection_url(cls, str config_url, *, bool create)
Definition apdbSql.py:227
ApdbMetadata metadata(self)
Definition apdbSql.py:764
None _makeSchema(cls, ApdbConfig config, bool drop=False)
Definition apdbSql.py:491
pandas.DataFrame _getDiaSourcesByIDs(self, list[int] object_ids, astropy.time.Time visit_time)
Definition apdbSql.py:810
None reassignDiaSources(self, Mapping[int, int] idMap)
Definition apdbSql.py:711
list[tuple[int, int]] _htm_indices(self, Region region)
Definition apdbSql.py:1121
bool containsVisitDetector(self, int visit, int detector, Region region, astropy.time.Time visit_time)
Definition apdbSql.py:614
dict[str, int] tableRowCount(self)
Definition apdbSql.py:458
pandas.DataFrame _getSourcesByIDs(self, ApdbTables table_enum, list[int] object_ids, float midpointMjdTai_start)
Definition apdbSql.py:839
ApdbSqlReplica get_replica(self)
Definition apdbSql.py:454
None store(self, astropy.time.Time visit_time, pandas.DataFrame objects, pandas.DataFrame|None sources=None, pandas.DataFrame|None forced_sources=None)
Definition apdbSql.py:651
None _storeDiaObjects(self, pandas.DataFrame objs, astropy.time.Time visit_time, ReplicaChunk|None replica_chunk, sqlalchemy.engine.Connection connection)
Definition apdbSql.py:929
Timer _timer(self, str name, *, Mapping[str, str|int]|None tags=None)
Definition apdbSql.py:185
Table|None tableDef(self, ApdbTables table)
Definition apdbSql.py:486
None storeSSObjects(self, pandas.DataFrame objects)
Definition apdbSql.py:678
None _storeDiaSources(self, pandas.DataFrame sources, ReplicaChunk|None replica_chunk, sqlalchemy.engine.Connection connection)
Definition apdbSql.py:1050
sql.ColumnElement _filterRegion(self, sqlalchemy.schema.Table table, Region region)
Definition apdbSql.py:1138
HtmPixelization provides HTM indexing of points and regions.
UnitVector3d is a unit vector in ℝ³ with components stored in double precision.
float _make_midpointMjdTai_start(astropy.time.Time visit_time, int months)
Definition apdbSql.py:88
None _onSqlite3Connect(sqlite3.Connection dbapiConnection, sqlalchemy.pool._ConnectionRecord connectionRecord)
Definition apdbSql.py:110
pandas.DataFrame _coerce_uint64(pandas.DataFrame df)
Definition apdbSql.py:80