Skip to content
Jennifer Programming Language

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

NameWhat it is
addColumnThe `ALTER TABLE ...
addForeignKeyThe `ALTER TABLE ...
aggregateA copy of q adding func(col) AS alias to the projection.
allRun a query and return every matching row.
autoIncrementA copy of s marking its most-recently-added column auto-incrementing (SERIAL on Postgres,...
belongsToDeclare a belongs-to relation: this table holds foreignKey, which references the target's primary...
columnA copy of s with a column appended.
countA copy of q adding COUNT(*) AS alias to the projection.
createIndexThe CREATE [UNIQUE] INDEX DDL over one or more columns.
createTableThe CREATE TABLE DDL for a schema, in its dialect - including each column's NOT NULL / DEFAULT /...
deleteDelete a row by primary-key value.
deleteWhereBulk-delete every row matching a query's WHERE.
distinctA copy of q rendered as SELECT DISTINCT ....
dropColumnThe `ALTER TABLE ...
dropForeignKeyThe `ALTER TABLE ...
dropIndexThe DROP INDEX DDL (Postgres drops by index name; MySQL needs the table).
dropTableThe DROP TABLE DDL for a table.
existsWhether a query matches any row (adds LIMIT 1).
findFind a single row by primary-key value.
findByThe first row of the schema's table where col = value, or {} if none.
firstThe first row a query matches (adds LIMIT 1), or an empty map when there is none.
fromA base query selecting all rows of the schema's table.
groupByA copy of q grouping by the named columns.
havingA copy of q with a HAVING condition over an aggregate (func(col) op value), AND-joined.
insertInsert a record.
insertManyInsert many records in one multi-row INSERT.
insertReturningInsert record and return the generated primary-key value (Postgres RETURNING pk; MySQL LAST_INSERT_ID...
joinA copy of q with an INNER JOIN.
joinRelationA copy of q with the JOIN(s) that a declared relation implies - an INNER JOIN on the correct key colu...
leftJoinA copy of q with a LEFT JOIN.
limitA copy of q with a LIMIT.
loadRun a query and eager-load its orm.with-marked relations in a fixed 1 + R queries (R = relations requ...
manyToManyDeclare a many-to-many relation through a join table.
notNullA copy of s marking its most-recently-added column NOT NULL.
offsetA copy of q with an OFFSET.
oneToManyDeclare a one-to-many (has-many) relation: the target table holds foreignKey, which references th...
oneToOneDeclare a one-to-one (has-one) relation: the target table holds foreignKey, which references this...
orHavingLike having, but OR-joined to the previous HAVING condition.
orWhereLike where, but OR-joined to the previous condition.
orWhereInLike whereIn, but OR-joined to the previous condition.
orderByA copy of q with an ORDER BY term added.
pageA copy of q with LIMIT / OFFSET set for a 1-based page: page pageNum of pageSize rows (page 1 sta...
pluckThe values of one column across every row a query matches (the column must be in the projection; the defaul...
relatedThe eager-loaded child rows of row for a has-many / many-to-many relation (an empty list if the row has n...
relatedOneThe single eager-loaded row of row for a belongs-to / has-one relation, or an empty map when there is...
renameColumnThe `ALTER TABLE ...
rightJoinA copy of q with a RIGHT JOIN.
rowsThe base rows of a Result (the same rows orm.all would return).
saveInsert record when it carries no primary key, else update it (matched by the primary key).
schemaStart a schema for a table with its primary-key column and dialect.
selectA copy of q projecting only the named columns (instead of SELECT *).
sessionA session that runs each statement directly on a connection (auto-commit).
toSqlRender a query to parameterized SQL for its dialect.
transactionA session that runs its statements inside a caller-managed transaction.
uniqueA copy of s adding a UNIQUE constraint to its most-recently-added column.
updateUpdate a record, matched by its primary-key value (which the record must carry).
updateWhereBulk-update every row matching a query's WHERE, setting assignments (column -> value, bound as paramete...
upsertInsert record, or update the conflicting row if a unique / primary-key conflict on conflictCols occurs ...
whereA copy of q with a column op value condition AND-joined to the rest.
whereBetweenA copy of q with a column BETWEEN lo AND hi condition, AND-joined.
whereInA copy of q with a column IN (...) condition AND-joined, one placeholder bound per value.
whereNotInA copy of q with a column NOT IN (...) condition AND-joined.
whereNotNullA copy of q with a column IS NOT NULL condition, AND-joined.
whereNullA copy of q with a column IS NULL condition, AND-joined.
withA copy of q marking a declared relation to eager-load with orm.load.
withDefaultA copy of s giving its most-recently-added column a DEFAULT.
Columnstruct: One column in a schema: its name, value kind, and DDL attributes.
Conditionstruct: A single WHERE condition within a Query; its bound value(s) live in the query's params list (positional...
Havingstruct: A single HAVING condition over an aggregate, its value in havingParams.
Joinstruct: One JOIN clause: its kind and the left = right equality.
Orderstruct: One ORDER BY term.
Querystruct: A composable, non-mutating SELECT query.
Relationstruct: A declared association from a schema to another table.
RelationDatastruct: The loaded child rows for one eager-loaded relation: a parent-key -> child-rows lookup, built once from a s...
Renderedstruct: A rendered, parameterized statement: the SQL text and the ordered bind values.
Resultstruct: The result of orm.load: the base query's rows plus the eager-loaded relations.
Schemastruct: A table mapping: the table name, its columns, the primary-key column, the SQL dialect, and any declared rel...
SelectItemstruct: One item in a SELECT projection: a plain column (func "") or an aggregate (func one of COUNT / SUM / AV...
Sessionstruct: A unit of work wrapping either a sql.Connection (auto-committing) or a sql.Tx (inside a caller's transa...
ColumnKindenum: A column's value kind: the SQL type family createTable renders.
Dialectenum: The SQL dialect: the backend selector that governs placeholder syntax and DDL spelling.
RelationKindenum: The kind of an association between two tables: orm.RelationKind.BelongsTo (this table holds the foreign k...

Functions

addColumn

jennifer
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

jennifer
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

jennifer
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

jennifer
orm.all(session as Session, q as Query)

Run a query and return every matching row.

session
the session (orm.session or orm.transaction)
q
the query (from the builder)
Returns list of map of string to string
the rows

autoIncrement

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
orm.delete(session as Session, s as Schema, id as string)

Delete a row by primary-key value.

session
the session (orm.session or orm.transaction)
s
the schema
id
the primary-key value
Returns sql.Result
the affected-rows result

deleteWhere

jennifer
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.session or orm.transaction)
s
the schema
q
the query whose WHERE selects the rows
Returns sql.Result
the affected-rows result

distinct

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
orm.dropTable(table as string)

The DROP TABLE DDL for a table.

table
the table name
Returns string
the DROP TABLE statement

exists

jennifer
orm.exists(session as Session, q as Query)

Whether a query matches any row (adds LIMIT 1).

session
the session (orm.session or orm.transaction)
q
the query
Returns bool
true if at least one row matches

find

jennifer
orm.find(session as Session, s as Schema, id as string)

Find a single row by primary-key value.

session
the session (orm.session or orm.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

jennifer
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.session or orm.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

jennifer
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.session or orm.transaction)
q
the query
Returns map of string to string
the first row, or {} if none

from

jennifer
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

jennifer
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

jennifer
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

jennifer
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.session or orm.transaction)
s
the schema
record
column name -> value
Returns sql.Result
the affected-rows / last-insert-id result

insertMany

jennifer
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.session or orm.transaction)
s
the schema
records
the rows to insert
Returns int
the number of records inserted

insertReturning

jennifer
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.session or orm.transaction)
s
the schema
record
the row to insert
Returns string
the generated primary-key value

join

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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.session or orm.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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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.session or orm.transaction)
q
the query
col
the column to pluck
Returns list of string
the column's value for each matching row
jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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.session or orm.transaction)
s
the schema
record
the row
Returns sql.Result
the affected-rows result

schema

jennifer
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
dialect
orm.Dialect.Mysql or orm.Dialect.Postgres
Returns Schema
the schema (no columns yet)

select

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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.session or orm.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

jennifer
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.session or orm.transaction)
s
the schema
assignments
the columns to set
q
the query whose WHERE selects the rows
Returns sql.Result
the affected-rows result

upsert

jennifer
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.session or orm.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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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

jennifer
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.

jennifer
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.

jennifer
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 condition
valueCount
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.

jennifer
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.

jennifer
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.

jennifer
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.

jennifer
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 by toSql)
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.

jennifer
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.

jennifer
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.

jennifer
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).

jennifer
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.

jennifer
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.

jennifer
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 AS alias 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).

jennifer
def struct Session {
    conn as sql.Connection,
    tx as sql.Tx,
    inTx as bool
};
conn
the connection (used when inTx is false)
tx
the transaction (used when inTx is 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).