RpRelPyDBRelational Python

Documentation

18. Function Reference

Every main public object and function, with inputs, outputs, examples, import notes, and usage guidance.

About this reference

This page is a developer-focused function reference for RelPyDB. It explains what each public object or function does, which inputs it accepts, what it returns, and how to use it in small examples.

For a shorter table-style API overview, see API Reference. For a wider feature map, see Full Capability Checklist.

Common imports

from relpy import RelPy, AutoNumber, col
from relpy import AND, OR, NOT
from relpy import count, sum_, avg, min_, max_

Most schema and data operations only need RelPy and AutoNumber. Query filters usually need col. Grouped queries usually need count, sum_, avg, min_, and max_.

RelPyDB API Functions Reference

This document lists the main public functions and objects in RelPyDB, with a short description, inputs, outputs, and examples.


1. Core Objects

RelPy(encryption_key=None)

Creates an in-memory relational database object.

Inputs

Parameter Type Default Description
encryption_key bytes \| str \| None None Optional encryption key used for encrypted columns.

Output

Type Description
RelPy A new empty RelPyDB database object.

Example

from relpy import RelPy

db = RelPy()

With encryption:

key = RelPy.generate_encryption_key()
db = RelPy(encryption_key=key)

AutoNumber

Special logical column type for auto-incrementing integer primary keys.

Inputs

None.

Output

Used as a column type, not as a normal runtime value.

Example

db.add_column("users", "id", AutoNumber, is_primary_key=True)

col(column_name)

Creates a column reference used in query conditions.

Inputs

Parameter Type Description
column_name str Name of the column to reference.

Output

Type Description
ColumnRef A column reference object used to build conditions.

Example

db.query("users").where(col("age") >= 18)

2. Schema Functions

create_table(table_name)

Creates a new empty table.

Inputs

Parameter Type Description
table_name str Name of the table to create.

Output

Type Description
RelPy The same database object, allowing chaining.

Example

db.create_table("users")

add_column(table_name, column_name, data_type, ...)

Adds a column to an existing table.

Inputs

Parameter Type Default Description
table_name str required Target table.
column_name str required New column name.
data_type type required Python type or AutoNumber.
is_primary_key bool False Whether the column is a primary key.
is_pii bool False Marks the column as personally identifiable information.
is_encrypted bool False Stores the column encrypted.
references str \| None None Foreign key target in "table.column" format.
on_delete str \| None None FK delete behavior: RESTRICT, CASCADE, or SET NULL.
nullable bool \| None None Whether the column can contain None.
default Any not set Optional default value.

Output

Type Description
RelPy The same database object.

Example

db.add_column("users", "id", AutoNumber, is_primary_key=True)
db.add_column("users", "name", str, nullable=False)
db.add_column("users", "email", str, is_encrypted=True)

Foreign key:

db.add_column(
    "orders",
    "user_id",
    int,
    nullable=False,
    references="users.id",
    on_delete="CASCADE",
)

set_primary_key(table_name, columns, replace=False)

Sets a primary key using one or more existing columns.

Inputs

Parameter Type Default Description
table_name str required Target table.
columns list[str] required Column names that form the primary key.
replace bool False Whether to replace an existing primary key.

Output

Type Description
RelPy The same database object.

Example

db.set_primary_key("order_items", ["order_id", "product_id"])

describe_table(table_name)

Returns metadata about one table.

Inputs

Parameter Type Description
table_name str Name of the table.

Output

Type Description
dict[str, Any] Table schema metadata.

Example

info = db.describe_table("users")

describe_schema()

Returns metadata about the entire schema.

Inputs

None.

Output

Type Description
dict[str, Any] Schema metadata for all tables.

Example

schema = db.describe_schema()

3. Data Operation Functions

insert(table_name, values)

Inserts one row into a table.

Inputs

Parameter Type Description
table_name str Target table.
values dict[str, Any] Row values to insert.

Output

Type Description
dict[str, Any] The inserted public row. Internal metadata is hidden.

Example

user = db.insert("users", {"name": "Alice"})

insert_many(table_name, rows)

Inserts many rows into a table efficiently.

Inputs

Parameter Type Description
table_name str Target table.
rows list[dict[str, Any]] Rows to insert.

Output

Type Description
list[dict[str, Any]] Inserted public rows.

Example

db.insert_many("users", [
    {"name": "Alice"},
    {"name": "Bob"},
])

update(table_name, values, where=None, allow_all=False)

Updates rows in a table.

