Skip to content

API Reference

All public exports from bigal.

initialize()

Creates repositories for all provided models.

ts
import { initialize } from 'bigal';

const repos = initialize({
  models: [Product, Store],
  pool,
  readonlyPool,
  connections,
  expose,
});

Parameters: InitializeOptions

OptionTypeRequiredDescription
modelsEntityStatic<Entity>[]YesModel classes decorated with @table()
poolPoolLikeYesPrimary connection pool
readonlyPoolPoolLikeNoPool for read operations (defaults to pool)
connectionsRecord<string, IConnection>NoNamed connections for multi-database setups
expose(repo, metadata) => voidNoCallback invoked for each created repository

Returns: Record<string, IReadonlyRepository<Entity> | IRepository<Entity>>

Repository

Full CRUD repository returned by initialize() for non-readonly models.

find()

ts
repository.find(options?): FindQuery<T>

Returns a query builder for multiple records. Options: { select?, pool? }.

findOne()

ts
repository.findOne(options?): FindOneQuery<T>

Returns a query builder for a single record or null. Options: { select?, pool? }.

count()

ts
repository.count(options?): CountQuery<T>

Returns a query builder that resolves to a number. Options: { pool? }. Prefer this over findOne() for existence checks - it performs better since it doesn't select or hydrate a row.

create()

ts
repository.create(values, options?): Promise<QueryResult<T>>
repository.create(values[], options?): Promise<QueryResult<T>[]>

Insert one or multiple records. Options: { returnRecords?, returnSelect?, onConflict? }.

An array inserts in a single statement. Prefer this over calling create() in a loop, which costs one round trip per record.

returnSelect narrows the returned columns and returnRecords: false skips them entirely, cutting transfer and hydration cost.

update()

ts
repository.update(where, values, options?): Promise<QueryResult<T>[]>

Update matching records. Options: { returnRecords?, returnSelect? }. As with create(), use returnSelect to return only the columns you need or returnRecords: false to skip the returned rows.

destroy()

ts
repository.destroy(where, options?): Promise<void>
repository.destroy(where, { returnRecords: true }): Promise<QueryResult<T>[]>

Delete matching records. Options: { returnRecords?, returnSelect? }. Unlike create()/update(), destroy() does not return records by default (plain DELETE, no RETURNING); pass returnRecords: true or returnSelect to get the deleted rows back.

ReadonlyRepository

Read-only repository returned for models with readonly: true. Exposes find(), findOne(), and count() only.

Query builder methods

All query types support fluent chaining. Each method returns a new immutable instance.

MethodAvailable onDescription
.where(query)find, findOne, countFilter records
.sort(value)find, findOneOrder results
.limit(n)findLimit rows returned
.skip(n)findSkip rows
.paginate(page, pageSize)findShorthand for skip + limit
.withCount()findReturn { results, totalCount }
.populate(relation, options?)find, findOneLoad related entities
.join(relation, alias?, on?)find, findOneINNER JOIN
.leftJoin(relation, alias?, on?)find, findOneLEFT JOIN
.distinctOn(columns)findPostgreSQL DISTINCT ON
.toJSON()find, findOneReturn plain objects

subquery()

ts
import { subquery } from 'bigal';

const sub = subquery(repository);

Returns a SubqueryBuilder with methods: select(), where(), sort(), limit(), groupBy(), having(), distinctOn().

Scalar aggregate shortcuts: sub.count(), sub.sum(col), sub.avg(col), sub.max(col), sub.min(col).

Decorators

@table(options)

Binds a class to a database table or view.

OptionTypeDescription
namestringTable or view name
schemastringPostgreSQL schema (default: public)
readonlybooleanReturns ReadonlyRepository if true
connectionstringNamed connection key

@primaryColumn(options)

Marks the primary key. Options: { type }.

@column(options)

Defines a column. See Models > Column options for all options. Vector columns are declared with { type: 'vector', dimensions: n } (dimensions is informational - BigAl does not issue DDL).

@createDateColumn()

Auto-set on insert.

@updateDateColumn()

Auto-set on update.

@versionColumn()

Auto-incrementing version for optimistic locking.

Types

Entity

Base class for all models.

NotEntity<T>

Wrapper type for JSON column objects that have an id field. Prevents BigAl's type system from treating them as entities.

QueryResult<T>

Narrows relationship fields from union types to foreign key types. See Relationships > QueryResult.

QueryResultPopulated<T, K>

Type for entities with specific relationships populated.

TypedAggregateExpression<Alias>

Return type annotation for aggregate callbacks that enables type-safe sorting on subquery join columns.

VectorDistanceMetric

ts
type VectorDistanceMetric = 'cosine' | 'innerProduct' | 'l1' | 'l2';

VectorDistanceSort

ts
interface VectorDistanceSort {
  nearestTo: number[];
  metric?: VectorDistanceMetric;
}

Used in .sort() for nearest-neighbor queries on vector columns. See Querying > Vector distance queries.

VectorDistanceConstraint

ts
interface VectorDistanceConstraint {
  nearestTo: number[];
  metric?: VectorDistanceMetric;
  distance: Partial<Record<'<' | '<=' | '>' | '>=', number>>;
}

Used in where clauses to filter vector columns by distance threshold. At least one distance bound is required (pgvector distance operators return a number, so a bare distance expression is not a valid where clause); multiple bounds are combined with AND. To order by distance without filtering, use sort() with nearestTo instead.

PoolLike

Interface for compatible connection pools. Supported: postgres-pool, pg, @neondatabase/serverless.

IConnection

ts
interface IConnection {
  pool: PoolLike;
  readonlyPool?: PoolLike;
}

IRepository<T>

Interface for full CRUD repositories.

IReadonlyRepository<T>

Interface for read-only repositories.