RpRelPyDBRelational Python

Documentation

17. API Reference

Every public function, class, signature, return type, and usage note in one place.

Core imports

from relpy import RelPy, AutoNumber, col, AND, OR, NOT
from relpy import count, sum_, avg, min_, max_
from relpy import (
    RelPyError, SchemaError, TableNotFoundError, ColumnNotFoundError,
    ConstraintError, QueryError, QueryTypeError, ViewError,
    NoRowsFoundError, MultipleRowsFoundError, EncryptionError,
)

Schema

FunctionSignatureReturns
create_tablecreate_table(table_name: str) → selfCreates an empty table.
add_columnadd_column(table, name, type, *, is_primary_key, nullable, default, references, on_delete, is_pii, is_encrypted) → selfAdds a typed column with optional constraints.
set_primary_keyset_primary_key(table: str, columns: list[str]) → selfDefines a composite primary key.
describe_tabledescribe_table(table: str) → dictColumn metadata for one table.
describe_schemadescribe_schema() → dictFull schema metadata for all tables.

Data operations

FunctionSignatureReturns
insertinsert(table: str, values: dict) → dictInserts one row; returns the stored row (plaintext).
insert_manyinsert_many(table: str, rows: list[dict]) → list[dict]Batch insert with optimised index rebuild.
updateupdate(table, values, where=None, allow_all=False) → intUpdates matching rows. Returns count updated.
deletedelete(table, where=None, allow_all=False) → intDeletes matching rows. Returns count deleted.

Query builder (chainable)

All methods below are called on the object returned by db.query(table).

MethodDescription
.where(condition)Filter rows. Accepts col() conditions, AND(), OR(), NOT().
.select(*columns)Project specific columns by name.
.order_by(col, descending=False)Sort by one or more columns. Alias: .orderby().
.limit(n)Return at most n rows.
.offset(n)Skip the first n rows.
.distinct()Remove duplicate rows from projected result.
.join(table, on=None, left_on=None, right_on=None, method="inner")Join another table. FK inferred automatically if on not given.
.inner_join(table)Shortcut for method="inner".
.left_join(table)Shortcut for method="left".
.right_join(table)Shortcut for method="right".
.full_join(table)Shortcut for method="full".
.cross_join(table)Cartesian product.
.natural_join(table)Join on columns with matching names.
.group_by(*columns)Switch query to grouped mode.
.aggregate(**kwargs)Define aggregate expressions. Each kwarg becomes a result column.
.having(condition)Filter on aggregated values. Must follow .aggregate().

Terminal methods

MethodReturnsNotes
.to_list()list[dict]Execute query, return all rows.
.first()dict | NoneFirst row or None.
.one()dictExactly one row; raises on 0 or 2+.
.exists()boolTrue if at least one row matches.
.pluck(column)listFlat list of values for one column.
.count()intRow count.
.sum(column)numberSum of column.
.avg(column) / .average()floatMean of column.
.min(column)valueMinimum value.
.max(column)valueMaximum value.

col() expressions

col("x") == v       col("x") != v
col("x") > v        col("x") >= v
col("x") < v        col("x") <= v
col("x").like("%pattern%")
col("x").in_(["a", "b", "c"])
col("x").between(lo, hi)
col("x").is_null()
col("x").is_not_null()

# logical
(cond_a) & (cond_b)    # AND
(cond_a) | (cond_b)    # OR
~cond_a                # NOT

AND(cond_a, cond_b, ...)
OR(cond_a, cond_b, ...)
NOT(cond_a)

Aggregate functions (for use in .aggregate())

count()             # COUNT(*)
count("column")     # COUNT(column) — skips None
sum_("column")      # SUM(column)
avg("column")       # AVG(column)
min_("column")      # MIN(column)
max_("column")      # MAX(column)

Views

FunctionSignatureReturns
create_viewcreate_view(name: str, callable) → selfRegister a named query.
viewview(name: str) → QueryExecute the view callable and return its Query.
drop_viewdrop_view(name: str) → selfRemove a view.
list_viewslist_views() → list[str]All registered view names.
describe_viewdescribe_view(name: str) → dictMetadata for one view.
describe_viewsdescribe_views() → list[dict]Metadata for all views.

Indexes

FunctionSignatureNotes
create_indexcreate_index(table, column, unique=False) → selfAccepts a single column name or a list for composite indexes.
drop_indexdrop_index(index_name: str) → self
list_indexeslist_indexes() → list[str]
describe_indexdescribe_index(name: str) → dict
describe_indexesdescribe_indexes() → list[dict]

Exports

FunctionReturnsNotes
to_list(table, column_name=None, where_key=None, decrypt=False)list[dict] | listPython dicts. Pass decrypt=True to reveal encrypted values.
to_json(table, column_name=None, where_key=None, decrypt=False)strJSON string.
to_pandas(table, column_name=None, where_key=None, decrypt=False)DataFrameRequires pandas installed.
to_numpy(table, column_name=None, where_key=None, decrypt=False)ndarrayRequires NumPy installed.
to_sql(table, where_key=None, decrypt=False)strSQL INSERT statements.
to_ddl()strSQL CREATE TABLE statements for the full schema.
print_table(table, limit=None, decrypt=False)printsPretty-prints a table to stdout.

Persistence

FunctionSignatureNotes
savesave(path: str) → NoneSerialises schema, data, and index definitions to JSON. Views are not saved.
loadRelPy.load(path, encryption_key=None) → RelPyClass method. Restores full state including AutoNumber sequences.

Encryption

Function / flagNotes
RelPy.generate_encryption_key()Returns a new Fernet key as bytes. Store this securely — it is never saved to the JSON file.
RelPy(encryption_key=key)Pass key at construction time.
db.set_encryption_key(key)Set key after construction.
is_encrypted=True in add_columnEncrypts stored values; exports show [ENCRYPTED] by default.
decrypt=True in export functionsReveals plaintext. Requires a key to be loaded.