Coverage for python/lsst/daf/butler/registry/datasets/byDimensions/tables.py : 100%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# This file is part of daf_butler.
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/>.
22from __future__ import annotations
24__all__ = (
25 "addDatasetForeignKey",
26 "makeStaticTableSpecs",
27 "makeDynamicTableName",
28 "makeDynamicTableSpec",
29 "StaticDatasetTablesTuple",
30)
32from typing import (
33 Any,
34 Optional,
35 Type,
36)
38from collections import namedtuple
40import sqlalchemy
42from lsst.daf.butler import (
43 DatasetType,
44 ddl,
45 DimensionUniverse,
46)
47from lsst.daf.butler import addDimensionForeignKey
48from lsst.daf.butler.registry.interfaces import CollectionManager
51DATASET_TYPE_NAME_LENGTH = 128
54StaticDatasetTablesTuple = namedtuple(
55 "StaticDatasetTablesTuple",
56 [
57 "dataset_type",
58 "dataset",
59 ]
60)
63def addDatasetForeignKey(tableSpec: ddl.TableSpec, *,
64 name: str = "dataset",
65 onDelete: Optional[str] = None,
66 constraint: bool = True,
67 **kwargs: Any) -> ddl.FieldSpec:
68 """Add a foreign key column for datasets and (optionally) a constraint to
69 a table.
71 This is an internal interface for the ``byDimensions`` package; external
72 code should use `DatasetRecordStorageManager.addDatasetForeignKey` instead.
74 Parameters
75 ----------
76 tableSpec : `ddl.TableSpec`
77 Specification for the table that should reference the dataset
78 table. Will be modified in place.
79 name: `str`, optional
80 A name to use for the prefix of the new field; the full name is
81 ``{name}_id``.
82 onDelete: `str`, optional
83 One of "CASCADE" or "SET NULL", indicating what should happen to
84 the referencing row if the collection row is deleted. `None`
85 indicates that this should be an integrity error.
86 constraint: `bool`, optional
87 If `False` (`True` is default), add a field that can be joined to
88 the dataset primary key, but do not add a foreign key constraint.
89 **kwargs
90 Additional keyword arguments are forwarded to the `ddl.FieldSpec`
91 constructor (only the ``name`` and ``dtype`` arguments are
92 otherwise provided).
94 Returns
95 -------
96 idSpec : `ddl.FieldSpec`
97 Specification for the ID field.
98 """
99 idFieldSpec = ddl.FieldSpec(f"{name}_id", dtype=sqlalchemy.BigInteger, **kwargs)
100 tableSpec.fields.add(idFieldSpec)
101 if constraint:
102 tableSpec.foreignKeys.append(ddl.ForeignKeySpec("dataset", source=(idFieldSpec.name,),
103 target=("id",), onDelete=onDelete))
104 return idFieldSpec
107def makeStaticTableSpecs(collections: Type[CollectionManager],
108 universe: DimensionUniverse,
109 ) -> StaticDatasetTablesTuple:
110 """Construct all static tables used by the classes in this package.
112 Static tables are those that are present in all Registries and do not
113 depend on what DatasetTypes have been registered.
115 Parameters
116 ----------
117 collections: `CollectionManager`
118 Manager object for the collections in this `Registry`.
119 universe : `DimensionUniverse`
120 Universe graph containing all dimensions known to this `Registry`.
122 Returns
123 -------
124 specs : `StaticDatasetTablesTuple`
125 A named tuple containing `ddl.TableSpec` instances.
126 """
127 specs = StaticDatasetTablesTuple(
128 dataset_type=ddl.TableSpec(
129 fields=[
130 ddl.FieldSpec(
131 name="id",
132 dtype=sqlalchemy.BigInteger,
133 autoincrement=True,
134 primaryKey=True,
135 doc=(
136 "Autoincrement ID that uniquely identifies a dataset "
137 "type in other tables. Python code outside the "
138 "`Registry` class should never interact with this; "
139 "its existence is considered an implementation detail."
140 ),
141 ),
142 ddl.FieldSpec(
143 name="name",
144 dtype=sqlalchemy.String,
145 length=DATASET_TYPE_NAME_LENGTH,
146 nullable=False,
147 doc="String name that uniquely identifies a dataset type.",
148 ),
149 ddl.FieldSpec(
150 name="storage_class",
151 dtype=sqlalchemy.String,
152 length=64,
153 nullable=False,
154 doc=(
155 "Name of the storage class associated with all "
156 "datasets of this type. Storage classes are "
157 "generally associated with a Python class, and are "
158 "enumerated in butler configuration."
159 )
160 ),
161 ddl.FieldSpec(
162 name="dimensions_encoded",
163 dtype=ddl.Base64Bytes,
164 nbytes=universe.getEncodeLength(),
165 nullable=False,
166 doc=(
167 "An opaque (but reversible) encoding of the set of "
168 "dimensions used to identify dataset of this type."
169 ),
170 ),
171 ],
172 unique=[("name",)],
173 ),
174 dataset=ddl.TableSpec(
175 fields=[
176 ddl.FieldSpec(
177 name="id",
178 dtype=sqlalchemy.BigInteger,
179 autoincrement=True,
180 primaryKey=True,
181 doc="A unique autoincrement field used as the primary key for dataset.",
182 ),
183 ddl.FieldSpec(
184 name="dataset_type_id",
185 dtype=sqlalchemy.BigInteger,
186 nullable=False,
187 doc=(
188 "Reference to the associated entry in the dataset_type "
189 "table."
190 ),
191 ),
192 # Foreign key field/constraint to run added below.
193 ],
194 foreignKeys=[
195 ddl.ForeignKeySpec("dataset_type", source=("dataset_type_id",), target=("id",)),
196 ]
197 ),
198 )
199 # Add foreign key fields programmatically.
200 collections.addRunForeignKey(specs.dataset, onDelete="CASCADE", nullable=False)
201 return specs
204def makeDynamicTableName(datasetType: DatasetType) -> str:
205 """Construct the name for a dynamic (DatasetType-dependent) table used by
206 the classes in this package.
208 Parameters
209 ----------
210 datasetType : `DatasetType`
211 Dataset type to construct a name for. Multiple dataset types may
212 share the same table.
214 Returns
215 -------
216 name : `str`
217 Name for the table.
218 """
219 return f"dataset_collection_{datasetType.dimensions.encode().hex()}"
222def makeDynamicTableSpec(datasetType: DatasetType, collections: Type[CollectionManager]) -> ddl.TableSpec:
223 """Construct the specification for a dynamic (DatasetType-dependent) table
224 used by the classes in this package.
226 Parameters
227 ----------
228 datasetType : `DatasetType`
229 Dataset type to construct a spec for. Multiple dataset types may
230 share the same table.
232 Returns
233 -------
234 spec : `ddl.TableSpec`
235 Specification for the table.
236 """
237 tableSpec = ddl.TableSpec(
238 fields=[
239 # Foreign key fields to dataset, collection, and usually dimension
240 # tables added below.
241 # The dataset_type_id field here would be redundant with the one
242 # in the main monolithic dataset table, but we need it here for an
243 # important unique constraint.
244 ddl.FieldSpec("dataset_type_id", dtype=sqlalchemy.BigInteger, nullable=False),
245 ],
246 foreignKeys=[
247 ddl.ForeignKeySpec("dataset_type", source=("dataset_type_id",), target=("id",)),
248 ]
249 )
250 # We'll also have a unique constraint on dataset type, collection, and data
251 # ID. We only include the required part of the data ID, as that's
252 # sufficient and saves us from worrying about nulls in the constraint.
253 constraint = ["dataset_type_id"]
254 # Add foreign key fields to dataset table (part of the primary key)
255 addDatasetForeignKey(tableSpec, primaryKey=True, onDelete="CASCADE")
256 # Add foreign key fields to collection table (part of the primary key and
257 # the data ID unique constraint).
258 fieldSpec = collections.addCollectionForeignKey(tableSpec, primaryKey=True, onDelete="CASCADE")
259 constraint.append(fieldSpec.name)
260 for dimension in datasetType.dimensions.required:
261 fieldSpec = addDimensionForeignKey(tableSpec, dimension=dimension, nullable=False, primaryKey=False)
262 constraint.append(fieldSpec.name)
263 # Actually add the unique constraint.
264 tableSpec.unique.add(tuple(constraint))
265 return tableSpec