Inputs

Parameter Type Default Description
table_name str required Target table.
values dict[str, Any] required Values to update.
where Callable[[dict], bool] \| None None Predicate selecting rows to update.
allow_all bool False Required to update all rows intentionally.

Output

Type Description
int Number of updated rows.

Example

count = db.update(
    "users",
    {"status": "active"},
    where=lambda row: row["age"] >= 18,
)

Update all rows intentionally:

db.update("users", {"status": "active"}, allow_all=True)

delete(table_name, where=None, allow_all=False)

Deletes rows from a table.

Inputs

Parameter Type Default Description
table_name str required Target table.
where Callable[[dict], bool] \| None None Predicate selecting rows to delete.
allow_all bool False Required to delete all rows intentionally.

Output

Type Description
int Number of deleted rows, including cascaded rows.

Example

deleted = db.delete(
    "users",
    where=lambda row: row["id"] == 1,
)

Delete all rows intentionally:

db.delete("logs", allow_all=True)

4. Query Builder Functions

query(table_name)

Starts a query on a table.

Inputs

Parameter Type Description
table_name str Table to query.

Output

Type Description
Query A query builder object.

Example

q = db.query("users")

where(condition_or_callable)

Filters query rows.

Inputs

Parameter Type Description
condition_or_callable Condition \| Callable[[dict], bool] Filtering condition.

Output

Type Description
Query A new filtered query.

Example

db.query("users").where(col("status") == "active")

select(*columns)

Projects selected columns.

Inputs

Parameter Type Description
columns str... or list[str] Columns to keep.

Output

Type Description
Query A new projected query.

Example

db.query("users").select("id", "name")

order_by(*columns, descending=False)

Sorts query results.

Inputs

Parameter Type Default Description
columns str \| tuple[str, str] required Columns or (column, direction) pairs.
descending bool False Default direction for string columns.

Output

Type Description
Query A sorted query.

Example

db.query("users").order_by("name")
db.query("users").order_by("age", descending=True)
db.query("users").order_by(("status", "asc"), ("age", "desc"))

orderby(...)

Alias for order_by(...).

Inputs

Same as order_by.

Output

Same as order_by.

Example

db.query("users").orderby("name")

limit(count)

Limits the number of returned rows.

Inputs

Parameter Type Description
count int Maximum number of rows.

Output

Type Description
Query A limited query.

Example

db.query("users").limit(10)

offset(count)

Skips rows before returning results.

Inputs

Parameter Type Description
count int Number of rows to skip.

Output

Type Description
Query An offset query.

Example

db.query("users").order_by("id").offset(20).limit(10)

distinct(enabled=True)

Removes duplicate result rows.

Inputs

Parameter Type Default Description
enabled bool True Whether distinct mode is enabled.

Output

Type Description
Query A distinct query.

Example

db.query("users").select("status").distinct()

5. Condition Functions

Column comparisons

col("column") supports:

Expression Description
col("x") == value Equality condition.
col("x") != value Not-equal condition.
col("x") > value Greater-than condition.
col("x") >= value Greater-than-or-equal condition.
col("x") < value Less-than condition.
col("x") <= value Less-than-or-equal condition.

Output

Type Description
Condition A condition object.

like(pattern, case_sensitive=True)

SQL-like pattern matching.

Inputs

Parameter Type Default Description
pattern str required LIKE pattern. % means any sequence, _ means one character.
case_sensitive bool True Whether matching is case-sensitive.

Output

Type Description
Condition LIKE condition.

Example

col("email").like("%@gmail.com")

in_(values)

Checks whether the value is included in a collection.

Inputs

Parameter Type Description
values list \| tuple \| set Allowed values.

Output

Type Description
Condition IN condition.

Example

col("status").in_(["paid", "pending"])

between(low, high, inclusive=True)

Checks whether a value is between two bounds.

Inputs

Parameter Type Default Description
low Any required Lower bound.
high Any required Upper bound.
inclusive bool True Whether bounds are inclusive.

Output

Type Description
Condition BETWEEN condition.

Example

col("amount").between(100, 500)

is_null() and is_not_null()

Checks whether a column value is or is not None.

Inputs

None.

Output

Type Description
Condition NULL-check condition.

Example

col("deleted_at").is_null()
col("email").is_not_null()

AND(*conditions)

Combines conditions with logical AND.

Inputs

Parameter Type Description
conditions Condition... Conditions to combine.

Output

Type Description
Condition Combined AND condition.

Example

