Coverage for python/felis/datamodel.py: 62%
242 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-03-20 03:38 -0700
« prev ^ index » next coverage.py v7.4.4, created at 2024-03-20 03:38 -0700
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 Annotated, Any, Literal, TypeAlias
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 "DescriptionStr",
42 "ForeignKeyConstraint",
43 "Index",
44 "Schema",
45 "SchemaVersion",
46 "Table",
47 "UniqueConstraint",
48)
50CONFIG = ConfigDict(
51 populate_by_name=True, # Populate attributes by name.
52 extra="forbid", # Do not allow extra fields.
53 use_enum_values=True, # Use enum values instead of names.
54 validate_assignment=True, # Validate assignments after model is created.
55 str_strip_whitespace=True, # Strip whitespace from string fields.
56)
57"""Pydantic model configuration as described in:
58https://docs.pydantic.dev/2.0/api/config/#pydantic.config.ConfigDict
59"""
61DESCR_MIN_LENGTH = 3
62"""Minimum length for a description field."""
64DescriptionStr: TypeAlias = Annotated[str, Field(min_length=DESCR_MIN_LENGTH)]
65"""Define a type for a description string, which must be three or more
66characters long. Stripping of whitespace is done globally on all str fields."""
69class BaseObject(BaseModel):
70 """Base class for all Felis objects."""
72 model_config = CONFIG
73 """Pydantic model configuration."""
75 name: str
76 """The name of the database object.
78 All Felis database objects must have a name.
79 """
81 id: str = Field(alias="@id")
82 """The unique identifier of the database object.
84 All Felis database objects must have a unique identifier.
85 """
87 description: DescriptionStr | None = None
88 """A description of the database object.
90 By default, the description is optional but will be required if
91 `BaseObject.Config.require_description` is set to `True` by the user.
92 """
94 @model_validator(mode="before")
95 @classmethod
96 def check_description(cls, values: dict[str, Any]) -> dict[str, Any]:
97 """Check that the description is present if required."""
98 if Schema.is_description_required():
99 if "description" not in values or not values["description"]:
100 raise ValueError("Description is required and must be non-empty")
101 if len(values["description"].strip()) < DESCR_MIN_LENGTH:
102 raise ValueError(f"Description must be at least {DESCR_MIN_LENGTH} characters long")
103 return values
106class DataType(Enum):
107 """`Enum` representing the data types supported by Felis."""
109 BOOLEAN = "boolean"
110 BYTE = "byte"
111 SHORT = "short"
112 INT = "int"
113 LONG = "long"
114 FLOAT = "float"
115 DOUBLE = "double"
116 CHAR = "char"
117 STRING = "string"
118 UNICODE = "unicode"
119 TEXT = "text"
120 BINARY = "binary"
121 TIMESTAMP = "timestamp"
124class Column(BaseObject):
125 """A column in a table."""
127 datatype: DataType
128 """The datatype of the column."""
130 length: int | None = None
131 """The length of the column."""
133 nullable: bool = True
134 """Whether the column can be `NULL`."""
136 value: Any = None
137 """The default value of the column."""
139 autoincrement: bool | None = None
140 """Whether the column is autoincremented."""
142 mysql_datatype: str | None = Field(None, alias="mysql:datatype")
143 """The MySQL datatype of the column."""
145 ivoa_ucd: str | None = Field(None, alias="ivoa:ucd")
146 """The IVOA UCD of the column."""
148 fits_tunit: str | None = Field(None, alias="fits:tunit")
149 """The FITS TUNIT of the column."""
151 ivoa_unit: str | None = Field(None, alias="ivoa:unit")
152 """The IVOA unit of the column."""
154 tap_column_index: int | None = Field(None, alias="tap:column_index")
155 """The TAP_SCHEMA column index of the column."""
157 tap_principal: int | None = Field(0, alias="tap:principal", ge=0, le=1)
158 """Whether this is a TAP_SCHEMA principal column; can be either 0 or 1.
159 """
161 votable_arraysize: int | Literal["*"] | None = Field(None, alias="votable:arraysize")
162 """The VOTable arraysize of the column."""
164 tap_std: int | None = Field(0, alias="tap:std", ge=0, le=1)
165 """TAP_SCHEMA indication that this column is defined by an IVOA standard.
166 """
168 votable_utype: str | None = Field(None, alias="votable:utype")
169 """The VOTable utype (usage-specific or unique type) of the column."""
171 votable_xtype: str | None = Field(None, alias="votable:xtype")
172 """The VOTable xtype (extended type) of the column."""
174 @field_validator("ivoa_ucd")
175 @classmethod
176 def check_ivoa_ucd(cls, ivoa_ucd: str) -> str:
177 """Check that IVOA UCD values are valid."""
178 if ivoa_ucd is not None:
179 try:
180 ucd.parse_ucd(ivoa_ucd, check_controlled_vocabulary=True, has_colon=";" in ivoa_ucd)
181 except ValueError as e:
182 raise ValueError(f"Invalid IVOA UCD: {e}")
183 return ivoa_ucd
185 @model_validator(mode="before")
186 @classmethod
187 def check_units(cls, values: dict[str, Any]) -> dict[str, Any]:
188 """Check that units are valid."""
189 fits_unit = values.get("fits:tunit")
190 ivoa_unit = values.get("ivoa:unit")
192 if fits_unit and ivoa_unit:
193 raise ValueError("Column cannot have both FITS and IVOA units")
194 unit = fits_unit or ivoa_unit
196 if unit is not None:
197 try:
198 units.Unit(unit)
199 except ValueError as e:
200 raise ValueError(f"Invalid unit: {e}")
202 return values
205class Constraint(BaseObject):
206 """A database table constraint."""
208 deferrable: bool = False
209 """If `True` then this constraint will be declared as deferrable."""
211 initially: str | None = None
212 """Value for ``INITIALLY`` clause, only used if ``deferrable`` is True."""
214 annotations: Mapping[str, Any] = Field(default_factory=dict)
215 """Additional annotations for this constraint."""
217 type: str | None = Field(None, alias="@type")
218 """The type of the constraint."""
221class CheckConstraint(Constraint):
222 """A check constraint on a table."""
224 expression: str
225 """The expression for the check constraint."""
228class UniqueConstraint(Constraint):
229 """A unique constraint on a table."""
231 columns: list[str]
232 """The columns in the unique constraint."""
235class Index(BaseObject):
236 """A database table index.
238 An index can be defined on either columns or expressions, but not both.
239 """
241 columns: list[str] | None = None
242 """The columns in the index."""
244 expressions: list[str] | None = None
245 """The expressions in the index."""
247 @model_validator(mode="before")
248 @classmethod
249 def check_columns_or_expressions(cls, values: dict[str, Any]) -> dict[str, Any]:
250 """Check that columns or expressions are specified, but not both."""
251 if "columns" in values and "expressions" in values:
252 raise ValueError("Defining columns and expressions is not valid")
253 elif "columns" not in values and "expressions" not in values:
254 raise ValueError("Must define columns or expressions")
255 return values
258class ForeignKeyConstraint(Constraint):
259 """A foreign key constraint on a table.
261 These will be reflected in the TAP_SCHEMA keys and key_columns data.
262 """
264 columns: list[str]
265 """The columns comprising the foreign key."""
267 referenced_columns: list[str] = Field(alias="referencedColumns")
268 """The columns referenced by the foreign key."""
271class Table(BaseObject):
272 """A database table."""
274 columns: Sequence[Column]
275 """The columns in the table."""
277 constraints: list[Constraint] = Field(default_factory=list)
278 """The constraints on the table."""
280 indexes: list[Index] = Field(default_factory=list)
281 """The indexes on the table."""
283 primaryKey: str | list[str] | None = None
284 """The primary key of the table."""
286 tap_table_index: int | None = Field(None, alias="tap:table_index")
287 """The IVOA TAP_SCHEMA table index of the table."""
289 mysql_engine: str | None = Field(None, alias="mysql:engine")
290 """The mysql engine to use for the table.
292 For now this is a freeform string but it could be constrained to a list of
293 known engines in the future.
294 """
296 mysql_charset: str | None = Field(None, alias="mysql:charset")
297 """The mysql charset to use for the table.
299 For now this is a freeform string but it could be constrained to a list of
300 known charsets in the future.
301 """
303 @model_validator(mode="before")
304 @classmethod
305 def create_constraints(cls, values: dict[str, Any]) -> dict[str, Any]:
306 """Create constraints from the ``constraints`` field."""
307 if "constraints" in values:
308 new_constraints: list[Constraint] = []
309 for item in values["constraints"]:
310 if item["@type"] == "ForeignKey":
311 new_constraints.append(ForeignKeyConstraint(**item))
312 elif item["@type"] == "Unique":
313 new_constraints.append(UniqueConstraint(**item))
314 elif item["@type"] == "Check":
315 new_constraints.append(CheckConstraint(**item))
316 else:
317 raise ValueError(f"Unknown constraint type: {item['@type']}")
318 values["constraints"] = new_constraints
319 return values
321 @field_validator("columns", mode="after")
322 @classmethod
323 def check_unique_column_names(cls, columns: list[Column]) -> list[Column]:
324 """Check that column names are unique."""
325 if len(columns) != len(set(column.name for column in columns)):
326 raise ValueError("Column names must be unique")
327 return columns
330class SchemaVersion(BaseModel):
331 """The version of the schema."""
333 current: str
334 """The current version of the schema."""
336 compatible: list[str] = Field(default_factory=list)
337 """The compatible versions of the schema."""
339 read_compatible: list[str] = Field(default_factory=list)
340 """The read compatible versions of the schema."""
343class SchemaIdVisitor:
344 """Visitor to build a Schema object's map of IDs to objects.
346 Duplicates are added to a set when they are encountered, which can be
347 accessed via the `duplicates` attribute. The presence of duplicates will
348 not throw an error. Only the first object with a given ID will be added to
349 the map, but this should not matter, since a ValidationError will be thrown
350 by the `model_validator` method if any duplicates are found in the schema.
352 This class is intended for internal use only.
353 """
355 def __init__(self) -> None:
356 """Create a new SchemaVisitor."""
357 self.schema: "Schema" | None = None
358 self.duplicates: set[str] = set()
360 def add(self, obj: BaseObject) -> None:
361 """Add an object to the ID map."""
362 if hasattr(obj, "id"):
363 obj_id = getattr(obj, "id")
364 if self.schema is not None:
365 if obj_id in self.schema.id_map:
366 self.duplicates.add(obj_id)
367 else:
368 self.schema.id_map[obj_id] = obj
370 def visit_schema(self, schema: "Schema") -> None:
371 """Visit the schema object that was added during initialization.
373 This will set an internal variable pointing to the schema object.
374 """
375 self.schema = schema
376 self.duplicates.clear()
377 self.add(self.schema)
378 for table in self.schema.tables:
379 self.visit_table(table)
381 def visit_table(self, table: Table) -> None:
382 """Visit a table object."""
383 self.add(table)
384 for column in table.columns:
385 self.visit_column(column)
386 for constraint in table.constraints:
387 self.visit_constraint(constraint)
389 def visit_column(self, column: Column) -> None:
390 """Visit a column object."""
391 self.add(column)
393 def visit_constraint(self, constraint: Constraint) -> None:
394 """Visit a constraint object."""
395 self.add(constraint)
398class Schema(BaseObject):
399 """The database schema containing the tables."""
401 class ValidationConfig:
402 """Validation configuration which is specific to Felis."""
404 _require_description = False
405 """Flag to require a description for all objects.
407 This is set by the `require_description` class method.
408 """
410 version: SchemaVersion | str | None = None
411 """The version of the schema."""
413 tables: Sequence[Table]
414 """The tables in the schema."""
416 id_map: dict[str, Any] = Field(default_factory=dict, exclude=True)
417 """Map of IDs to objects."""
419 @field_validator("tables", mode="after")
420 @classmethod
421 def check_unique_table_names(cls, tables: list[Table]) -> list[Table]:
422 """Check that table names are unique."""
423 if len(tables) != len(set(table.name for table in tables)):
424 raise ValueError("Table names must be unique")
425 return tables
427 @model_validator(mode="after")
428 def create_id_map(self: Schema) -> Schema:
429 """Create a map of IDs to objects."""
430 visitor: SchemaIdVisitor = SchemaIdVisitor()
431 visitor.visit_schema(self)
432 logger.debug(f"ID map contains {len(self.id_map.keys())} objects")
433 if len(visitor.duplicates):
434 raise ValueError(
435 "Duplicate IDs found in schema:\n " + "\n ".join(visitor.duplicates) + "\n"
436 )
437 return self
439 def __getitem__(self, id: str) -> BaseObject:
440 """Get an object by its ID."""
441 if id not in self:
442 raise KeyError(f"Object with ID '{id}' not found in schema")
443 return self.id_map[id]
445 def __contains__(self, id: str) -> bool:
446 """Check if an object with the given ID is in the schema."""
447 return id in self.id_map
449 @classmethod
450 def require_description(cls, rd: bool = True) -> None:
451 """Set whether a description is required for all objects.
453 This includes the schema, tables, columns, and constraints.
455 Users should call this method to set the requirement for a description
456 when validating schemas, rather than change the flag value directly.
457 """
458 logger.debug(f"Setting description requirement to '{rd}'")
459 cls.ValidationConfig._require_description = rd
461 @classmethod
462 def is_description_required(cls) -> bool:
463 """Return whether a description is required for all objects."""
464 return cls.ValidationConfig._require_description