Files
leleka/scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/table.py
T

200 lines
7.3 KiB
Python

"""Tables and the database that owns them."""
from __future__ import annotations
from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Union
from .errors import RowNotFound, SchemaError, TableError
from .index import HashIndex
from .query import compile_where
from .schema import Column, Schema
from .storage import MemoryStorage
Row = Dict[str, Any]
Predicate = Callable[[Row], Any]
Where = Union[None, str, Predicate]
class Table:
"""Rows of one schema, kept in insertion order and addressed by integer id."""
def __init__(self, name: str, schema: Schema) -> None:
self.name = name
self.schema = schema
self._rows: Dict[int, Row] = {}
self._next_id = 1
self._indexes: Dict[str, HashIndex] = {}
def __len__(self) -> int:
return len(self._rows)
# -- writing ---------------------------------------------------------
def insert(self, **values: Any) -> int:
"""Add a row and return its id."""
row = self.schema.build_row(values, self._next_id)
self._rows[row["id"]] = row
self._next_id += 1
for index in self._indexes.values():
index.add(row)
return row["id"]
def insert_many(self, rows: Iterable[Mapping[str, Any]]) -> List[int]:
return [self.insert(**row) for row in rows]
def update(self, values: Mapping[str, Any], where: Where = None) -> int:
"""Change the matching rows (all rows without ``where``); returns how many changed."""
changes = self.schema.coerce_changes(values)
matches = self._matcher(where)
targets = [row for row in self._rows.values() if matches(row)]
for row in targets:
for index in self._indexes.values():
index.remove(row)
row.update(changes)
for index in self._indexes.values():
index.add(row)
return len(targets)
def delete(self, where: Where = None) -> int:
"""Remove the matching rows (all rows without ``where``); returns how many were removed."""
matches = self._matcher(where)
targets = [row for row in self._rows.values() if matches(row)]
for row in targets:
del self._rows[row["id"]]
for index in self._indexes.values():
index.remove(row)
return len(targets)
# -- reading ---------------------------------------------------------
def get(self, row_id: int) -> Row:
try:
return dict(self._rows[row_id])
except KeyError:
raise RowNotFound("no row with id %r in table %s" % (row_id, self.name)) from None
def find(self, column: str, value: Any) -> List[Row]:
"""Rows whose ``column`` equals ``value``; uses the index when there is one."""
self.schema.column(column)
index = self._indexes.get(column)
if index is not None:
return [dict(self._rows[i]) for i in index.lookup(value)]
return [dict(r) for r in self._rows.values() if r[column] is not None and r[column] == value]
def select(
self,
where: Where = None,
columns: Optional[Sequence[str]] = None,
order_by: Optional[str] = None,
descending: bool = False,
limit: Optional[int] = None,
) -> List[Row]:
"""Rows selected by ``where`` (a callable or a query string), optionally sorted, limited and projected.
Rows whose ``order_by`` value is NULL always come last.
"""
matches = self._matcher(where)
rows = [row for row in self._rows.values() if matches(row)]
if order_by is not None:
rows = self._ordered(rows, order_by, descending)
if limit is not None:
rows = rows[:limit]
return [self._project(row, columns) for row in rows]
def count(self, where: Where = None) -> int:
matches = self._matcher(where)
return sum(1 for row in self._rows.values() if matches(row))
# -- indexes ---------------------------------------------------------
def create_index(self, column: str) -> None:
self.schema.column(column)
if column in self._indexes:
raise TableError("column %s is already indexed" % column)
index = HashIndex(column)
index.rebuild(self._rows.values())
self._indexes[column] = index
def indexed_columns(self) -> List[str]:
return sorted(self._indexes)
# -- internals -------------------------------------------------------
def _matcher(self, where: Where) -> Predicate:
if where is None:
return lambda row: True
if isinstance(where, str):
return compile_where(where, self.schema.names())
if callable(where):
return where
raise TypeError("where must be a string, a callable or None, not %s" % type(where).__name__)
def _ordered(self, rows: List[Row], order_by: str, descending: bool) -> List[Row]:
self.schema.column(order_by)
present = [row for row in rows if row[order_by] is not None]
missing = [row for row in rows if row[order_by] is None]
present.sort(key=lambda row: row[order_by], reverse=descending)
return present + missing
def _project(self, row: Row, columns: Optional[Sequence[str]]) -> Row:
if columns is None:
return dict(row)
for name in columns:
self.schema.column(name)
return {name: row[name] for name in columns}
# -- persistence -----------------------------------------------------
def to_dict(self) -> Dict[str, Any]:
return {
"schema": self.schema.to_dict(),
"next_id": self._next_id,
"indexes": self.indexed_columns(),
"rows": [dict(row) for row in self._rows.values()],
}
@classmethod
def from_dict(cls, name: str, spec: Mapping[str, Any]) -> "Table":
table = cls(name, Schema.from_dict(spec["schema"]))
for row in spec["rows"]:
table._rows[row["id"]] = dict(row)
table._next_id = spec["next_id"]
for column in spec.get("indexes", []):
table.create_index(column)
return table
class Database:
"""A named collection of tables backed by a storage object."""
def __init__(self, storage: Optional[Any] = None) -> None:
self.storage = storage if storage is not None else MemoryStorage()
self._tables: Dict[str, Table] = {}
data = self.storage.load()
if data:
for name, spec in data["tables"].items():
self._tables[name] = Table.from_dict(name, spec)
def create_table(self, name: str, columns: Iterable[Column]) -> Table:
if name in self._tables:
raise TableError("table already exists: %s" % name)
table = Table(name, Schema(columns))
self._tables[name] = table
return table
def table(self, name: str) -> Table:
try:
return self._tables[name]
except KeyError:
raise TableError("no such table: %s" % name) from None
def drop_table(self, name: str) -> None:
self.table(name)
del self._tables[name]
def table_names(self) -> List[str]:
return sorted(self._tables)
def save(self) -> None:
self.storage.save({"version": 1, "tables": {n: t.to_dict() for n, t in self._tables.items()}})