AND(col("age") >= 18, col("status") == "active")

OR(*conditions)

Combines conditions with logical OR.

Output

Type Description
Condition Combined OR condition.

Example

OR(col("tier") == "gold", col("tier") == "platinum")

NOT(condition)

Negates a condition.

Output

Type Description
Condition Negated condition.

Example

NOT(col("status") == "inactive")

6. Join Functions

join(other, ...)

Joins the current query with another table, view, or query.

Inputs

Parameter Type Default Description
other str \| Query required Table, view, or query to join.
on str \| tuple \| list[tuple] \| None None Join column definition.
left_on str \| list[str] \| None None Left-side join columns.
right_on str \| list[str] \| None None Right-side join columns.
method str "inner" Join type.
left_prefix str \| None None Prefix for left columns.
right_prefix str \| None None Prefix for right columns.
prefix_columns bool True Whether to prefix output columns.
preserve_prefixed_columns bool True Whether to preserve already-prefixed names.
suffixes tuple[str, str] ("_left", "_right") Suffixes for name collisions.
match_nulls bool False Whether None values match.

Output

Type Description
Query Joined query.

Example

db.query("orders").join("users")
db.query("orders").join("users", on=("user_id", "id"))
db.query("orders").join("users", method="left")

Join shortcuts

Shortcut functions call join(..., method=...).

Function Join method
inner_join(other, **kwargs) inner
left_join(other, **kwargs) left
right_join(other, **kwargs) right
full_join(other, **kwargs) full
cross_join(other, **kwargs) cross
natural_join(other, **kwargs) natural

Example

db.query("orders").left_join("users")

7. Grouping Functions

group_by(*columns)

Starts a grouped query.

Inputs

Parameter Type Description
columns str... or list[str] Columns to group by.

Output

Type Description
GroupedQuery A grouped query object.

Example

db.query("orders").group_by("status")

aggregate(**aggregations)

Adds aggregate columns to a grouped query.

Inputs

Parameter Type Description
**aggregations AggregationSpec Named aggregation aliases.

Output

Type Description
GroupedQuery Grouped query with aggregations.

Example

(
    db.query("orders")
      .group_by("status")
      .aggregate(
          order_count=count(),
          total_amount=sum_("amount"),
      )
)

having(condition)

Filters grouped results after aggregation.

Inputs

Parameter Type Description
condition Condition Condition over grouped result columns.

Output

Type Description
GroupedQuery Filtered grouped query.

Example

.having(col("total_amount") > 1000)

Aggregation specification functions

Function Input Output Description
count(column_name=None) str \| None AggregationSpec Counts rows or non-null values.
sum_(column_name) str AggregationSpec Sums a numeric column.
avg(column_name) str AggregationSpec Computes average.
min_(column_name) str AggregationSpec Computes minimum.
max_(column_name) str AggregationSpec Computes maximum.

8. Query Terminal Methods

Query.to_list(decrypt=False)

Executes a query and returns rows as a list of dictionaries.

Output

Type Description
list[dict[str, Any]] Query rows.

Query.to_json(decrypt=False, ...)

Executes a query and returns JSON text.

Output

Type Description
str JSON string.

Query.to_pandas(decrypt=False)

Executes a query and returns a pandas DataFrame.

Output

Type Description
pandas.DataFrame Query rows as a DataFrame.

Query.to_numpy(decrypt=False)

Executes a query and returns a NumPy array.

Output

Type Description
numpy.ndarray Query rows as an array.

first()

Returns the first row or None.

Output

Type Description
dict[str, Any] \| None First row or None.

one()

Returns exactly one row.

Output

Type Description
dict[str, Any] The single matching row.

Raises

  • NoRowsFoundError if there are zero rows.
  • MultipleRowsFoundError if there is more than one row.

exists()

Checks whether the query returns any rows.

Output

Type Description
bool True if at least one row exists.

pluck(column_name)

Returns one column as a list.

Inputs

Parameter Type Description
column_name str Column to extract.

Output

Type Description
list[Any] Column values.

Query aggregate terminal methods

Function Input Output Description
count(column_name=None) str \| None int Counts rows or non-null values.
sum(column_name) str int \| float \| None Sums a numeric column.
avg(column_name) str float \| None Computes average.
average(column_name) str float \| None Alias for avg.
min(column_name) str Any \| None Minimum value.
max(column_name) str Any \| None Maximum value.

9. View Functions

create_view(view_name, query_builder, description=None)

Creates a named logical view.

