Coverage for python/felis/datamodel.py: 62%
240 statements
« prev ^ index » next coverage.py v7.4.1, created at 2024-02-17 10:27 +0000
« prev ^ index » next coverage.py v7.4.1, created at 2024-02-17 10:27 +0000
1# This file is part of felis.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://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 <https://www.gnu.org/licenses/>.
22from __future__ import annotations
24import logging
25from collections.abc import Mapping, Sequence
26from enum import Enum
27from typing import Any, Literal
29from astropy import units as units # type: ignore
30from astropy.io.votable import ucd # type: ignore
31from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
33logger = logging.getLogger(__name__)
34# logger.setLevel(logging.DEBUG)
36__all__ = (
37 "BaseObject",
38 "Column",
39 "CheckConstraint",
40 "Constraint",
41 "ForeignKeyConstraint",
42 "Index",
43 "Schema",
44 "SchemaVersion",
45 "Table",
46 "UniqueConstraint",
47)
49CONFIG = ConfigDict(
50 populate_by_name=True, # Populate attributes by name.
51 extra="forbid", # Do not allow extra fields.
52 use_enum_values=True, # Use enum values instead of names.
53 validate_assignment=True, # Validate assignments after model is created.
54 str_strip_whitespace=True, # Strip whitespace from string fields.
55)
56"""Pydantic model configuration as described in:
57https://docs.pydantic.dev/2.0/api/config/#pydantic.config.ConfigDict
58"""
60DESCR_MIN_LENGTH = 3
61"""Minimum length for a description field."""
64class BaseObject(BaseModel):
65 """Base class for all Felis objects."""
67 model_config = CONFIG
68 """Pydantic model configuration."""
70 name: str
71 """The name of the database object.
73 All Felis database objects must have a name.
74 """
76 id: str = Field(alias="@id")
77 """The unique identifier of the database object.
79 All Felis database objects must have a unique identifier.
80 """
82 description: str | None = Field(None, min_length=DESCR_MIN_LENGTH)
83 """A description of the database object.
85 By default, the description is optional but will be required if
86 `BaseObject.Config.require_description` is set to `True` by the user.
87 """
89 @model_validator(mode="before")
90 @classmethod
91 def check_description(cls, values: dict[str, Any]) -> dict[str, Any]:
92 """Check that the description is present if required."""
93 if Schema.is_description_required():
94 if "description" not in values or not values["description"]:
95 raise ValueError("Description is required and must be non-empty")
96 if len(values["description"].strip()) < DESCR_MIN_LENGTH:
97 raise ValueError(f"Description must be at least {DESCR_MIN_LENGTH} characters long")
98 return values
101class DataType(Enum):
102 """`Enum` representing the data types supported by Felis."""
104 BOOLEAN = "boolean"
105 BYTE = "byte"
106 SHORT = "short"
107 INT = "int"
108 LONG = "long"
109 FLOAT = "float"
110 DOUBLE = "double"
111 CHAR = "char"
112 STRING = "string"
113 UNICODE = "unicode"
114 TEXT = "text"
115 BINARY = "binary"
116 TIMESTAMP = "timestamp"
119class Column(BaseObject):
120 """A column in a table."""
122 datatype: DataType
123 """The datatype of the column."""
125 length: int | None = None
126 """The length of the column."""
128 nullable: bool = True
129 """Whether the column can be `NULL`."""
131 value: Any = None
132 """The default value of the column."""
134 autoincrement: bool | None = None
135 """Whether the column is autoincremented."""
137 mysql_datatype: str | None = Field(None, alias="mysql:datatype")
138 """The MySQL datatype of the column."""
140 ivoa_ucd: str | None = Field(None, alias="ivoa:ucd")
141 """The IVOA UCD of the column."""
143 fits_tunit: str | None = Field(None, alias="fits:tunit")
144 """The FITS TUNIT of the column."""
146 ivoa_unit: str | None = Field(None, alias="ivoa:unit")
147 """The IVOA unit of the column."""
149 tap_column_index: int | None = Field(None, alias="tap:column_index")
150 """The TAP_SCHEMA column index of the column."""
152 tap_principal: int | None = Field(0, alias="tap:principal", ge=0, le=1)
153 """Whether this is a TAP_SCHEMA principal column; can be either 0 or 1.
154 """
156 votable_arraysize: int | Literal["*"] | None = Field(None, alias="votable:arraysize")
157 """The VOTable arraysize of the column."""
159 tap_std: int | None = Field(0, alias="tap:std", ge=0, le=1)
160 """TAP_SCHEMA indication that this column is defined by an IVOA standard.
161 """
163 votable_utype: str | None = Field(None, alias="votable:utype")
164 """The VOTable utype (usage-specific or unique type) of the column."""
166 votable_xtype: str | None = Field(None, alias="votable:xtype")
167 """The VOTable xtype (extended type) of the column."""
169 @field_validator("ivoa_ucd")
170 @classmethod
171 def check_ivoa_ucd(cls, ivoa_ucd: str) -> str:
172 """Check that IVOA UCD values are valid."""
173 if ivoa_ucd is not None:
174 try:
175 ucd.parse_ucd(ivoa_ucd, check_controlled_vocabulary=True, has_colon=";" in ivoa_ucd)
176 except ValueError as e:
177 raise ValueError(f"Invalid IVOA UCD: {e}")
178 return ivoa_ucd
180 @model_validator(mode="before")
181 @classmethod
182 def check_units(cls, values: dict[str, Any]) -> dict[str, Any]:
183 """Check that units are valid."""
184 fits_unit = values.get("fits:tunit")
185 ivoa_unit = values.get("ivoa:unit")
187 if fits_unit and ivoa_unit:
188 raise ValueError("Column cannot have both FITS and IVOA units")
189 unit = fits_unit or ivoa_unit
191 if unit is not None:
192 try:
193 units.Unit(unit)
194 except ValueError as e:
195 raise ValueError(f"Invalid unit: {e}")
197 return values
200class Constraint(BaseObject):
201 """A database table constraint."""
203 deferrable: bool = False
204 """If `True` then this constraint will be declared as deferrable."""
206 initially: str | None = None
207 """Value for ``INITIALLY`` clause, only used if ``deferrable`` is True."""
209 annotations: Mapping[str, Any] = Field(default_factory=dict)
210 """Additional annotations for this constraint."""
212 type: str | None = Field(None, alias="@type")
213 """The type of the constraint."""
216class CheckConstraint(Constraint):
217 """A check constraint on a table."""
219 expression: str
220 """The expression for the check constraint."""
223class UniqueConstraint(Constraint):
224 """A unique constraint on a table."""
226 columns: list[str]
227 """The columns in the unique constraint."""
230class Index(BaseObject):
231 """A database table index.
233 An index can be defined on either columns or expressions, but not both.
234 """
236 columns: list[str] | None = None
237 """The columns in the index."""
239 expressions: list[str] | None = None
240 """The expressions in the index."""
242 @model_validator(mode="before")
243 @classmethod
244 def check_columns_or_expressions(cls, values: dict[str, Any]) -> dict[str, Any]:
245 """Check that columns or expressions are specified, but not both."""
246 if "columns" in values and "expressions" in values:
247 raise ValueError("Defining columns and expressions is not valid")
248 elif "columns" not in values and "expressions" not in values:
249 raise ValueError("Must define columns or expressions")
250 return values
253class ForeignKeyConstraint(Constraint):
254 """A foreign key constraint on a table.
256 These will be reflected in the TAP_SCHEMA keys and key_columns data.
257 """
259 columns: list[str]
260 """The columns comprising the foreign key."""
262 referenced_columns: list[str] = Field(alias="referencedColumns")
263 """The columns referenced by the foreign key."""
266class Table(BaseObject):
267 """A database table."""
269 columns: Sequence[Column]
270 """The columns in the table."""
272 constraints: list[Constraint] = Field(default_factory=list)
273 """The constraints on the table."""
275 indexes: list[Index] = Field(default_factory=list)
276 """The indexes on the table."""
278 primaryKey: str | list[str] | None = None
279 """The primary key of the table."""
281 tap_table_index: int | None = Field(None, alias="tap:table_index")
282 """The IVOA TAP_SCHEMA table index of the table."""
284 mysql_engine: str | None = Field(None, alias="mysql:engine")
285 """The mysql engine to use for the table.
287 For now this is a freeform string but it could be constrained to a list of
288 known engines in the future.
289 """
291 mysql_charset: str | None = Field(None, alias="mysql:charset")
292 """The mysql charset to use for the table.
294 For now this is a freeform string but it could be constrained to a list of
295 known charsets in the future.
296 """
298 @model_validator(mode="before")
299 @classmethod
300 def create_constraints(cls, values: dict[str, Any]) -> dict[str, Any]:
301 """Create constraints from the ``constraints`` field."""
302 if "constraints" in values:
303 new_constraints: list[Constraint] = []
304 for item in values["constraints"]:
305 if item["@type"] == "ForeignKey":
306 new_constraints.append(ForeignKeyConstraint(**item))
307 elif item["@type"] == "Unique":
308 new_constraints.append(UniqueConstraint(**item))
309 elif item["@type"] == "Check":
310 new_constraints.append(CheckConstraint(**item))
311 else:
312 raise ValueError(f"Unknown constraint type: {item['@type']}")
313 values["constraints"] = new_constraints
314 return values
316 @field_validator("columns", mode="after")
317 @classmethod
318 def check_unique_column_names(cls, columns: list[Column]) -> list[Column]:
319 """Check that column names are unique."""
320 if len(columns) != len(set(column.name for column in columns)):
321 raise ValueError("Column names must be unique")
322 return columns
325class SchemaVersion(BaseModel):
326 """The version of the schema."""
328 current: str
329 """The current version of the schema."""
331 compatible: list[str] = Field(default_factory=list)
332 """The compatible versions of the schema."""
334 read_compatible: list[str] = Field(default_factory=list)
335 """The read compatible versions of the schema."""
338class SchemaIdVisitor:
339 """Visitor to build a Schema object's map of IDs to objects.
341 Duplicates are added to a set when they are encountered, which can be
342 accessed via the `duplicates` attribute. The presence of duplicates will
343 not throw an error. Only the first object with a given ID will be added to
344 the map, but this should not matter, since a ValidationError will be thrown
345 by the `model_validator` method if any duplicates are found in the schema.
347 This class is intended for internal use only.
348 """
350 def __init__(self) -> None:
351 """Create a new SchemaVisitor."""
352 self.schema: "Schema" | None = None
353 self.duplicates: set[str] = set()
355 def add(self, obj: BaseObject) -> None:
356 """Add an object to the ID map."""
357 if hasattr(obj, "id"):
358 obj_id = getattr(obj, "id")
359 if self.schema is not None:
360 if obj_id in self.schema.id_map:
361 self.duplicates.add(obj_id)
362 else:
363 self.schema.id_map[obj_id] = obj
365 def visit_schema(self, schema: "Schema") -> None:
366 """Visit the schema object that was added during initialization.
368 This will set an internal variable pointing to the schema object.
369 """
370 self.schema = schema
371 self.duplicates.clear()
372 self.add(self.schema)
373 for table in self.schema.tables:
374 self.visit_table(table)
376 def visit_table(self, table: Table) -> None:
377 """Visit a table object."""
378 self.add(table)
379 for column in table.columns:
380 self.visit_column(column)
381 for constraint in table.constraints:
382 self.visit_constraint(constraint)
384 def visit_column(self, column: Column) -> None:
385 """Visit a column object."""
386 self.add(column)
388 def visit_constraint(self, constraint: Constraint) -> None:
389 """Visit a constraint object."""
390 self.add(constraint)
393class Schema(BaseObject):
394 """The database schema containing the tables."""
396 class ValidationConfig:
397 """Validation configuration which is specific to Felis."""
399 _require_description = False
400 """Flag to require a description for all objects.
402 This is set by the `require_description` class method.
403 """
405 version: SchemaVersion | str | None = None
406 """The version of the schema."""
408 tables: Sequence[Table]
409 """The tables in the schema."""
411 id_map: dict[str, Any] = Field(default_factory=dict, exclude=True)
412 """Map of IDs to objects."""
414 @field_validator("tables", mode="after")
415 @classmethod
416 def check_unique_table_names(cls, tables: list[Table]) -> list[Table]:
417 """Check that table names are unique."""
418 if len(tables) != len(set(table.name for table in tables)):
419 raise ValueError("Table names must be unique")
420 return tables
422 @model_validator(mode="after")
423 def create_id_map(self: Schema) -> Schema:
424 """Create a map of IDs to objects."""
425 visitor: SchemaIdVisitor = SchemaIdVisitor()
426 visitor.visit_schema(self)
427 logger.debug(f"ID map contains {len(self.id_map.keys())} objects")
428 if len(visitor.duplicates):
429 raise ValueError(
430 "Duplicate IDs found in schema:\n " + "\n ".join(visitor.duplicates) + "\n"
431 )
432 return self
434 def __getitem__(self, id: str) -> BaseObject:
435 """Get an object by its ID."""
436 if id not in self:
437 raise KeyError(f"Object with ID '{id}' not found in schema")
438 return self.id_map[id]
440 def __contains__(self, id: str) -> bool:
441 """Check if an object with the given ID is in the schema."""
442 return id in self.id_map
444 @classmethod
445 def require_description(cls, rd: bool = True) -> None:
446 """Set whether a description is required for all objects.
448 This includes the schema, tables, columns, and constraints.
450 Users should call this method to set the requirement for a description
451 when validating schemas, rather than change the flag value directly.
452 """
453 logger.debug(f"Setting description requirement to '{rd}'")
454 cls.ValidationConfig._require_description = rd
456 @classmethod
457 def is_description_required(cls) -> bool:
458 """Return whether a description is required for all objects."""
459 return cls.ValidationConfig._require_description