Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
133 lines
4.8 KiB
Python
133 lines
4.8 KiB
Python
"""Column definitions, type checking and row building."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from dataclasses import dataclass
|
|
from typing import Any, Dict, Iterable, List, Mapping
|
|
|
|
from .errors import SchemaError
|
|
|
|
TYPES = ("int", "float", "str", "bool")
|
|
|
|
# Words with a fixed meaning in the query language; they cannot name columns.
|
|
RESERVED_WORDS = frozenset(
|
|
{"AND", "OR", "NOT", "IN", "BETWEEN", "LIKE", "ILIKE", "IS", "NULL", "TRUE", "FALSE"}
|
|
)
|
|
|
|
_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Column:
|
|
name: str
|
|
type: str = "str"
|
|
nullable: bool = True
|
|
default: Any = None
|
|
|
|
def __post_init__(self) -> None:
|
|
if not _NAME.fullmatch(self.name):
|
|
raise SchemaError("invalid column name: %r" % (self.name,))
|
|
if self.name.upper() in RESERVED_WORDS:
|
|
raise SchemaError("column name is a reserved word: %s" % self.name)
|
|
if self.type not in TYPES:
|
|
raise SchemaError("unknown column type: %r" % (self.type,))
|
|
if self.default is not None:
|
|
object.__setattr__(self, "default", coerce_value(self, self.default))
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {"name": self.name, "type": self.type, "nullable": self.nullable, "default": self.default}
|
|
|
|
|
|
def coerce_value(column: Column, value: Any) -> Any:
|
|
"""Check ``value`` against the column type and return the value to store."""
|
|
if value is None:
|
|
if not column.nullable:
|
|
raise SchemaError("column %s may not be NULL" % column.name)
|
|
return None
|
|
is_number = isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
if column.type == "int" and isinstance(value, int) and is_number:
|
|
return value
|
|
if column.type == "float" and is_number:
|
|
return float(value)
|
|
if column.type == "str" and isinstance(value, str):
|
|
return value
|
|
if column.type == "bool" and isinstance(value, bool):
|
|
return value
|
|
raise SchemaError("column %s expects %s, got %s" % (column.name, column.type, type(value).__name__))
|
|
|
|
|
|
def parse_text(column: Column, text: str) -> Any:
|
|
"""Convert text from a CSV file or the command line; empty text means NULL."""
|
|
if text == "":
|
|
return coerce_value(column, None)
|
|
try:
|
|
if column.type == "int":
|
|
value: Any = int(text)
|
|
elif column.type == "float":
|
|
value = float(text)
|
|
elif column.type == "bool":
|
|
lowered = text.lower()
|
|
if lowered not in ("true", "false"):
|
|
raise ValueError(text)
|
|
value = lowered == "true"
|
|
else:
|
|
value = text
|
|
except ValueError:
|
|
raise SchemaError("column %s expects %s, got %r" % (column.name, column.type, text)) from None
|
|
return coerce_value(column, value)
|
|
|
|
|
|
class Schema:
|
|
"""An ordered set of columns; the first column is always the integer row id."""
|
|
|
|
ID = Column("id", "int", nullable=False)
|
|
|
|
def __init__(self, columns: Iterable[Column]) -> None:
|
|
self.columns: List[Column] = [self.ID]
|
|
seen = {"id"}
|
|
for column in columns:
|
|
if column.name in seen:
|
|
raise SchemaError("duplicate column: %s" % column.name)
|
|
seen.add(column.name)
|
|
self.columns.append(column)
|
|
|
|
def names(self) -> List[str]:
|
|
return [c.name for c in self.columns]
|
|
|
|
def has(self, name: str) -> bool:
|
|
return any(c.name == name for c in self.columns)
|
|
|
|
def column(self, name: str) -> Column:
|
|
for column in self.columns:
|
|
if column.name == name:
|
|
return column
|
|
raise SchemaError("unknown column: %s" % name)
|
|
|
|
def build_row(self, values: Mapping[str, Any], row_id: int) -> Dict[str, Any]:
|
|
"""A complete row for ``values``: defaults fill the gaps, unknown names are rejected."""
|
|
for name in values:
|
|
if name == "id":
|
|
raise SchemaError("the id column is assigned automatically")
|
|
self.column(name)
|
|
row: Dict[str, Any] = {"id": row_id}
|
|
for column in self.columns[1:]:
|
|
row[column.name] = coerce_value(column, values.get(column.name, column.default))
|
|
return row
|
|
|
|
def coerce_changes(self, values: Mapping[str, Any]) -> Dict[str, Any]:
|
|
"""Validated partial values for an update."""
|
|
changes: Dict[str, Any] = {}
|
|
for name, value in values.items():
|
|
if name == "id":
|
|
raise SchemaError("the id column cannot be changed")
|
|
changes[name] = coerce_value(self.column(name), value)
|
|
return changes
|
|
|
|
def to_dict(self) -> List[Dict[str, Any]]:
|
|
return [c.to_dict() for c in self.columns[1:]]
|
|
|
|
@classmethod
|
|
def from_dict(cls, spec: List[Dict[str, Any]]) -> "Schema":
|
|
return cls(Column(**item) for item in spec)
|