Inputs

Parameter Type Default Description
view_name str required Name of the view.
query_builder Callable[[RelPy], Query] required Function that builds the view query.
description str \| None None Optional description.

Output

Type Description
RelPy The same database object.

Example

db.create_view(
    "active_users",
    lambda db: db.query("users").where(col("status") == "active"),
)

view(view_name)

Evaluates and returns a view query.

Inputs

Parameter Type Description
view_name str View name.

Output

Type Description
Query Query returned by the view builder.

drop_view(view_name)

Drops a view.

Output

Type Description
RelPy The same database object.

list_views()

Lists view names.

Output

Type Description
list[str] View names.

describe_view(view_name)

Describes one view.

Output

Type Description
dict[str, Any] View metadata.

describe_views()

Describes all views.

Output

Type Description
dict[str, dict[str, Any]] Metadata for all views.

10. Index Functions

create_index(table_name, columns, name=None, unique=False, nulls_distinct=True)

Creates an index.

Inputs

Parameter Type Default Description
table_name str required Target table.
columns str \| list[str] \| tuple[str, ...] required Indexed column or columns.
name str \| None None Optional index name.
unique bool False Whether values must be unique.
nulls_distinct bool True Whether nulls are distinct in unique indexes.

Output

Type Description
RelPy The same database object.

Example

db.create_index("users", "email")
db.create_index("orders", ["customer_id", "status"])

drop_index(index_name)

Drops an index.

Inputs

Parameter Type Description
index_name str Index name.

Output

Type Description
RelPy The same database object.

list_indexes(table_name=None)

Lists indexes.

Inputs

Parameter Type Default Description
table_name str \| None None Optional table filter.

Output

Type Description
list[str] Index names.

describe_index(index_name)

Describes one index.

Output

Type Description
dict[str, Any] Index metadata.

describe_indexes(table_name=None)

Describes all indexes, optionally filtered by table.

Output

Type Description
dict[str, dict[str, Any]] Index metadata.

11. Table Export Functions

These functions are methods on the RelPy object.

They usually support: - whole table export - single column export - single row export through where_key - encrypted export through decrypt=True

to_list(table_name, column_name=None, where_key=None, decrypt=False)

Exports table data as Python lists.

Inputs

Parameter Type Default Description
table_name str required Table to export.
column_name str \| None None Optional column to export.
where_key dict[str, Any] \| None None Optional primary-key lookup.
decrypt bool False Whether to decrypt encrypted values.

Output

Type Description
list[dict[str, Any]] \| list[Any] Exported rows or column values.

to_json(table_name, column_name=None, where_key=None, decrypt=False, ...)

Exports table data as JSON text.

Output

Type Description
str JSON text.

to_pandas(table_name, column_name=None, where_key=None, decrypt=False)

Exports table data to pandas.

Output

Type Description
pandas.DataFrame DataFrame containing exported data.

to_numpy(table_name, column_name=None, where_key=None, decrypt=False, dtype=None)

Exports table data to NumPy.

Output

Type Description
numpy.ndarray NumPy array.

to_sql(table_name, row=None, where_key=None, decrypt=False)

Exports table rows as SQL INSERT statements.

Inputs

Parameter Type Default Description
table_name str required Source table.
row dict[str, Any] \| None None Optional explicit row.
where_key dict[str, Any] \| None None Optional primary-key lookup.
decrypt bool False Required for encrypted plaintext export.

Output

Type Description
str SQL INSERT statements.

to_ddl()

Exports the schema as SQL DDL.

Inputs

None.

Output

Type Description
str SQL CREATE TABLE statements.

Prints a table preview.

Inputs

Parameter Type Default Description
table_name str required Table to preview.
limit int 3 Number of rows to print.
max_width int 24 Maximum cell width.
decrypt bool False Whether to decrypt encrypted values.

Output

Type Description
None Prints output to stdout.

12. Persistence Functions

save(file_path, indent=2)

Saves the database to a .relpy.json file.

Inputs

Parameter Type Default Description
file_path str \| Path required Target file path.
indent int \| None 2 JSON indentation.

Output

Type Description
None Writes a file.

load(file_path, encryption_key=None)

Loads a database from a .relpy.json file.

Inputs

Parameter Type Default Description
file_path str \| Path required Source file path.
encryption_key bytes \| str \| None None Optional key for encrypted data.

Output

Type Description
RelPy Loaded database object.

Example

