orm API reference
A minimal relational mapper over the sql library. It is Data Mapper, not Active Record - Jennifer structs are value-semantic and carry no methods, and a module holds no state, so a row cannot save() itself. Instead you pass a record and a Schema to repository functions: orm.insert / find / update / delete, and orm.all over a query.
There is no reflection, so you declare the table mapping once as an orm.Schema (built with orm.schema + orm.column), which also carries the SQL dialect (orm.Dialect.Mysql or orm.Dialect.Postgres) - a backend selector on one module, not parallel modules. The query builder is functional (like the json write surface): each step returns a fresh orm.Query, rendered to parameterized SQL by orm.toSql. The surface covers ordinary queries: column projection (select) and aggregates (count / aggregate), where / orWhere / whereIn (AND / OR / IN conditions), join / leftJoin / rightJoin, groupBy + having, orderBy / limit / offset.
Values bind only through placeholders (injection safety inherited from sql); the tokens that cannot be parameterized - table / column identifiers, comparison operators, aggregate functions, join kinds, sort directions - are validated against fixed allowlists (identifiers must be bare SQL names). They are checked both at build time (for an early, friendly error) and again at render time inside toSql / createTable / the CRUD builders, so even a hand-built orm.Query / orm.Schema struct literal that skipped the builder cannot inject SQL.
A record - both the input to insert / update and the result of find / all - is a map of string to string keyed by column name (the row form that needs no map-to-struct conversion; a typed-struct form waits on that language feature). The database coerces the string values to the column types.
Needs sql, so the default jennifer binary.
Import with import "orm.j" as orm;. See the orm guide for prose and examples.
Contents
| Name | What it is |
|---|---|
addColumn | The `ALTER TABLE ... |
addForeignKey | The `ALTER TABLE ... |
aggregate | A copy of q adding func(col) AS alias to the projection. |
all | Run a query and return every matching row. |
autoIncrement | A copy of s marking its most-recently-added column auto-incrementing (SERIAL on Postgres,... |
belongsTo | Declare a belongs-to relation: this table holds foreignKey, which references the target's primary... |
column | A copy of s with a column appended. |
count | A copy of q adding COUNT(*) AS alias to the projection. |
createIndex | The CREATE [UNIQUE] INDEX DDL over one or more columns. |
createTable | The CREATE TABLE DDL for a schema, in its dialect - including each column's NOT NULL / DEFAULT /... |
delete | Delete a row by primary-key value. |
deleteWhere | Bulk-delete every row matching a query's WHERE. |
distinct | A copy of q rendered as SELECT DISTINCT .... |
dropColumn | The `ALTER TABLE ... |
dropForeignKey | The `ALTER TABLE ... |
dropIndex | The DROP INDEX DDL (Postgres drops by index name; MySQL needs the table). |
dropTable | The DROP TABLE DDL for a table. |
exists | Whether a query matches any row (adds LIMIT 1). |
find | Find a single row by primary-key value. |
findBy | The first row of the schema's table where col = value, or {} if none. |
first | The first row a query matches (adds LIMIT 1), or an empty map when there is none. |
from | A base query selecting all rows of the schema's table. |
groupBy | A copy of q grouping by the named columns. |
having | A copy of q with a HAVING condition over an aggregate (func(col) op value), AND-joined. |
insert | Insert a record. |
insertMany | Insert many records in one multi-row INSERT. |
insertReturning | Insert record and return the generated primary-key value (Postgres RETURNING pk; MySQL LAST_INSERT_ID... |
join | A copy of q with an INNER JOIN. |
joinRelation | A copy of q with the JOIN(s) that a declared relation implies - an INNER JOIN on the correct key colu... |
leftJoin | A copy of q with a LEFT JOIN. |
limit | A copy of q with a LIMIT. |
load | Run a query and eager-load its orm.with-marked relations in a fixed 1 + R queries (R = relations requ... |
manyToMany | Declare a many-to-many relation through a join table. |
notNull | A copy of s marking its most-recently-added column NOT NULL. |
offset | A copy of q with an OFFSET. |
oneToMany | Declare a one-to-many (has-many) relation: the target table holds foreignKey, which references th... |
oneToOne | Declare a one-to-one (has-one) relation: the target table holds foreignKey, which references this... |
orHaving | Like having, but OR-joined to the previous HAVING condition. |
orWhere | Like where, but OR-joined to the previous condition. |
orWhereIn | Like whereIn, but OR-joined to the previous condition. |
orderBy | A copy of q with an ORDER BY term added. |
page | A copy of q with LIMIT / OFFSET set for a 1-based page: page pageNum of pageSize rows (page 1 sta... |
pluck | The values of one column across every row a query matches (the column must be in the projection; the defaul... |
related | The eager-loaded child rows of row for a has-many / many-to-many relation (an empty list if the row has n... |
relatedOne | The single eager-loaded row of row for a belongs-to / has-one relation, or an empty map when there is... |
renameColumn | The `ALTER TABLE ... |
rightJoin | A copy of q with a RIGHT JOIN. |
rows | The base rows of a Result (the same rows orm.all would return). |
save | Insert record when it carries no primary key, else update it (matched by the primary key). |
schema | Start a schema for a table with its primary-key column and dialect. |
select | A copy of q projecting only the named columns (instead of SELECT *). |
session | A session that runs each statement directly on a connection (auto-commit). |
toSql | Render a query to parameterized SQL for its dialect. |
transaction | A session that runs its statements inside a caller-managed transaction. |
unique | A copy of s adding a UNIQUE constraint to its most-recently-added column. |
update | Update a record, matched by its primary-key value (which the record must carry). |
updateWhere | Bulk-update every row matching a query's WHERE, setting assignments (column -> value, bound as paramete... |
upsert | Insert record, or update the conflicting row if a unique / primary-key conflict on conflictCols occurs ... |
where | A copy of q with a column op value condition AND-joined to the rest. |
whereBetween | A copy of q with a column BETWEEN lo AND hi condition, AND-joined. |
whereIn | A copy of q with a column IN (...) condition AND-joined, one placeholder bound per value. |
whereNotIn | A copy of q with a column NOT IN (...) condition AND-joined. |
whereNotNull | A copy of q with a column IS NOT NULL condition, AND-joined. |
whereNull | A copy of q with a column IS NULL condition, AND-joined. |
with | A copy of q marking a declared relation to eager-load with orm.load. |
withDefault | A copy of s giving its most-recently-added column a DEFAULT. |
Column | struct: One column in a schema: its name, value kind, and DDL attributes. |
Condition | struct: A single WHERE condition within a Query; its bound value(s) live in the query's params list (positional... |
Having | struct: A single HAVING condition over an aggregate, its value in havingParams. |
Join | struct: One JOIN clause: its kind and the left = right equality. |
Order | struct: One ORDER BY term. |
Query | struct: A composable, non-mutating SELECT query. |
Relation | struct: A declared association from a schema to another table. |
RelationData | struct: The loaded child rows for one eager-loaded relation: a parent-key -> child-rows lookup, built once from a s... |
Rendered | struct: A rendered, parameterized statement: the SQL text and the ordered bind values. |
Result | struct: The result of orm.load: the base query's rows plus the eager-loaded relations. |
Schema | struct: A table mapping: the table name, its columns, the primary-key column, the SQL dialect, and any declared rel... |
SelectItem | struct: One item in a SELECT projection: a plain column (func "") or an aggregate (func one of COUNT / SUM / AV... |
Session | struct: A unit of work wrapping either a sql.Connection (auto-committing) or a sql.Tx (inside a caller's transa... |
ColumnKind | enum: A column's value kind: the SQL type family createTable renders. |
Dialect | enum: The SQL dialect: the backend selector that governs placeholder syntax and DDL spelling. |
RelationKind | enum: The kind of an association between two tables: orm.RelationKind.BelongsTo (this table holds the foreign k... |
Functions
addColumn
orm.addColumn(
table as string,
name as string,
kind as ColumnKind,
dialect as Dialect)The ALTER TABLE ... ADD COLUMN DDL for a new column (name + type, no attributes; express attribute-rich columns in a createTable schema).
table- the table name
name- the new column name
kind- the column value kind
dialect- the SQL dialect (for the type spelling)
- Returns
string - the ALTER TABLE ADD COLUMN statement
addForeignKey
orm.addForeignKey(
table as string,
name as string,
column as string,
refTable as string,
refColumn as string)The ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY DDL.
table- the table carrying the foreign key
name- the constraint name
column- the local foreign-key column
refTable- the referenced table
refColumn- the referenced column
- Returns
string - the ALTER TABLE ADD CONSTRAINT statement
aggregate
orm.aggregate(q as Query, fn as string, col as string, alias as string)A copy of q adding func(col) AS alias to the projection. func is one of COUNT / SUM / AVG / MIN / MAX; col may be "*" (for COUNT).
q- the source query
fn- the aggregate function
col- the column (or
"*") alias- the result-column alias
- Returns
Query - the extended query
all
orm.all(session as Session, q as Query)Run a query and return every matching row.
session- the session (
orm.sessionororm.transaction) q- the query (from the builder)
- Returns
list of map of string to string - the rows
autoIncrement
orm.autoIncrement(s as Schema)A copy of s marking its most-recently-added column auto-incrementing (SERIAL on Postgres, AUTO_INCREMENT on MySQL).
s- the source schema
- Returns
Schema - the schema with the last column auto-incrementing
belongsTo
orm.belongsTo(
s as Schema,
name as string,
target as string,
foreignKey as string)Declare a belongs-to relation: this table holds foreignKey, which references the target's primary key (id by convention). E.g. a post belongs to an author via posts.authorId -> authors.id.
s- the source schema
name- the relation name
target- the target table
foreignKey- the foreign-key column on this table
- Returns
Schema - the schema with the relation added
column
orm.column(s as Schema, name as string, kind as ColumnKind)A copy of s with a column appended.
s- the source schema
name- the column name
kind- the value kind (
orm.ColumnKind.Int/String/Float/Bool/Bytes) - Returns
Schema - the extended schema
count
orm.count(q as Query, alias as string)A copy of q adding COUNT(*) AS alias to the projection.
q- the source query
alias- the result-column alias
- Returns
Query - the extended query
createIndex
orm.createIndex(
name as string,
table as string,
columns as list of string,
isUnique as bool)The CREATE [UNIQUE] INDEX DDL over one or more columns.
name- the index name
table- the table name
columns- the indexed columns (non-empty)
isUnique- whether the index is UNIQUE
- Returns
string - the CREATE INDEX statement
createTable
orm.createTable(s as Schema)The CREATE TABLE DDL for a schema, in its dialect - including each column's NOT NULL / DEFAULT / UNIQUE / auto-increment attributes and the primary key. Pair it with the migration runner (orm.migrate) or run it directly.
s- the schema
- Returns
string - the CREATE TABLE statement
delete
orm.delete(session as Session, s as Schema, id as string)Delete a row by primary-key value.
session- the session (
orm.sessionororm.transaction) s- the schema
id- the primary-key value
- Returns
sql.Result - the affected-rows result
deleteWhere
orm.deleteWhere(session as Session, s as Schema, q as Query)Bulk-delete every row matching a query's WHERE. Refuses a query with no WHERE (use a raw sql.exec to truncate deliberately).
session- the session (
orm.sessionororm.transaction) s- the schema
q- the query whose
WHEREselects the rows - Returns
sql.Result - the affected-rows result
distinct
orm.distinct(q as Query)A copy of q rendered as SELECT DISTINCT ....
q- the source query
- Returns
Query - the query with DISTINCT set
dropColumn
orm.dropColumn(table as string, name as string)The ALTER TABLE ... DROP COLUMN DDL.
table- the table name
name- the column to drop
- Returns
string - the ALTER TABLE DROP COLUMN statement
dropForeignKey
orm.dropForeignKey(table as string, name as string, dialect as Dialect)The ALTER TABLE ... DROP foreign-key DDL (Postgres DROP CONSTRAINT; MySQL DROP FOREIGN KEY).
table- the table name
name- the constraint name
dialect- the SQL dialect
- Returns
string - the ALTER TABLE DROP statement
dropIndex
orm.dropIndex(name as string, table as string, dialect as Dialect)The DROP INDEX DDL (Postgres drops by index name; MySQL needs the table).
name- the index name
table- the table the index is on
dialect- the SQL dialect
- Returns
string - the DROP INDEX statement
dropTable
orm.dropTable(table as string)The DROP TABLE DDL for a table.
table- the table name
- Returns
string - the DROP TABLE statement
exists
orm.exists(session as Session, q as Query)Whether a query matches any row (adds LIMIT 1).
session- the session (
orm.sessionororm.transaction) q- the query
- Returns
bool - true if at least one row matches
find
orm.find(session as Session, s as Schema, id as string)Find a single row by primary-key value.
session- the session (
orm.sessionororm.transaction) s- the schema
id- the primary-key value
- Returns
map of string to string - the row (column name -> value)
- Throws
Error - when no row has that key
findBy
orm.findBy(session as Session, s as Schema, col as string, value as string)The first row of the schema's table where col = value, or {} if none.
session- the session (
orm.sessionororm.transaction) s- the schema
col- the column to match
value- the value to match
- Returns
map of string to string - the matching row, or
{}if none
first
orm.first(session as Session, q as Query)The first row a query matches (adds LIMIT 1), or an empty map when there is none.
session- the session (
orm.sessionororm.transaction) q- the query
- Returns
map of string to string - the first row, or
{}if none
from
orm.from(s as Schema)A base query selecting all rows of the schema's table.
s- the schema
- Returns
Query - the base query
groupBy
orm.groupBy(q as Query, cols as list of string)A copy of q grouping by the named columns.
q- the source query
cols- the GROUP BY columns
- Returns
Query - the extended query
having
orm.having(
q as Query,
fn as string,
col as string,
op as string,
value as string)A copy of q with a HAVING condition over an aggregate (func(col) op value), AND-joined. HAVING filters groups, so it is used with groupBy / aggregate.
q- the source query
fn- the aggregate function (COUNT / SUM / AVG / MIN / MAX)
col- the aggregated column (or
"*") op- the operator
value- the value to bind
- Returns
Query - the extended query
insert
orm.insert(
session as Session,
s as Schema,
record as map of string to string)Insert a record. Only the columns present in record are written (so an auto-generated primary key is simply omitted).
session- the session (
orm.sessionororm.transaction) s- the schema
record- column name -> value
- Returns
sql.Result - the affected-rows / last-insert-id result
insertMany
orm.insertMany(
session as Session,
s as Schema,
records as list of map of string to string)Insert many records in one multi-row INSERT. Every record must set the same columns (those present in the first). A batch whose placeholder count would exceed the per-statement limit is split across several INSERTs (never silently capped); wrap the call in orm.transaction for all-or-nothing.
session- the session (
orm.sessionororm.transaction) s- the schema
records- the rows to insert
- Returns
int - the number of records inserted
insertReturning
orm.insertReturning(
session as Session,
s as Schema,
record as map of string to string)Insert record and return the generated primary-key value (Postgres RETURNING pk; MySQL LAST_INSERT_ID via the result's lastId).
session- the session (
orm.sessionororm.transaction) s- the schema
record- the row to insert
- Returns
string - the generated primary-key value
join
orm.join(q as Query, table as string, leftCol as string, rightCol as string)A copy of q with an INNER JOIN.
q- the source query
table- the table to join
leftCol- the left join column (
table.col) rightCol- the right join column
- Returns
Query - the extended query
joinRelation
orm.joinRelation(q as Query, s as Schema, relationName as string)A copy of q with the JOIN(s) that a declared relation implies - an INNER JOIN on the correct key columns (two joins for a many-to-many, through its join table). Built over the join primitive.
q- the source query
s- the schema declaring the relation
relationName- the relation to join
- Returns
Query - the extended query
leftJoin
orm.leftJoin(
q as Query,
table as string,
leftCol as string,
rightCol as string)A copy of q with a LEFT JOIN.
q- the source query
table- the table to join
leftCol- the left join column (
table.col) rightCol- the right join column
- Returns
Query - the extended query
limit
orm.limit(q as Query, n as int)A copy of q with a LIMIT.
q- the source query
n- the row limit (>= 0; negative throws kind
orm) - Returns
Query - the extended query
load
orm.load(session as Session, schema as Schema, q as Query)Run a query and eager-load its orm.with-marked relations in a fixed 1 + R queries (R = relations requested): the base query once, then one batched WHERE fk IN (...) per relation - never one query per row. Returns a Result walked by orm.rows / related / relatedOne.
session- the session (
orm.sessionororm.transaction) schema- the base schema (declares the relations)
q- the query, with relations marked by
orm.with - Returns
Result - the base rows plus the eager-loaded relations
manyToMany
orm.manyToMany(
s as Schema,
name as string,
target as string,
joinTable as string,
localFk as string,
targetFk as string)Declare a many-to-many relation through a join table. E.g. a post has many tags via post_tags(postId, tagId): manyToMany(s, "tags", "tags", "post_tags", "postId", "tagId"). The target's primary key is id by convention, and this table's key is its primary key.
s- the source schema
name- the relation name
target- the target table
joinTable- the join (through) table
localFk- the join-table column referencing this table
targetFk- the join-table column referencing the target
- Returns
Schema - the schema with the relation added
notNull
orm.notNull(s as Schema)A copy of s marking its most-recently-added column NOT NULL.
s- the source schema
- Returns
Schema - the schema with the last column made non-nullable
offset
orm.offset(q as Query, n as int)A copy of q with an OFFSET.
q- the source query
n- the row offset (>= 0; negative throws kind
orm) - Returns
Query - the extended query
oneToMany
orm.oneToMany(
s as Schema,
name as string,
target as string,
foreignKey as string)Declare a one-to-many (has-many) relation: the target table holds foreignKey, which references this table's primary key. E.g. an author has many posts via posts.authorId -> authors.id.
s- the source schema
name- the relation name
target- the target table
foreignKey- the foreign-key column on the target table
- Returns
Schema - the schema with the relation added
oneToOne
orm.oneToOne(
s as Schema,
name as string,
target as string,
foreignKey as string)Declare a one-to-one (has-one) relation: the target table holds foreignKey, which references this table's primary key. E.g. a user has one profile via profiles.userId -> users.id.
s- the source schema
name- the relation name
target- the target table
foreignKey- the foreign-key column on the target table
- Returns
Schema - the schema with the relation added
orHaving
orm.orHaving(
q as Query,
fn as string,
col as string,
op as string,
value as string)Like having, but OR-joined to the previous HAVING condition.
q- the source query
fn- the aggregate function
col- the aggregated column (or
"*") op- the operator
value- the value to bind
- Returns
Query - the extended query
orWhere
orm.orWhere(q as Query, col as string, op as string, value as string)Like where, but OR-joined to the previous condition. SQL binds AND tighter than OR, so where(...).orWhere(...) reads a AND b OR c = (a AND b) OR c.
q- the source query
col- the column
op- the operator
value- the value to bind
- Returns
Query - the extended query
orWhereIn
orm.orWhereIn(q as Query, col as string, values as list of string)Like whereIn, but OR-joined to the previous condition.
q- the source query
col- the column
values- the values (must be non-empty)
- Returns
Query - the extended query
orderBy
orm.orderBy(q as Query, col as string, dir as string)A copy of q with an ORDER BY term added.
q- the source query
col- the column
dir"asc"or"desc"- Returns
Query - the extended query
page
orm.page(q as Query, pageNum as int, pageSize as int)A copy of q with LIMIT / OFFSET set for a 1-based page: page pageNum of pageSize rows (page 1 starts at offset 0).
q- the source query
pageNum- the 1-based page number
pageSize- the rows per page
- Returns
Query - the paginated query
pluck
orm.pluck(session as Session, q as Query, col as string)The values of one column across every row a query matches (the column must be in the projection; the default SELECT * includes it).
session- the session (
orm.sessionororm.transaction) q- the query
col- the column to pluck
- Returns
list of string - the column's value for each matching row
related
orm.related(
result as Result,
row as map of string to string,
name as string)The eager-loaded child rows of row for a has-many / many-to-many relation (an empty list if the row has none). No query - a lookup into the Result.
result- the load result
row- one base row (from
orm.rows) name- the relation name
- Returns
list of map of string to string - the related child rows
relatedOne
orm.relatedOne(
result as Result,
row as map of string to string,
name as string)The single eager-loaded row of row for a belongs-to / has-one relation, or an empty map when there is none (a null / unmatched foreign key). No query.
result- the load result
row- one base row (from
orm.rows) name- the relation name
- Returns
map of string to string - the related row, or
{}if none
renameColumn
orm.renameColumn(table as string, fromName as string, toName as string)The ALTER TABLE ... RENAME COLUMN DDL (modern MySQL 8+ / MariaDB / Postgres syntax).
table- the table name
fromName- the current column name
toName- the new column name
- Returns
string - the ALTER TABLE RENAME COLUMN statement
rightJoin
orm.rightJoin(
q as Query,
table as string,
leftCol as string,
rightCol as string)A copy of q with a RIGHT JOIN.
q- the source query
table- the table to join
leftCol- the left join column (
table.col) rightCol- the right join column
- Returns
Query - the extended query
rows
orm.rows(result as Result)The base rows of a Result (the same rows orm.all would return).
result- the load result
- Returns
list of map of string to string - the base rows
save
orm.save(session as Session, s as Schema, record as map of string to string)Insert record when it carries no primary key, else update it (matched by the primary key). A Data-Mapper convenience - still no per-row method. (A new row with an explicitly-assigned primary key should use orm.insert.)
session- the session (
orm.sessionororm.transaction) s- the schema
record- the row
- Returns
sql.Result - the affected-rows result
schema
orm.schema(table as string, primaryKey as string, dialect as Dialect)Start a schema for a table with its primary-key column and dialect. Add columns with orm.column.
table- the table name
primaryKey- the primary-key column
dialectorm.Dialect.Mysqlororm.Dialect.Postgres- Returns
Schema - the schema (no columns yet)
select
orm.select(q as Query, cols as list of string)A copy of q projecting only the named columns (instead of SELECT *). Additive: call again, or combine with count / aggregate.
q- the source query
cols- the columns to project
- Returns
Query - the extended query
session
orm.session(conn as sql.Connection)A session that runs each statement directly on a connection (auto-commit).
conn- the open connection
- Returns
Session - an auto-committing session
toSql
orm.toSql(q as Query)Render a query to parameterized SQL for its dialect. Pure - the whole query-builder surface is testable without a database. Every identifier and operator is re-validated here (validateQuery), so a hand-built Query literal that skipped the builder guards still cannot inject.
q- the query
- Returns
Rendered - the SQL text and ordered bind values
transaction
orm.transaction(tx as sql.Tx)A session that runs its statements inside a caller-managed transaction. The caller owns sql.begin / commit / rollback; orm just executes through the Tx. The idiom is sql.begin + errdefer sql.rollback + orm.transaction + sql.commit.
tx- the open transaction
- Returns
Session - a transaction-bound session
unique
orm.unique(s as Schema)A copy of s adding a UNIQUE constraint to its most-recently-added column.
s- the source schema
- Returns
Schema - the schema with the last column made unique
update
orm.update(
session as Session,
s as Schema,
record as map of string to string)Update a record, matched by its primary-key value (which the record must carry). Every other present column is written.
session- the session (
orm.sessionororm.transaction) s- the schema
record- the row, including the primary key
- Returns
sql.Result - the affected-rows result
- Throws
Error - when the record has no primary-key value
updateWhere
orm.updateWhere(
session as Session,
s as Schema,
assignments as map of string to string,
q as Query)Bulk-update every row matching a query's WHERE, setting assignments (column -> value, bound as parameters). Refuses a query with no WHERE.
session- the session (
orm.sessionororm.transaction) s- the schema
assignments- the columns to set
q- the query whose
WHEREselects the rows - Returns
sql.Result - the affected-rows result
upsert
orm.upsert(
session as Session,
s as Schema,
record as map of string to string,
conflictCols as list of string)Insert record, or update the conflicting row if a unique / primary-key conflict on conflictCols occurs (Postgres ON CONFLICT ... DO UPDATE, MySQL ON DUPLICATE KEY UPDATE). The non-conflict present columns are updated.
session- the session (
orm.sessionororm.transaction) s- the schema
record- the row to insert / update
conflictCols- the conflict-target columns (unique / PK; non-empty)
- Returns
sql.Result - the affected-rows result
where
orm.where(q as Query, col as string, op as string, value as string)A copy of q with a column op value condition AND-joined to the rest. The value binds as a parameter.
q- the source query
col- the column
op- the operator (
=,>,<,>=,<=,!=,<>,LIKE,NOT LIKE) value- the value to bind
- Returns
Query - the extended query
whereBetween
orm.whereBetween(q as Query, col as string, lo as string, hi as string)A copy of q with a column BETWEEN lo AND hi condition, AND-joined. Both bounds bind as parameters.
q- the source query
col- the column
lo- the lower bound (inclusive)
hi- the upper bound (inclusive)
- Returns
Query - the extended query
whereIn
orm.whereIn(q as Query, col as string, values as list of string)A copy of q with a column IN (...) condition AND-joined, one placeholder bound per value.
q- the source query
col- the column
values- the values (must be non-empty)
- Returns
Query - the extended query
whereNotIn
orm.whereNotIn(q as Query, col as string, values as list of string)A copy of q with a column NOT IN (...) condition AND-joined.
q- the source query
col- the column
values- the values (must be non-empty)
- Returns
Query - the extended query
whereNotNull
orm.whereNotNull(q as Query, col as string)A copy of q with a column IS NOT NULL condition, AND-joined.
q- the source query
col- the column
- Returns
Query - the extended query
whereNull
orm.whereNull(q as Query, col as string)A copy of q with a column IS NULL condition, AND-joined.
q- the source query
col- the column
- Returns
Query - the extended query
with
orm.with(q as Query, relationName as string)A copy of q marking a declared relation to eager-load with orm.load. Additive: call again for more relations. Does not change the base SQL (toSql ignores it); load runs one extra batched query per marked relation.
q- the source query
relationName- the relation to eager-load
- Returns
Query - the extended query
withDefault
orm.withDefault(s as Schema, value as string)A copy of s giving its most-recently-added column a DEFAULT. The value is rendered by the column kind: an Int / Float default is validated numeric and rendered bare; a Bool default accepts true/false/1/0; a String / Bytes default is rendered as a quoted, escaped SQL string literal (backslashes and control characters are rejected). So no default value can inject DDL.
s- the source schema
value- the default value (interpreted per the column kind)
- Returns
Schema - the schema with the last column defaulted
Structs
Column
One column in a schema: its name, value kind, and DDL attributes. The attributes drive createTable / addColumn DDL; set them with the fluent setters (notNull / unique / withDefault / autoIncrement), which decorate the most-recently-added column. A column is nullable by default (SQL's own default); notNull opts into NOT NULL.
def struct Column {
name as string,
kind as ColumnKind,
nullable as bool,
unique as bool,
hasDefault as bool,
default as string,
autoIncrement as bool
};name- the column name
kind- the value kind
nullable- whether the column allows NULL (true = no NOT NULL clause)
unique- whether the column carries a UNIQUE constraint
hasDefault- whether a DEFAULT is set (guards
default) default- the DEFAULT value (rendered by kind: numeric/bool bare, string quoted+escaped)
autoIncrement- whether the column auto-increments (
SERIAL/AUTO_INCREMENT)
Condition
A single WHERE condition within a Query; its bound value(s) live in the query's params list (positionally). Built by orm.where / orWhere / whereIn, not directly.
def struct Condition {
column as string,
op as string,
connector as string,
valueCount as int
};column- the column
op- the comparison operator (or
IN/NOT IN) connector"AND"or"OR"- how this joins the previous conditionvalueCount- the number of placeholders this condition consumes (1, or N for
IN)
Having
A single HAVING condition over an aggregate, its value in havingParams. Built by orm.having, not directly.
def struct Having {
func as string,
column as string,
op as string,
connector as string
};func- the aggregate function (COUNT / SUM / AVG / MIN / MAX)
column- the aggregated column (or "" for COUNT())
op- the comparison operator
connector"AND"or"OR"- how this joins the previous HAVING condition
Join
One JOIN clause: its kind and the left = right equality. Built by orm.join / orm.leftJoin / orm.rightJoin, not directly.
def struct Join {
kind as string,
table as string,
leftCol as string,
rightCol as string
};kind"INNER","LEFT", or"RIGHT"table- the joined table
leftCol- the left join column (
table.col) rightCol- the right join column
Order
One ORDER BY term. Built by orm.orderBy, not directly.
def struct Order {
column as string,
dir as string
};column- the column
dir"ASC"or"DESC"
Query
A composable, non-mutating SELECT query. Build it with from / select / count / aggregate / where / orWhere / whereIn / join / leftJoin / groupBy / having / orderBy / limit / offset, then render with toSql. Every identifier is re-validated at render time, so a hand-built Query literal cannot bypass the injection guards.
def struct Query {
table as string,
dialect as Dialect,
selects as list of SelectItem,
wheres as list of Condition,
params as list of string,
joins as list of Join,
groups as list of string,
havings as list of Having,
havingParams as list of string,
orders as list of Order,
hasLimit as bool,
limitN as int,
hasOffset as bool,
offsetN as int,
withRelations as list of string,
distinctSelect as bool
};table- the base table
dialect- the SQL dialect
selects- the projection (empty =
SELECT *) wheres- the WHERE conditions
params- the bind values for the WHERE conditions
joins- the JOIN clauses
groups- the GROUP BY columns
havings- the HAVING conditions
havingParams- the bind values for the HAVING conditions
orders- the ORDER BY terms
hasLimit- whether a LIMIT is set
limitN- the LIMIT value
hasOffset- whether an OFFSET is set
offsetN- the OFFSET value
withRelations- relation names to eager-load (consumed by
load, ignored bytoSql) distinctSelect- whether to render
SELECT DISTINCT
Relation
A declared association from a schema to another table. Metadata only - built by orm.belongsTo / oneToOne / oneToMany / manyToMany, read by orm.joinRelation and eager loading (orm.with / orm.load). For a BelongsTo, foreignKey is on this table and localKey is the target's key; for HasOne / HasMany, foreignKey is on the target table and localKey is this table's key. ManyToMany links through through (a join table) via its two keys.
def struct Relation {
name as string,
kind as RelationKind,
target as string,
foreignKey as string,
localKey as string,
through as string,
throughLocalKey as string,
throughTargetKey as string
};name- the relation's name (the lookup key for joinRelation / eager loading)
kind- the association kind
target- the target table
foreignKey- the foreign-key column (side depends on kind)
localKey- the referenced key column (the "one" side's key)
through- the join table for ManyToMany (else "")
throughLocalKey- the join-table column referencing this table (else "")
throughTargetKey- the join-table column referencing the target (else "")
RelationData
The loaded child rows for one eager-loaded relation: a parent-key -> child-rows lookup, built once from a single batched query. Internal to a Result; read it through orm.related / orm.relatedOne, not directly.
def struct RelationData {
name as string,
parentKeyColumn as string,
byParentKey as map of string to list of map of string to string
};name- the relation name
parentKeyColumn- the base-row column whose value indexes the lookup
byParentKey- parent-key value -> its child rows
Rendered
A rendered, parameterized statement: the SQL text and the ordered bind values.
def struct Rendered {
sql as string,
params as list of string
};sql- the SQL with dialect placeholders
params- the bind values, in placeholder order
Result
The result of orm.load: the base query's rows plus the eager-loaded relations. Read the base rows with orm.rows and a row's related rows with orm.related (has-many / many-to-many) or orm.relatedOne (belongs-to / has-one).
def struct Result {
rows as list of map of string to string,
relations as list of RelationData
};rows- the base query's rows
relations- one entry per eager-loaded relation
Schema
A table mapping: the table name, its columns, the primary-key column, the SQL dialect, and any declared relations. Value-semantic; column returns a fresh schema.
def struct Schema {
table as string,
columns as list of Column,
primaryKey as string,
dialect as Dialect,
relations as list of Relation
};table- the table name
columns- the columns
primaryKey- the primary-key column name
dialect- the SQL dialect (placeholder + DDL spelling)
relations- the declared associations
SelectItem
One item in a SELECT projection: a plain column (func "") or an aggregate (func one of COUNT / SUM / AVG / MIN / MAX, rendered func(column) AS alias). Built by orm.select / orm.count / orm.aggregate, not directly.
def struct SelectItem {
func as string,
column as string,
alias as string
};func- the aggregate function, or "" for a plain column
column- the column (or "" for COUNT())
alias- the
ASalias for an aggregate, or "" for a plain column
Session
A unit of work wrapping either a sql.Connection (auto-committing) or a sql.Tx (inside a caller's transaction). Every persistence / query-executing function takes a Session as its first argument, so the same call runs standalone or inside a transaction. Value-semantic; build it with orm.session or orm.transaction, not directly (only the handle selected by inTx is ever touched).
def struct Session {
conn as sql.Connection,
tx as sql.Tx,
inTx as bool
};conn- the connection (used when
inTxis false) tx- the transaction (used when
inTxis true) inTx- which handle is live
Enums
ColumnKind
A column's value kind: the SQL type family createTable renders. One of orm.ColumnKind.Int / String / Float / Bool / Bytes.
Dialect
The SQL dialect: the backend selector that governs placeholder syntax and DDL spelling. orm.Dialect.Mysql or orm.Dialect.Postgres.
RelationKind
The kind of an association between two tables: orm.RelationKind.BelongsTo (this table holds the foreign key), HasOne / HasMany (the target table holds it), or ManyToMany (a join table links the two).