The TableModel class represents a database table in the oRm framework. It manages table structure, fields, relationships, and provides methods for interacting with the database table.
Details
TableModel is a core component of the oRm framework, responsible for:
Defining table structure with columns and relationships
Creating and managing database tables
Providing an interface for CRUD operations on table records
Managing relationships between different tables
Key features:
Dynamic table creation and management
Support for various column types and constraints
Relationship definitions and querying
Record creation and retrieval
Note
Errors if the table's schema does not exist.
Throws an error if zero or multiple records are found.
Throws an error if multiple records are found.
Methods
initialize(tablename, engine, ..., .data = list(), .schema = NULL, .default_mode = "all")Constructor for creating a new TableModel instance.
get_connection()Retrieve the active database connection from the engine.
generate_sql_fields()Generate SQL field definitions for table creation.
create_table(if_not_exists = TRUE, overwrite = FALSE, verbose = FALSE)Create the associated table in the database.
record(..., .data = list())Create a new Record object associated with this model.
create(..., .data = list())Insert a new row (set-level counterpart to
Record$create()).read(..., .mode = NULL, .limit = NULL)Read records from the table using dynamic filters. If `.mode` is NULL, uses `default_mode`.
update(..., .all = FALSE, .data = list())Update matching rows; bare exprs are the WHERE filter, named args are the SET values.
delete(..., .all = FALSE)Delete matching rows; bare exprs are the WHERE filter.
define_relationship(local_key, type, related_model, related_key, ref = NULL, backref = NULL)Define a relationship from this model to a related model (method form of
define_relationship()).relationship(rel_name, ...)Query related records based on defined relationships.
print()Print a concise summary of the model, including its fields.
See also
Engine, Record, Column, ForeignKey
Engine::get_connection
[Record$relationship()]
[define_relationship()], [TableModel$relationship()]
[Engine$print()], [Record$print()].
Public fields
tablenameFully qualified name of the table in the database.
schemaSchema that namespaces the table; defaults to the engine's schema.
engineEngine instance providing connections and SQL dialect.
fieldsNamed list of Column objects defining the table structure.
relationshipsNamed list of Relationship objects linking to other models.
default_modeDefault mode for reading records when `.mode` is NULL.
Methods
Method new()
Constructor for a new TableModel.
Usage
TableModel$new(
tablename,
engine,
...,
.data = list(),
.schema = NULL,
.default_mode = c("all", "one_or_none", "get", "data.frame", "tbl")
)Arguments
tablenameThe name of the database table.
engineThe Engine object for database connection.
...Column definitions.
.dataa list of Column defintions
.schemaCharacter. Schema to apply to the table name. Defaults to the engine's schema.
.default_modeCharacter. Default mode used when `read()` is called with `.mode` = NULL. Must be one of "all", "one_or_none", "get", "data.frame", or "tbl".
Method get_connection()
Retrieve the active database connection from the engine. Delegates to the associated engine and respects schema and pooling settings.
Method set_schema()
Update the schema for this model and re-qualify the table name.
Method create_table()
Create the associated table in the database.
Usage
TableModel$create_table(
if_not_exists = TRUE,
overwrite = FALSE,
ask = TRUE,
verbose = FALSE
)Arguments
if_not_existsLogical. If TRUE, only create the table if it doesn't exist. Default is TRUE.
overwriteLogical. If TRUE, drop the table if it exists and recreate it. Default is FALSE.
askLogical. If TRUE (default) and `overwrite` is TRUE, prompt for confirmation in interactive sessions before dropping the table. Pass `ask = FALSE` to bypass the prompt (e.g. in scripts).
verboseLogical. If TRUE, return the SQL statement instead of executing it. Default is FALSE.
Method drop_table()
Drop the associated table from the database. Prompts for confirmation by default if running interactively.
Usage
TableModel$drop_table(ask = interactive())Arguments
askLogical. If TRUE (default in interactive sessions), prompts the user for confirmation before dropping the table.
Method record()
Create a new Record object with this model.
Usage
TableModel$record(..., .data = list())Method create()
Insert a new row into the table.
Convenience wrapper over `model$record(...)$create()`: builds a Record from the supplied values and immediately persists it. This is the set-level counterpart to `Record$create()`.
Usage
TableModel$create(..., .data = list())Method update()
Update matching rows in the table (set-level `UPDATE ... WHERE`).
Bare expressions are treated as the WHERE filter (exactly like `read()`), while named arguments are treated as the SET assignments (like `create()`/`record()`). For example, `User$update(id == 1, name = "Kent")` sets `name` on the row(s) where `id == 1`.
Usage
TableModel$update(..., .all = FALSE, .data = list())Method delete()
Delete matching rows from the table (set-level `DELETE ... WHERE`).
Bare expressions are treated as the WHERE filter, exactly like `read()`. This is the set-level counterpart to `Record$delete()`.
Method read()
Read records using dynamic filters and return in the specified mode.
Usage
TableModel$read(
...,
.mode = NULL,
.limit = 100,
.offset = 0,
.order_by = list()
)Arguments
...Unquoted expressions for filtering.
.modeMode for reading records. One of "all", "one_or_none", "get", "data.frame", or "tbl". If NULL, uses `default_mode`. "data.frame" returns the raw result of `dplyr::collect()` rather than Record objects. "tbl" returns the uncollected dbplyr table.
.limitInteger. Maximum number of records to return. Defaults to 100. NULL means no limit. Positive values return the first N records, negative values return the last N records.
.offsetInteger. Offset for pagination. Default is 0.
.order_byUnquoted expressions for ordering. Defaults to NULL (no order). Calls dplyr::arrange() so can take multiple args / desc()
Method get()
Shortcut for retrieving a single record. Expects exactly one matching record.
Method all()
Retrieve all records matching the given filters.
Method one_or_none()
Retrieve zero or one record matching the given filters.
Examples
\donttest{
# Get user by email (expects 0 or 1 result)
user <- User$one_or_none(email == "user@example.com")
# Returns NULL if no match
user <- User$one_or_none(id == 999)
# Errors if multiple matches
user <- User$one_or_none(status == "active") # Error if multiple active users
}
Retrieve related records based on a defined relationship.
Method relationship()
Arguments
rel_nameThe name of the relationship to query.
...Additional arguments passed to the related model's read method.
Details
This method returns related records based on the relationship type: - For 'belongs_to', 'owns', 'one_to_one', and 'many_to_one' relationships, it returns a single Record object or NULL. - For 'one_to_many' and 'many_to_many' relationships, it returns a list of Record objects.
For per-record filtering based on existing data, use [Record$relationship()], which applies additional constraints.
Method define_relationship()
Define a relationship from this model to a related model.
Method form of [define_relationship()] with this model supplied as the `local_model`. Modifies both models in place (R6 semantics); the related model gains the reverse relationship unless `backref = FALSE`.
Usage
TableModel$define_relationship(
local_key,
type,
related_model,
related_key,
ref = NULL,
backref = NULL
)Arguments
local_keyThe key in this model that relates to `related_key`.
typeThe relationship type. One of 'one_to_one', 'one_to_many', 'many_to_one', or 'many_to_many'.
related_modelThe model being related to.
related_keyThe key in the related model that `local_key` relates to.
refName for this relationship on this model. Defaults to the lowercase related table name.
backrefName for the reverse relationship on the related model. Defaults to the lowercase local table name; `FALSE` skips it.
Method print()
Print a concise summary of the model, including the table name and column names.