db = RelPy.load("database.relpy.json")
db = RelPy.load("database.relpy.json", encryption_key=key)

13. Encryption Functions

generate_encryption_key()

Generates a key for encrypted columns.

Inputs

None.

Output

Type Description
bytes Encryption key.

Example

key = RelPy.generate_encryption_key()

set_encryption_key(encryption_key)

Sets the encryption key on an existing database object.

Inputs

Parameter Type Description
encryption_key bytes \| str Key generated by generate_encryption_key().

Output

Type Description
None Updates the object state.

Example

db.set_encryption_key(key)

14. Exceptions

RelPyDB defines a custom exception hierarchy.

Base exceptions

Exception Description
RelPyError Base exception for all RelPyDB errors.
RelPyValueError Base for RelPyDB value errors.
RelPyTypeError Base for RelPyDB type errors.
RelPyLookupError Base for lookup errors.
RelPyKeyError Base for key errors.

Specific exceptions

Exception Description
SchemaError Invalid schema operation.
TableNotFoundError Table does not exist.
ColumnNotFoundError Column does not exist.
ConstraintError Relational constraint violation.
QueryError Invalid query operation.
QueryTypeError Invalid query argument type.
ViewError Invalid view operation.
RowNotFoundError Requested row does not exist.
NoRowsFoundError one() expected one row but found none.
MultipleRowsFoundError one() expected one row but found multiple rows.
EncryptionError Encryption/decryption error.

15. Minimal End-to-End Example

from relpy import RelPy, AutoNumber, col, count

db = RelPy()

db.create_table("users")
db.add_column("users", "id", AutoNumber, is_primary_key=True)
db.add_column("users", "name", str, nullable=False)

db.create_table("orders")
db.add_column("orders", "id", AutoNumber, is_primary_key=True)
db.add_column("orders", "user_id", int, nullable=False, references="users.id")
db.add_column("orders", "status", str, nullable=False)

alice = db.insert("users", {"name": "Alice"})

db.insert_many("orders", [
    {"user_id": alice["id"], "status": "paid"},
    {"user_id": alice["id"], "status": "paid"},
])

result = (
    db.query("orders")
      .join("users")
      .where(col("orders.status") == "paid")
      .group_by("users.name")
      .aggregate(order_count=count())
      .to_list()
)

print(result)

Expected output:

[
    {
        "users.name": "Alice",
        "order_count": 2,
    }
]

Recommended explicit join syntax

For a single-column explicit join, prefer a tuple for on:

db.query("orders").inner_join(
    "support_tickets",
    on=("customer_id", "customer_id"),
)

This means:

orders.customer_id = support_tickets.customer_id

Avoid documenting on=["customer_id", "customer_id"] as the main style. A list looks like a list of columns and becomes confusing when composite joins are introduced.

For maximum clarity, use left_on and right_on:

db.query("orders").inner_join(
    "support_tickets",
    left_on="customer_id",
    right_on="customer_id",
)

For a composite join, use a list of pairs:

db.query("orders").inner_join(
    "support_tickets",
    on=[
        ("customer_id", "customer_id"),
        ("region_id", "region_id"),
    ],
)

Full join shortcuts example

The example below shows the shortcut methods that map directly to join methods.

from relpy import RelPy, AutoNumber

db = RelPy()

db.create_table("users")
db.add_column("users", "id", AutoNumber, is_primary_key=True)
db.add_column("users", "name", str, nullable=False)

db.create_table("orders")
db.add_column("orders", "id", AutoNumber, is_primary_key=True)
db.add_column("orders", "user_id", int, nullable=True, references="users.id")
db.add_column("orders", "amount", float, nullable=False)

alice = db.insert("users", {"name": "Alice"})
bob = db.insert("users", {"name": "Bob"})

db.insert_many("orders", [
    {"user_id": alice["id"], "amount": 120.0},
    {"user_id": alice["id"], "amount": 80.0},
])

inner_rows = db.query("orders").inner_join("users").to_list()
left_rows = db.query("orders").left_join("users").to_list()
right_rows = db.query("orders").right_join("users").to_list()
full_rows = db.query("orders").full_join("users").to_list()
cross_rows = db.query("orders").cross_join("users").to_list()

print(inner_rows)
print(left_rows)
print(right_rows)
print(full_rows)
print(cross_rows)

Use inner_join when you only want matching rows. Use left_join when every left-side row should appear. Use right_join when every right-side row should appear. Use full_join when unmatched rows from both sides should appear. Use cross_join when you want every combination of rows.