Source code for scim2_sqlalchemy.constraints

from typing import Any

from sqlalchemy import Column
from sqlalchemy import ColumnElement
from sqlalchemy import FunctionElement
from sqlalchemy import String
from sqlalchemy import UniqueConstraint
from sqlalchemy import column as sql_column
from sqlalchemy import func
from sqlalchemy import literal_column
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.compiler import SQLCompiler


[docs] class UniqueConstraintWarning(UserWarning): """A unique attribute that no unique constraint of the database covers. The database checks the unique values, so the storage lets such an attribute take a value that another resource holds. """
def _postgresql_form(expression: Any, casefolded: bool) -> ColumnElement[Any]: """Return a string expression normalized to NFC, lowered if casefolded, under the C collation.""" normalized = func.normalize(expression, literal_column("NFC"), type_=String) if casefolded: normalized = func.normalize( func.lower(normalized), literal_column("NFC"), type_=String ) return normalized.collate("C") class _Utf8mb4(FunctionElement[str]): """A string converted to utf8mb4, the character set of the MariaDB collations.""" type = String() inherit_cache = True @compiles(_Utf8mb4) def _compile_utf8mb4(element: _Utf8mb4, compiler: SQLCompiler, **kw: Any) -> str: """Write the conversion of a string to utf8mb4.""" (expression,) = element.clauses return f"CONVERT({compiler.process(expression, **kw)} USING utf8mb4)" def _mariadb_form(expression: Any, casefolded: bool) -> ColumnElement[Any]: """Return a string expression in utf8mb4, lowered if casefolded, under a binary collation.""" converted: ColumnElement[Any] = _Utf8mb4(expression) if casefolded: converted = func.lower( converted.collate("utf8mb4_uca1400_nopad_as_cs"), type_=String ) return converted.collate("utf8mb4_nopad_bin") class _ComparisonKey(FunctionElement[str]): """The form in which the storage compares a string column that ignores the case.""" type = String() inherit_cache = True @property def source(self) -> str: """Return the name of the column the key is computed from.""" (column,) = self.clauses return str(column.name) @compiles(_ComparisonKey) def _compile_key(element: _ComparisonKey, compiler: SQLCompiler, **kw: Any) -> str: """Write the key with lower(), which only lowers ASCII letters on SQLite.""" (column,) = element.clauses return compiler.process(func.lower(column), **kw) @compiles(_ComparisonKey, "postgresql") def _compile_postgresql_key( element: _ComparisonKey, compiler: SQLCompiler, **kw: Any ) -> str: """Write the key as the PostgreSQL storage compares the strings.""" (column,) = element.clauses return compiler.process(_postgresql_form(column, True), **kw) @compiles(_ComparisonKey, "mysql") @compiles(_ComparisonKey, "mariadb") def _compile_mariadb_key( element: _ComparisonKey, compiler: SQLCompiler, **kw: Any ) -> str: """Write the key as the MariaDB storage compares the strings.""" (column,) = element.clauses return compiler.process(_mariadb_form(column, True), **kw)
[docs] def comparison_key(column: str) -> ColumnElement[str]: """Return the SQL expression of a column in the form the storage compares it, ignoring the case. A unique column computed from this expression refuses two values that the filters of the storage find equal, such as ``bjensen`` and ``BJensen``. Declare it for each unique attribute that ignores the case, such as ``userName``: >>> from sqlalchemy import Computed >>> from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column >>> from scim2_sqlalchemy import comparison_key >>> class Base(DeclarativeBase): ... pass >>> class UserRecord(Base): ... __tablename__ = "users" ... id: Mapped[int] = mapped_column(primary_key=True) ... user_name: Mapped[str] ... user_name_key: Mapped[str | None] = mapped_column( ... Computed(comparison_key("user_name"), persisted=True), unique=True ... ) On MariaDB, give the column a binary collation, such as ``utf8mb4_nopad_bin``: the default collations ignore the accents, and refuse ``élise`` next to ``elise``. On SQLite, the expression only lowers the ASCII letters, while the filters follow the comparison key of the policy: two values that differ by the case of another letter, such as ``Élise`` and ``élise``, are both accepted. :param column: The name of the column in its table. """ return _ComparisonKey(sql_column(column))
def _unique_on(column: Column[Any]) -> bool: """Tell whether a unique constraint of its table covers this column alone.""" table = column.table if column.unique or list(table.primary_key.columns) == [column]: return True constraints = [ list(constraint.columns) for constraint in table.constraints if isinstance(constraint, UniqueConstraint) ] indexes = [list(index.expressions) for index in table.indexes if index.unique] return [column] in constraints + indexes def _key_columns(column: Column[Any]) -> list[Column[Any]]: """Return the columns of its table computed from the comparison_key() of a column.""" return [ key for key in column.table.columns if key.computed is not None and isinstance(key.computed.sqltext, _ComparisonKey) and key.computed.sqltext.source == column.name ] def _constrained(column: Column[Any], casefolded: bool) -> bool: """Tell whether a unique constraint refuses two values of a column that the storage finds equal. A column that ignores the case needs a unique column computed from its comparison_key(). """ if not casefolded: return _unique_on(column) return any(_unique_on(key) for key in _key_columns(column))