Files
esports/build/server/chunks/index2-B7hVh_Qf.js

7046 lines
211 KiB
JavaScript

import pgClient from 'postgres';
import { b as private_env } from './shared-server-DaWdgxVh.js';
const entityKind = Symbol.for("drizzle:entityKind");
function is(value, type) {
if (!value || typeof value !== "object") {
return false;
}
if (value instanceof type) {
return true;
}
if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
throw new Error(
`Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`
);
}
let cls = Object.getPrototypeOf(value).constructor;
if (cls) {
while (cls) {
if (entityKind in cls && cls[entityKind] === type[entityKind]) {
return true;
}
cls = Object.getPrototypeOf(cls);
}
}
return false;
}
class Column {
constructor(table, config) {
this.table = table;
this.config = config;
this.name = config.name;
this.keyAsName = config.keyAsName;
this.notNull = config.notNull;
this.default = config.default;
this.defaultFn = config.defaultFn;
this.onUpdateFn = config.onUpdateFn;
this.hasDefault = config.hasDefault;
this.primary = config.primaryKey;
this.isUnique = config.isUnique;
this.uniqueName = config.uniqueName;
this.uniqueType = config.uniqueType;
this.dataType = config.dataType;
this.columnType = config.columnType;
this.generated = config.generated;
this.generatedIdentity = config.generatedIdentity;
}
static [entityKind] = "Column";
name;
keyAsName;
primary;
notNull;
default;
defaultFn;
onUpdateFn;
hasDefault;
isUnique;
uniqueName;
uniqueType;
dataType;
columnType;
enumValues = void 0;
generated = void 0;
generatedIdentity = void 0;
config;
mapFromDriverValue(value) {
return value;
}
mapToDriverValue(value) {
return value;
}
// ** @internal */
shouldDisableInsert() {
return this.config.generated !== void 0 && this.config.generated.type !== "byDefault";
}
}
class ColumnBuilder {
static [entityKind] = "ColumnBuilder";
config;
constructor(name, dataType, columnType) {
this.config = {
name,
keyAsName: name === "",
notNull: false,
default: void 0,
hasDefault: false,
primaryKey: false,
isUnique: false,
uniqueName: void 0,
uniqueType: void 0,
dataType,
columnType,
generated: void 0
};
}
/**
* Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.
*
* @example
* ```ts
* const users = pgTable('users', {
* id: integer('id').$type<UserId>().primaryKey(),
* details: json('details').$type<UserDetails>().notNull(),
* });
* ```
*/
$type() {
return this;
}
/**
* Adds a `not null` clause to the column definition.
*
* Affects the `select` model of the table - columns *without* `not null` will be nullable on select.
*/
notNull() {
this.config.notNull = true;
return this;
}
/**
* Adds a `default <value>` clause to the column definition.
*
* Affects the `insert` model of the table - columns *with* `default` are optional on insert.
*
* If you need to set a dynamic default value, use {@link $defaultFn} instead.
*/
default(value) {
this.config.default = value;
this.config.hasDefault = true;
return this;
}
/**
* Adds a dynamic default value to the column.
* The function will be called when the row is inserted, and the returned value will be used as the column value.
*
* **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
*/
$defaultFn(fn) {
this.config.defaultFn = fn;
this.config.hasDefault = true;
return this;
}
/**
* Alias for {@link $defaultFn}.
*/
$default = this.$defaultFn;
/**
* Adds a dynamic update value to the column.
* The function will be called when the row is updated, and the returned value will be used as the column value if none is provided.
* If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value.
*
* **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
*/
$onUpdateFn(fn) {
this.config.onUpdateFn = fn;
this.config.hasDefault = true;
return this;
}
/**
* Alias for {@link $onUpdateFn}.
*/
$onUpdate = this.$onUpdateFn;
/**
* Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.
*
* In SQLite, `integer primary key` implicitly makes the column auto-incrementing.
*/
primaryKey() {
this.config.primaryKey = true;
this.config.notNull = true;
return this;
}
/** @internal Sets the name of the column to the key within the table definition if a name was not given. */
setName(name) {
if (this.config.name !== "") return;
this.config.name = name;
}
}
const TableName = Symbol.for("drizzle:Name");
class ForeignKeyBuilder {
static [entityKind] = "PgForeignKeyBuilder";
/** @internal */
reference;
/** @internal */
_onUpdate = "no action";
/** @internal */
_onDelete = "no action";
constructor(config, actions) {
this.reference = () => {
const { name, columns, foreignColumns } = config();
return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns };
};
if (actions) {
this._onUpdate = actions.onUpdate;
this._onDelete = actions.onDelete;
}
}
onUpdate(action) {
this._onUpdate = action === void 0 ? "no action" : action;
return this;
}
onDelete(action) {
this._onDelete = action === void 0 ? "no action" : action;
return this;
}
/** @internal */
build(table) {
return new ForeignKey(table, this);
}
}
class ForeignKey {
constructor(table, builder) {
this.table = table;
this.reference = builder.reference;
this.onUpdate = builder._onUpdate;
this.onDelete = builder._onDelete;
}
static [entityKind] = "PgForeignKey";
reference;
onUpdate;
onDelete;
getName() {
const { name, columns, foreignColumns } = this.reference();
const columnNames = columns.map((column) => column.name);
const foreignColumnNames = foreignColumns.map((column) => column.name);
const chunks = [
this.table[TableName],
...columnNames,
foreignColumns[0].table[TableName],
...foreignColumnNames
];
return name ?? `${chunks.join("_")}_fk`;
}
}
function iife(fn, ...args) {
return fn(...args);
}
function uniqueKeyName(table, columns) {
return `${table[TableName]}_${columns.join("_")}_unique`;
}
function parsePgArrayValue(arrayString, startFrom, inQuotes) {
for (let i = startFrom; i < arrayString.length; i++) {
const char = arrayString[i];
if (char === "\\") {
i++;
continue;
}
if (char === '"') {
return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1];
}
if (inQuotes) {
continue;
}
if (char === "," || char === "}") {
return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i];
}
}
return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length];
}
function parsePgNestedArray(arrayString, startFrom = 0) {
const result = [];
let i = startFrom;
let lastCharIsComma = false;
while (i < arrayString.length) {
const char = arrayString[i];
if (char === ",") {
if (lastCharIsComma || i === startFrom) {
result.push("");
}
lastCharIsComma = true;
i++;
continue;
}
lastCharIsComma = false;
if (char === "\\") {
i += 2;
continue;
}
if (char === '"') {
const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true);
result.push(value2);
i = startFrom2;
continue;
}
if (char === "}") {
return [result, i + 1];
}
if (char === "{") {
const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1);
result.push(value2);
i = startFrom2;
continue;
}
const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);
result.push(value);
i = newStartFrom;
}
return [result, i];
}
function parsePgArray(arrayString) {
const [result] = parsePgNestedArray(arrayString, 1);
return result;
}
function makePgArray(array) {
return `{${array.map((item) => {
if (Array.isArray(item)) {
return makePgArray(item);
}
if (typeof item === "string") {
return `"${item.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
}
return `${item}`;
}).join(",")}}`;
}
class PgColumnBuilder extends ColumnBuilder {
foreignKeyConfigs = [];
static [entityKind] = "PgColumnBuilder";
array(size) {
return new PgArrayBuilder(this.config.name, this, size);
}
references(ref, actions = {}) {
this.foreignKeyConfigs.push({ ref, actions });
return this;
}
unique(name, config) {
this.config.isUnique = true;
this.config.uniqueName = name;
this.config.uniqueType = config?.nulls;
return this;
}
generatedAlwaysAs(as) {
this.config.generated = {
as,
type: "always",
mode: "stored"
};
return this;
}
/** @internal */
buildForeignKeys(column, table) {
return this.foreignKeyConfigs.map(({ ref, actions }) => {
return iife(
(ref2, actions2) => {
const builder = new ForeignKeyBuilder(() => {
const foreignColumn = ref2();
return { columns: [column], foreignColumns: [foreignColumn] };
});
if (actions2.onUpdate) {
builder.onUpdate(actions2.onUpdate);
}
if (actions2.onDelete) {
builder.onDelete(actions2.onDelete);
}
return builder.build(table);
},
ref,
actions
);
});
}
/** @internal */
buildExtraConfigColumn(table) {
return new ExtraConfigColumn(table, this.config);
}
}
class PgColumn extends Column {
constructor(table, config) {
if (!config.uniqueName) {
config.uniqueName = uniqueKeyName(table, [config.name]);
}
super(table, config);
this.table = table;
}
static [entityKind] = "PgColumn";
}
class ExtraConfigColumn extends PgColumn {
static [entityKind] = "ExtraConfigColumn";
getSQLType() {
return this.getSQLType();
}
indexConfig = {
order: this.config.order ?? "asc",
nulls: this.config.nulls ?? "last",
opClass: this.config.opClass
};
defaultConfig = {
order: "asc",
nulls: "last",
opClass: void 0
};
asc() {
this.indexConfig.order = "asc";
return this;
}
desc() {
this.indexConfig.order = "desc";
return this;
}
nullsFirst() {
this.indexConfig.nulls = "first";
return this;
}
nullsLast() {
this.indexConfig.nulls = "last";
return this;
}
/**
* ### PostgreSQL documentation quote
*
* > An operator class with optional parameters can be specified for each column of an index.
* The operator class identifies the operators to be used by the index for that column.
* For example, a B-tree index on four-byte integers would use the int4_ops class;
* this operator class includes comparison functions for four-byte integers.
* In practice the default operator class for the column's data type is usually sufficient.
* The main point of having operator classes is that for some data types, there could be more than one meaningful ordering.
* For example, we might want to sort a complex-number data type either by absolute value or by real part.
* We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index.
* More information about operator classes check:
*
* ### Useful links
* https://www.postgresql.org/docs/current/sql-createindex.html
*
* https://www.postgresql.org/docs/current/indexes-opclass.html
*
* https://www.postgresql.org/docs/current/xindex.html
*
* ### Additional types
* If you have the `pg_vector` extension installed in your database, you can use the
* `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types.
*
* **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types**
*
* @param opClass
* @returns
*/
op(opClass) {
this.indexConfig.opClass = opClass;
return this;
}
}
class IndexedColumn {
static [entityKind] = "IndexedColumn";
constructor(name, keyAsName, type, indexConfig) {
this.name = name;
this.keyAsName = keyAsName;
this.type = type;
this.indexConfig = indexConfig;
}
name;
keyAsName;
type;
indexConfig;
}
class PgArrayBuilder extends PgColumnBuilder {
static [entityKind] = "PgArrayBuilder";
constructor(name, baseBuilder, size) {
super(name, "array", "PgArray");
this.config.baseBuilder = baseBuilder;
this.config.size = size;
}
/** @internal */
build(table) {
const baseColumn = this.config.baseBuilder.build(table);
return new PgArray(
table,
this.config,
baseColumn
);
}
}
class PgArray extends PgColumn {
constructor(table, config, baseColumn, range) {
super(table, config);
this.baseColumn = baseColumn;
this.range = range;
this.size = config.size;
}
size;
static [entityKind] = "PgArray";
getSQLType() {
return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`;
}
mapFromDriverValue(value) {
if (typeof value === "string") {
value = parsePgArray(value);
}
return value.map((v) => this.baseColumn.mapFromDriverValue(v));
}
mapToDriverValue(value, isNestedArray = false) {
const a = value.map(
(v) => v === null ? null : is(this.baseColumn, PgArray) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v)
);
if (isNestedArray) return a;
return makePgArray(a);
}
}
const isPgEnumSym = Symbol.for("drizzle:isPgEnum");
function isPgEnum(obj) {
return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
}
class Subquery {
static [entityKind] = "Subquery";
constructor(sql, fields, alias, isWith = false, usedTables = []) {
this._ = {
brand: "Subquery",
sql,
selectedFields: fields,
alias,
isWith,
usedTables
};
}
// getSQL(): SQL<unknown> {
// return new SQL([this]);
// }
}
class WithSubquery extends Subquery {
static [entityKind] = "WithSubquery";
}
const tracer = {
startActiveSpan(name, fn) {
{
return fn();
}
}
};
const ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
const Schema = Symbol.for("drizzle:Schema");
const Columns = Symbol.for("drizzle:Columns");
const ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
const OriginalName = Symbol.for("drizzle:OriginalName");
const BaseName = Symbol.for("drizzle:BaseName");
const IsAlias = Symbol.for("drizzle:IsAlias");
const ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder");
const IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable");
class Table {
static [entityKind] = "Table";
/** @internal */
static Symbol = {
Name: TableName,
Schema,
OriginalName,
Columns,
ExtraConfigColumns,
BaseName,
IsAlias,
ExtraConfigBuilder
};
/**
* @internal
* Can be changed if the table is aliased.
*/
[TableName];
/**
* @internal
* Used to store the original name of the table, before any aliasing.
*/
[OriginalName];
/** @internal */
[Schema];
/** @internal */
[Columns];
/** @internal */
[ExtraConfigColumns];
/**
* @internal
* Used to store the table name before the transformation via the `tableCreator` functions.
*/
[BaseName];
/** @internal */
[IsAlias] = false;
/** @internal */
[IsDrizzleTable] = true;
/** @internal */
[ExtraConfigBuilder] = void 0;
constructor(name, schema, baseName) {
this[TableName] = this[OriginalName] = name;
this[Schema] = schema;
this[BaseName] = baseName;
}
}
function getTableName(table) {
return table[TableName];
}
function getTableUniqueName(table) {
return `${table[Schema] ?? "public"}.${table[TableName]}`;
}
function isSQLWrapper(value) {
return value !== null && value !== void 0 && typeof value.getSQL === "function";
}
function mergeQueries(queries) {
const result = { sql: "", params: [] };
for (const query of queries) {
result.sql += query.sql;
result.params.push(...query.params);
if (query.typings?.length) {
if (!result.typings) {
result.typings = [];
}
result.typings.push(...query.typings);
}
}
return result;
}
class StringChunk {
static [entityKind] = "StringChunk";
value;
constructor(value) {
this.value = Array.isArray(value) ? value : [value];
}
getSQL() {
return new SQL([this]);
}
}
class SQL {
constructor(queryChunks) {
this.queryChunks = queryChunks;
for (const chunk of queryChunks) {
if (is(chunk, Table)) {
const schemaName = chunk[Table.Symbol.Schema];
this.usedTables.push(
schemaName === void 0 ? chunk[Table.Symbol.Name] : schemaName + "." + chunk[Table.Symbol.Name]
);
}
}
}
static [entityKind] = "SQL";
/** @internal */
decoder = noopDecoder;
shouldInlineParams = false;
/** @internal */
usedTables = [];
append(query) {
this.queryChunks.push(...query.queryChunks);
return this;
}
toQuery(config) {
return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
const query = this.buildQueryFromSourceParams(this.queryChunks, config);
span?.setAttributes({
"drizzle.query.text": query.sql,
"drizzle.query.params": JSON.stringify(query.params)
});
return query;
});
}
buildQueryFromSourceParams(chunks, _config) {
const config = Object.assign({}, _config, {
inlineParams: _config.inlineParams || this.shouldInlineParams,
paramStartIndex: _config.paramStartIndex || { value: 0 }
});
const {
casing,
escapeName,
escapeParam,
prepareTyping,
inlineParams,
paramStartIndex
} = config;
return mergeQueries(chunks.map((chunk) => {
if (is(chunk, StringChunk)) {
return { sql: chunk.value.join(""), params: [] };
}
if (is(chunk, Name)) {
return { sql: escapeName(chunk.value), params: [] };
}
if (chunk === void 0) {
return { sql: "", params: [] };
}
if (Array.isArray(chunk)) {
const result = [new StringChunk("(")];
for (const [i, p] of chunk.entries()) {
result.push(p);
if (i < chunk.length - 1) {
result.push(new StringChunk(", "));
}
}
result.push(new StringChunk(")"));
return this.buildQueryFromSourceParams(result, config);
}
if (is(chunk, SQL)) {
return this.buildQueryFromSourceParams(chunk.queryChunks, {
...config,
inlineParams: inlineParams || chunk.shouldInlineParams
});
}
if (is(chunk, Table)) {
const schemaName = chunk[Table.Symbol.Schema];
const tableName = chunk[Table.Symbol.Name];
return {
sql: schemaName === void 0 || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
params: []
};
}
if (is(chunk, Column)) {
const columnName = casing.getColumnCasing(chunk);
if (_config.invokeSource === "indexes") {
return { sql: escapeName(columnName), params: [] };
}
const schemaName = chunk.table[Table.Symbol.Schema];
return {
sql: chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName),
params: []
};
}
if (is(chunk, View)) {
const schemaName = chunk[ViewBaseConfig].schema;
const viewName = chunk[ViewBaseConfig].name;
return {
sql: schemaName === void 0 || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
params: []
};
}
if (is(chunk, Param)) {
if (is(chunk.value, Placeholder)) {
return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
}
const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
if (is(mappedValue, SQL)) {
return this.buildQueryFromSourceParams([mappedValue], config);
}
if (inlineParams) {
return { sql: this.mapInlineParam(mappedValue, config), params: [] };
}
let typings = ["none"];
if (prepareTyping) {
typings = [prepareTyping(chunk.encoder)];
}
return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
}
if (is(chunk, Placeholder)) {
return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
}
if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== void 0) {
return { sql: escapeName(chunk.fieldAlias), params: [] };
}
if (is(chunk, Subquery)) {
if (chunk._.isWith) {
return { sql: escapeName(chunk._.alias), params: [] };
}
return this.buildQueryFromSourceParams([
new StringChunk("("),
chunk._.sql,
new StringChunk(") "),
new Name(chunk._.alias)
], config);
}
if (isPgEnum(chunk)) {
if (chunk.schema) {
return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] };
}
return { sql: escapeName(chunk.enumName), params: [] };
}
if (isSQLWrapper(chunk)) {
if (chunk.shouldOmitSQLParens?.()) {
return this.buildQueryFromSourceParams([chunk.getSQL()], config);
}
return this.buildQueryFromSourceParams([
new StringChunk("("),
chunk.getSQL(),
new StringChunk(")")
], config);
}
if (inlineParams) {
return { sql: this.mapInlineParam(chunk, config), params: [] };
}
return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
}));
}
mapInlineParam(chunk, { escapeString }) {
if (chunk === null) {
return "null";
}
if (typeof chunk === "number" || typeof chunk === "boolean") {
return chunk.toString();
}
if (typeof chunk === "string") {
return escapeString(chunk);
}
if (typeof chunk === "object") {
const mappedValueAsString = chunk.toString();
if (mappedValueAsString === "[object Object]") {
return escapeString(JSON.stringify(chunk));
}
return escapeString(mappedValueAsString);
}
throw new Error("Unexpected param value: " + chunk);
}
getSQL() {
return this;
}
as(alias) {
if (alias === void 0) {
return this;
}
return new SQL.Aliased(this, alias);
}
mapWith(decoder) {
this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
return this;
}
inlineParams() {
this.shouldInlineParams = true;
return this;
}
/**
* This method is used to conditionally include a part of the query.
*
* @param condition - Condition to check
* @returns itself if the condition is `true`, otherwise `undefined`
*/
if(condition) {
return condition ? this : void 0;
}
}
class Name {
constructor(value) {
this.value = value;
}
static [entityKind] = "Name";
brand;
getSQL() {
return new SQL([this]);
}
}
function isDriverValueEncoder(value) {
return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function";
}
const noopDecoder = {
mapFromDriverValue: (value) => value
};
const noopEncoder = {
mapToDriverValue: (value) => value
};
({
...noopDecoder,
...noopEncoder
});
class Param {
/**
* @param value - Parameter value
* @param encoder - Encoder to convert the value to a driver parameter
*/
constructor(value, encoder = noopEncoder) {
this.value = value;
this.encoder = encoder;
}
static [entityKind] = "Param";
brand;
getSQL() {
return new SQL([this]);
}
}
function sql(strings, ...params) {
const queryChunks = [];
if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
queryChunks.push(new StringChunk(strings[0]));
}
for (const [paramIndex, param2] of params.entries()) {
queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
}
return new SQL(queryChunks);
}
((sql2) => {
function empty() {
return new SQL([]);
}
sql2.empty = empty;
function fromList(list) {
return new SQL(list);
}
sql2.fromList = fromList;
function raw(str) {
return new SQL([new StringChunk(str)]);
}
sql2.raw = raw;
function join(chunks, separator) {
const result = [];
for (const [i, chunk] of chunks.entries()) {
if (i > 0 && separator !== void 0) {
result.push(separator);
}
result.push(chunk);
}
return new SQL(result);
}
sql2.join = join;
function identifier(value) {
return new Name(value);
}
sql2.identifier = identifier;
function placeholder2(name2) {
return new Placeholder(name2);
}
sql2.placeholder = placeholder2;
function param2(value, encoder) {
return new Param(value, encoder);
}
sql2.param = param2;
})(sql || (sql = {}));
((SQL2) => {
class Aliased {
constructor(sql2, fieldAlias) {
this.sql = sql2;
this.fieldAlias = fieldAlias;
}
static [entityKind] = "SQL.Aliased";
/** @internal */
isSelectionField = false;
getSQL() {
return this.sql;
}
/** @internal */
clone() {
return new Aliased(this.sql, this.fieldAlias);
}
}
SQL2.Aliased = Aliased;
})(SQL || (SQL = {}));
class Placeholder {
constructor(name2) {
this.name = name2;
}
static [entityKind] = "Placeholder";
getSQL() {
return new SQL([this]);
}
}
function fillPlaceholders(params, values) {
return params.map((p) => {
if (is(p, Placeholder)) {
if (!(p.name in values)) {
throw new Error(`No value for placeholder "${p.name}" was provided`);
}
return values[p.name];
}
if (is(p, Param) && is(p.value, Placeholder)) {
if (!(p.value.name in values)) {
throw new Error(`No value for placeholder "${p.value.name}" was provided`);
}
return p.encoder.mapToDriverValue(values[p.value.name]);
}
return p;
});
}
const IsDrizzleView = Symbol.for("drizzle:IsDrizzleView");
class View {
static [entityKind] = "View";
/** @internal */
[ViewBaseConfig];
/** @internal */
[IsDrizzleView] = true;
constructor({ name: name2, schema, selectedFields, query }) {
this[ViewBaseConfig] = {
name: name2,
originalName: name2,
schema,
selectedFields,
query,
isExisting: !query,
isAlias: false
};
}
getSQL() {
return new SQL([this]);
}
}
Column.prototype.getSQL = function() {
return new SQL([this]);
};
Table.prototype.getSQL = function() {
return new SQL([this]);
};
Subquery.prototype.getSQL = function() {
return new SQL([this]);
};
class ColumnAliasProxyHandler {
constructor(table) {
this.table = table;
}
static [entityKind] = "ColumnAliasProxyHandler";
get(columnObj, prop) {
if (prop === "table") {
return this.table;
}
return columnObj[prop];
}
}
class TableAliasProxyHandler {
constructor(alias, replaceOriginalName) {
this.alias = alias;
this.replaceOriginalName = replaceOriginalName;
}
static [entityKind] = "TableAliasProxyHandler";
get(target, prop) {
if (prop === Table.Symbol.IsAlias) {
return true;
}
if (prop === Table.Symbol.Name) {
return this.alias;
}
if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) {
return this.alias;
}
if (prop === ViewBaseConfig) {
return {
...target[ViewBaseConfig],
name: this.alias,
isAlias: true
};
}
if (prop === Table.Symbol.Columns) {
const columns = target[Table.Symbol.Columns];
if (!columns) {
return columns;
}
const proxiedColumns = {};
Object.keys(columns).map((key) => {
proxiedColumns[key] = new Proxy(
columns[key],
new ColumnAliasProxyHandler(new Proxy(target, this))
);
});
return proxiedColumns;
}
const value = target[prop];
if (is(value, Column)) {
return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
}
return value;
}
}
function aliasedTable(table, tableAlias) {
return new Proxy(table, new TableAliasProxyHandler(tableAlias, false));
}
function aliasedTableColumn(column, tableAlias) {
return new Proxy(
column,
new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false)))
);
}
function mapColumnsInAliasedSQLToAlias(query, alias) {
return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);
}
function mapColumnsInSQLToAlias(query, alias) {
return sql.join(query.queryChunks.map((c) => {
if (is(c, Column)) {
return aliasedTableColumn(c, alias);
}
if (is(c, SQL)) {
return mapColumnsInSQLToAlias(c, alias);
}
if (is(c, SQL.Aliased)) {
return mapColumnsInAliasedSQLToAlias(c, alias);
}
return c;
}));
}
class DrizzleError extends Error {
static [entityKind] = "DrizzleError";
constructor({ message, cause }) {
super(message);
this.name = "DrizzleError";
this.cause = cause;
}
}
class DrizzleQueryError extends Error {
constructor(query, params, cause) {
super(`Failed query: ${query}
params: ${params}`);
this.query = query;
this.params = params;
this.cause = cause;
Error.captureStackTrace(this, DrizzleQueryError);
if (cause) this.cause = cause;
}
}
class TransactionRollbackError extends DrizzleError {
static [entityKind] = "TransactionRollbackError";
constructor() {
super({ message: "Rollback" });
}
}
class ConsoleLogWriter {
static [entityKind] = "ConsoleLogWriter";
write(message) {
console.log(message);
}
}
class DefaultLogger {
static [entityKind] = "DefaultLogger";
writer;
constructor(config) {
this.writer = config?.writer ?? new ConsoleLogWriter();
}
logQuery(query, params) {
const stringifiedParams = params.map((p) => {
try {
return JSON.stringify(p);
} catch {
return String(p);
}
});
const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : "";
this.writer.write(`Query: ${query}${paramsStr}`);
}
}
class NoopLogger {
static [entityKind] = "NoopLogger";
logQuery() {
}
}
class QueryPromise {
static [entityKind] = "QueryPromise";
[Symbol.toStringTag] = "QueryPromise";
catch(onRejected) {
return this.then(void 0, onRejected);
}
finally(onFinally) {
return this.then(
(value) => {
onFinally?.();
return value;
},
(reason) => {
onFinally?.();
throw reason;
}
);
}
then(onFulfilled, onRejected) {
return this.execute().then(onFulfilled, onRejected);
}
}
function mapResultRow(columns, row, joinsNotNullableMap) {
const nullifyMap = {};
const result = columns.reduce(
(result2, { path, field }, columnIndex) => {
let decoder;
if (is(field, Column)) {
decoder = field;
} else if (is(field, SQL)) {
decoder = field.decoder;
} else if (is(field, Subquery)) {
decoder = field._.sql.decoder;
} else {
decoder = field.sql.decoder;
}
let node = result2;
for (const [pathChunkIndex, pathChunk] of path.entries()) {
if (pathChunkIndex < path.length - 1) {
if (!(pathChunk in node)) {
node[pathChunk] = {};
}
node = node[pathChunk];
} else {
const rawValue = row[columnIndex];
const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);
if (joinsNotNullableMap && is(field, Column) && path.length === 2) {
const objectName = path[0];
if (!(objectName in nullifyMap)) {
nullifyMap[objectName] = value === null ? getTableName(field.table) : false;
} else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) {
nullifyMap[objectName] = false;
}
}
}
}
return result2;
},
{}
);
if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
for (const [objectName, tableName] of Object.entries(nullifyMap)) {
if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) {
result[objectName] = null;
}
}
}
return result;
}
function orderSelectedFields(fields, pathPrefix) {
return Object.entries(fields).reduce((result, [name, field]) => {
if (typeof name !== "string") {
return result;
}
const newPath = pathPrefix ? [...pathPrefix, name] : [name];
if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased) || is(field, Subquery)) {
result.push({ path: newPath, field });
} else if (is(field, Table)) {
result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));
} else {
result.push(...orderSelectedFields(field, newPath));
}
return result;
}, []);
}
function haveSameKeys(left, right) {
const leftKeys = Object.keys(left);
const rightKeys = Object.keys(right);
if (leftKeys.length !== rightKeys.length) {
return false;
}
for (const [index, key] of leftKeys.entries()) {
if (key !== rightKeys[index]) {
return false;
}
}
return true;
}
function mapUpdateSet(table, values) {
const entries = Object.entries(values).filter(([, value]) => value !== void 0).map(([key, value]) => {
if (is(value, SQL) || is(value, Column)) {
return [key, value];
} else {
return [key, new Param(value, table[Table.Symbol.Columns][key])];
}
});
if (entries.length === 0) {
throw new Error("No values to set");
}
return Object.fromEntries(entries);
}
function applyMixins(baseClass, extendedClasses) {
for (const extendedClass of extendedClasses) {
for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {
if (name === "constructor") continue;
Object.defineProperty(
baseClass.prototype,
name,
Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null)
);
}
}
}
function getTableColumns(table) {
return table[Table.Symbol.Columns];
}
function getTableLikeName(table) {
return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName];
}
function getColumnNameAndConfig(a, b) {
return {
name: typeof a === "string" && a.length > 0 ? a : "",
config: typeof a === "object" ? a : b
};
}
function isConfig(data) {
if (typeof data !== "object" || data === null) return false;
if (data.constructor.name !== "Object") return false;
if ("logger" in data) {
const type = typeof data["logger"];
if (type !== "boolean" && (type !== "object" || typeof data["logger"]["logQuery"] !== "function") && type !== "undefined") return false;
return true;
}
if ("schema" in data) {
const type = typeof data["schema"];
if (type !== "object" && type !== "undefined") return false;
return true;
}
if ("casing" in data) {
const type = typeof data["casing"];
if (type !== "string" && type !== "undefined") return false;
return true;
}
if ("mode" in data) {
if (data["mode"] !== "default" || data["mode"] !== "planetscale" || data["mode"] !== void 0) return false;
return true;
}
if ("connection" in data) {
const type = typeof data["connection"];
if (type !== "string" && type !== "object" && type !== "undefined") return false;
return true;
}
if ("client" in data) {
const type = typeof data["client"];
if (type !== "object" && type !== "function" && type !== "undefined") return false;
return true;
}
if (Object.keys(data).length === 0) return true;
return false;
}
typeof TextDecoder === "undefined" ? null : new TextDecoder();
class PgIntColumnBaseBuilder extends PgColumnBuilder {
static [entityKind] = "PgIntColumnBaseBuilder";
generatedAlwaysAsIdentity(sequence) {
if (sequence) {
const { name, ...options } = sequence;
this.config.generatedIdentity = {
type: "always",
sequenceName: name,
sequenceOptions: options
};
} else {
this.config.generatedIdentity = {
type: "always"
};
}
this.config.hasDefault = true;
this.config.notNull = true;
return this;
}
generatedByDefaultAsIdentity(sequence) {
if (sequence) {
const { name, ...options } = sequence;
this.config.generatedIdentity = {
type: "byDefault",
sequenceName: name,
sequenceOptions: options
};
} else {
this.config.generatedIdentity = {
type: "byDefault"
};
}
this.config.hasDefault = true;
this.config.notNull = true;
return this;
}
}
class PgBigInt53Builder extends PgIntColumnBaseBuilder {
static [entityKind] = "PgBigInt53Builder";
constructor(name) {
super(name, "number", "PgBigInt53");
}
/** @internal */
build(table) {
return new PgBigInt53(table, this.config);
}
}
class PgBigInt53 extends PgColumn {
static [entityKind] = "PgBigInt53";
getSQLType() {
return "bigint";
}
mapFromDriverValue(value) {
if (typeof value === "number") {
return value;
}
return Number(value);
}
}
class PgBigInt64Builder extends PgIntColumnBaseBuilder {
static [entityKind] = "PgBigInt64Builder";
constructor(name) {
super(name, "bigint", "PgBigInt64");
}
/** @internal */
build(table) {
return new PgBigInt64(
table,
this.config
);
}
}
class PgBigInt64 extends PgColumn {
static [entityKind] = "PgBigInt64";
getSQLType() {
return "bigint";
}
// eslint-disable-next-line unicorn/prefer-native-coercion-functions
mapFromDriverValue(value) {
return BigInt(value);
}
}
function bigint(a, b) {
const { name, config } = getColumnNameAndConfig(a, b);
if (config.mode === "number") {
return new PgBigInt53Builder(name);
}
return new PgBigInt64Builder(name);
}
class PgBigSerial53Builder extends PgColumnBuilder {
static [entityKind] = "PgBigSerial53Builder";
constructor(name) {
super(name, "number", "PgBigSerial53");
this.config.hasDefault = true;
this.config.notNull = true;
}
/** @internal */
build(table) {
return new PgBigSerial53(
table,
this.config
);
}
}
class PgBigSerial53 extends PgColumn {
static [entityKind] = "PgBigSerial53";
getSQLType() {
return "bigserial";
}
mapFromDriverValue(value) {
if (typeof value === "number") {
return value;
}
return Number(value);
}
}
class PgBigSerial64Builder extends PgColumnBuilder {
static [entityKind] = "PgBigSerial64Builder";
constructor(name) {
super(name, "bigint", "PgBigSerial64");
this.config.hasDefault = true;
}
/** @internal */
build(table) {
return new PgBigSerial64(
table,
this.config
);
}
}
class PgBigSerial64 extends PgColumn {
static [entityKind] = "PgBigSerial64";
getSQLType() {
return "bigserial";
}
// eslint-disable-next-line unicorn/prefer-native-coercion-functions
mapFromDriverValue(value) {
return BigInt(value);
}
}
function bigserial(a, b) {
const { name, config } = getColumnNameAndConfig(a, b);
if (config.mode === "number") {
return new PgBigSerial53Builder(name);
}
return new PgBigSerial64Builder(name);
}
class PgBooleanBuilder extends PgColumnBuilder {
static [entityKind] = "PgBooleanBuilder";
constructor(name) {
super(name, "boolean", "PgBoolean");
}
/** @internal */
build(table) {
return new PgBoolean(table, this.config);
}
}
class PgBoolean extends PgColumn {
static [entityKind] = "PgBoolean";
getSQLType() {
return "boolean";
}
}
function boolean(name) {
return new PgBooleanBuilder(name ?? "");
}
class PgCharBuilder extends PgColumnBuilder {
static [entityKind] = "PgCharBuilder";
constructor(name, config) {
super(name, "string", "PgChar");
this.config.length = config.length;
this.config.enumValues = config.enum;
}
/** @internal */
build(table) {
return new PgChar(
table,
this.config
);
}
}
class PgChar extends PgColumn {
static [entityKind] = "PgChar";
length = this.config.length;
enumValues = this.config.enumValues;
getSQLType() {
return this.length === void 0 ? `char` : `char(${this.length})`;
}
}
function char(a, b = {}) {
const { name, config } = getColumnNameAndConfig(a, b);
return new PgCharBuilder(name, config);
}
class PgCidrBuilder extends PgColumnBuilder {
static [entityKind] = "PgCidrBuilder";
constructor(name) {
super(name, "string", "PgCidr");
}
/** @internal */
build(table) {
return new PgCidr(table, this.config);
}
}
class PgCidr extends PgColumn {
static [entityKind] = "PgCidr";
getSQLType() {
return "cidr";
}
}
function cidr(name) {
return new PgCidrBuilder(name ?? "");
}
class PgCustomColumnBuilder extends PgColumnBuilder {
static [entityKind] = "PgCustomColumnBuilder";
constructor(name, fieldConfig, customTypeParams) {
super(name, "custom", "PgCustomColumn");
this.config.fieldConfig = fieldConfig;
this.config.customTypeParams = customTypeParams;
}
/** @internal */
build(table) {
return new PgCustomColumn(
table,
this.config
);
}
}
class PgCustomColumn extends PgColumn {
static [entityKind] = "PgCustomColumn";
sqlName;
mapTo;
mapFrom;
constructor(table, config) {
super(table, config);
this.sqlName = config.customTypeParams.dataType(config.fieldConfig);
this.mapTo = config.customTypeParams.toDriver;
this.mapFrom = config.customTypeParams.fromDriver;
}
getSQLType() {
return this.sqlName;
}
mapFromDriverValue(value) {
return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
}
mapToDriverValue(value) {
return typeof this.mapTo === "function" ? this.mapTo(value) : value;
}
}
function customType(customTypeParams) {
return (a, b) => {
const { name, config } = getColumnNameAndConfig(a, b);
return new PgCustomColumnBuilder(name, config, customTypeParams);
};
}
class PgDateColumnBaseBuilder extends PgColumnBuilder {
static [entityKind] = "PgDateColumnBaseBuilder";
defaultNow() {
return this.default(sql`now()`);
}
}
class PgDateBuilder extends PgDateColumnBaseBuilder {
static [entityKind] = "PgDateBuilder";
constructor(name) {
super(name, "date", "PgDate");
}
/** @internal */
build(table) {
return new PgDate(table, this.config);
}
}
class PgDate extends PgColumn {
static [entityKind] = "PgDate";
getSQLType() {
return "date";
}
mapFromDriverValue(value) {
if (typeof value === "string") return new Date(value);
return value;
}
mapToDriverValue(value) {
return value.toISOString();
}
}
class PgDateStringBuilder extends PgDateColumnBaseBuilder {
static [entityKind] = "PgDateStringBuilder";
constructor(name) {
super(name, "string", "PgDateString");
}
/** @internal */
build(table) {
return new PgDateString(
table,
this.config
);
}
}
class PgDateString extends PgColumn {
static [entityKind] = "PgDateString";
getSQLType() {
return "date";
}
mapFromDriverValue(value) {
if (typeof value === "string") return value;
return value.toISOString().slice(0, -14);
}
}
function date(a, b) {
const { name, config } = getColumnNameAndConfig(a, b);
if (config?.mode === "date") {
return new PgDateBuilder(name);
}
return new PgDateStringBuilder(name);
}
class PgDoublePrecisionBuilder extends PgColumnBuilder {
static [entityKind] = "PgDoublePrecisionBuilder";
constructor(name) {
super(name, "number", "PgDoublePrecision");
}
/** @internal */
build(table) {
return new PgDoublePrecision(
table,
this.config
);
}
}
class PgDoublePrecision extends PgColumn {
static [entityKind] = "PgDoublePrecision";
getSQLType() {
return "double precision";
}
mapFromDriverValue(value) {
if (typeof value === "string") {
return Number.parseFloat(value);
}
return value;
}
}
function doublePrecision(name) {
return new PgDoublePrecisionBuilder(name ?? "");
}
class PgInetBuilder extends PgColumnBuilder {
static [entityKind] = "PgInetBuilder";
constructor(name) {
super(name, "string", "PgInet");
}
/** @internal */
build(table) {
return new PgInet(table, this.config);
}
}
class PgInet extends PgColumn {
static [entityKind] = "PgInet";
getSQLType() {
return "inet";
}
}
function inet(name) {
return new PgInetBuilder(name ?? "");
}
class PgIntegerBuilder extends PgIntColumnBaseBuilder {
static [entityKind] = "PgIntegerBuilder";
constructor(name) {
super(name, "number", "PgInteger");
}
/** @internal */
build(table) {
return new PgInteger(table, this.config);
}
}
class PgInteger extends PgColumn {
static [entityKind] = "PgInteger";
getSQLType() {
return "integer";
}
mapFromDriverValue(value) {
if (typeof value === "string") {
return Number.parseInt(value);
}
return value;
}
}
function integer(name) {
return new PgIntegerBuilder(name ?? "");
}
class PgIntervalBuilder extends PgColumnBuilder {
static [entityKind] = "PgIntervalBuilder";
constructor(name, intervalConfig) {
super(name, "string", "PgInterval");
this.config.intervalConfig = intervalConfig;
}
/** @internal */
build(table) {
return new PgInterval(table, this.config);
}
}
class PgInterval extends PgColumn {
static [entityKind] = "PgInterval";
fields = this.config.intervalConfig.fields;
precision = this.config.intervalConfig.precision;
getSQLType() {
const fields = this.fields ? ` ${this.fields}` : "";
const precision = this.precision ? `(${this.precision})` : "";
return `interval${fields}${precision}`;
}
}
function interval(a, b = {}) {
const { name, config } = getColumnNameAndConfig(a, b);
return new PgIntervalBuilder(name, config);
}
class PgJsonBuilder extends PgColumnBuilder {
static [entityKind] = "PgJsonBuilder";
constructor(name) {
super(name, "json", "PgJson");
}
/** @internal */
build(table) {
return new PgJson(table, this.config);
}
}
class PgJson extends PgColumn {
static [entityKind] = "PgJson";
constructor(table, config) {
super(table, config);
}
getSQLType() {
return "json";
}
mapToDriverValue(value) {
return JSON.stringify(value);
}
mapFromDriverValue(value) {
if (typeof value === "string") {
try {
return JSON.parse(value);
} catch {
return value;
}
}
return value;
}
}
function json(name) {
return new PgJsonBuilder(name ?? "");
}
class PgJsonbBuilder extends PgColumnBuilder {
static [entityKind] = "PgJsonbBuilder";
constructor(name) {
super(name, "json", "PgJsonb");
}
/** @internal */
build(table) {
return new PgJsonb(table, this.config);
}
}
class PgJsonb extends PgColumn {
static [entityKind] = "PgJsonb";
constructor(table, config) {
super(table, config);
}
getSQLType() {
return "jsonb";
}
mapToDriverValue(value) {
return JSON.stringify(value);
}
mapFromDriverValue(value) {
if (typeof value === "string") {
try {
return JSON.parse(value);
} catch {
return value;
}
}
return value;
}
}
function jsonb(name) {
return new PgJsonbBuilder(name ?? "");
}
class PgLineBuilder extends PgColumnBuilder {
static [entityKind] = "PgLineBuilder";
constructor(name) {
super(name, "array", "PgLine");
}
/** @internal */
build(table) {
return new PgLineTuple(
table,
this.config
);
}
}
class PgLineTuple extends PgColumn {
static [entityKind] = "PgLine";
getSQLType() {
return "line";
}
mapFromDriverValue(value) {
const [a, b, c] = value.slice(1, -1).split(",");
return [Number.parseFloat(a), Number.parseFloat(b), Number.parseFloat(c)];
}
mapToDriverValue(value) {
return `{${value[0]},${value[1]},${value[2]}}`;
}
}
class PgLineABCBuilder extends PgColumnBuilder {
static [entityKind] = "PgLineABCBuilder";
constructor(name) {
super(name, "json", "PgLineABC");
}
/** @internal */
build(table) {
return new PgLineABC(
table,
this.config
);
}
}
class PgLineABC extends PgColumn {
static [entityKind] = "PgLineABC";
getSQLType() {
return "line";
}
mapFromDriverValue(value) {
const [a, b, c] = value.slice(1, -1).split(",");
return { a: Number.parseFloat(a), b: Number.parseFloat(b), c: Number.parseFloat(c) };
}
mapToDriverValue(value) {
return `{${value.a},${value.b},${value.c}}`;
}
}
function line(a, b) {
const { name, config } = getColumnNameAndConfig(a, b);
if (!config?.mode || config.mode === "tuple") {
return new PgLineBuilder(name);
}
return new PgLineABCBuilder(name);
}
class PgMacaddrBuilder extends PgColumnBuilder {
static [entityKind] = "PgMacaddrBuilder";
constructor(name) {
super(name, "string", "PgMacaddr");
}
/** @internal */
build(table) {
return new PgMacaddr(table, this.config);
}
}
class PgMacaddr extends PgColumn {
static [entityKind] = "PgMacaddr";
getSQLType() {
return "macaddr";
}
}
function macaddr(name) {
return new PgMacaddrBuilder(name ?? "");
}
class PgMacaddr8Builder extends PgColumnBuilder {
static [entityKind] = "PgMacaddr8Builder";
constructor(name) {
super(name, "string", "PgMacaddr8");
}
/** @internal */
build(table) {
return new PgMacaddr8(table, this.config);
}
}
class PgMacaddr8 extends PgColumn {
static [entityKind] = "PgMacaddr8";
getSQLType() {
return "macaddr8";
}
}
function macaddr8(name) {
return new PgMacaddr8Builder(name ?? "");
}
class PgNumericBuilder extends PgColumnBuilder {
static [entityKind] = "PgNumericBuilder";
constructor(name, precision, scale) {
super(name, "string", "PgNumeric");
this.config.precision = precision;
this.config.scale = scale;
}
/** @internal */
build(table) {
return new PgNumeric(table, this.config);
}
}
class PgNumeric extends PgColumn {
static [entityKind] = "PgNumeric";
precision;
scale;
constructor(table, config) {
super(table, config);
this.precision = config.precision;
this.scale = config.scale;
}
mapFromDriverValue(value) {
if (typeof value === "string") return value;
return String(value);
}
getSQLType() {
if (this.precision !== void 0 && this.scale !== void 0) {
return `numeric(${this.precision}, ${this.scale})`;
} else if (this.precision === void 0) {
return "numeric";
} else {
return `numeric(${this.precision})`;
}
}
}
class PgNumericNumberBuilder extends PgColumnBuilder {
static [entityKind] = "PgNumericNumberBuilder";
constructor(name, precision, scale) {
super(name, "number", "PgNumericNumber");
this.config.precision = precision;
this.config.scale = scale;
}
/** @internal */
build(table) {
return new PgNumericNumber(
table,
this.config
);
}
}
class PgNumericNumber extends PgColumn {
static [entityKind] = "PgNumericNumber";
precision;
scale;
constructor(table, config) {
super(table, config);
this.precision = config.precision;
this.scale = config.scale;
}
mapFromDriverValue(value) {
if (typeof value === "number") return value;
return Number(value);
}
mapToDriverValue = String;
getSQLType() {
if (this.precision !== void 0 && this.scale !== void 0) {
return `numeric(${this.precision}, ${this.scale})`;
} else if (this.precision === void 0) {
return "numeric";
} else {
return `numeric(${this.precision})`;
}
}
}
class PgNumericBigIntBuilder extends PgColumnBuilder {
static [entityKind] = "PgNumericBigIntBuilder";
constructor(name, precision, scale) {
super(name, "bigint", "PgNumericBigInt");
this.config.precision = precision;
this.config.scale = scale;
}
/** @internal */
build(table) {
return new PgNumericBigInt(
table,
this.config
);
}
}
class PgNumericBigInt extends PgColumn {
static [entityKind] = "PgNumericBigInt";
precision;
scale;
constructor(table, config) {
super(table, config);
this.precision = config.precision;
this.scale = config.scale;
}
mapFromDriverValue = BigInt;
mapToDriverValue = String;
getSQLType() {
if (this.precision !== void 0 && this.scale !== void 0) {
return `numeric(${this.precision}, ${this.scale})`;
} else if (this.precision === void 0) {
return "numeric";
} else {
return `numeric(${this.precision})`;
}
}
}
function numeric(a, b) {
const { name, config } = getColumnNameAndConfig(a, b);
const mode = config?.mode;
return mode === "number" ? new PgNumericNumberBuilder(name, config?.precision, config?.scale) : mode === "bigint" ? new PgNumericBigIntBuilder(name, config?.precision, config?.scale) : new PgNumericBuilder(name, config?.precision, config?.scale);
}
class PgPointTupleBuilder extends PgColumnBuilder {
static [entityKind] = "PgPointTupleBuilder";
constructor(name) {
super(name, "array", "PgPointTuple");
}
/** @internal */
build(table) {
return new PgPointTuple(
table,
this.config
);
}
}
class PgPointTuple extends PgColumn {
static [entityKind] = "PgPointTuple";
getSQLType() {
return "point";
}
mapFromDriverValue(value) {
if (typeof value === "string") {
const [x, y] = value.slice(1, -1).split(",");
return [Number.parseFloat(x), Number.parseFloat(y)];
}
return [value.x, value.y];
}
mapToDriverValue(value) {
return `(${value[0]},${value[1]})`;
}
}
class PgPointObjectBuilder extends PgColumnBuilder {
static [entityKind] = "PgPointObjectBuilder";
constructor(name) {
super(name, "json", "PgPointObject");
}
/** @internal */
build(table) {
return new PgPointObject(
table,
this.config
);
}
}
class PgPointObject extends PgColumn {
static [entityKind] = "PgPointObject";
getSQLType() {
return "point";
}
mapFromDriverValue(value) {
if (typeof value === "string") {
const [x, y] = value.slice(1, -1).split(",");
return { x: Number.parseFloat(x), y: Number.parseFloat(y) };
}
return value;
}
mapToDriverValue(value) {
return `(${value.x},${value.y})`;
}
}
function point(a, b) {
const { name, config } = getColumnNameAndConfig(a, b);
if (!config?.mode || config.mode === "tuple") {
return new PgPointTupleBuilder(name);
}
return new PgPointObjectBuilder(name);
}
function hexToBytes(hex) {
const bytes = [];
for (let c = 0; c < hex.length; c += 2) {
bytes.push(Number.parseInt(hex.slice(c, c + 2), 16));
}
return new Uint8Array(bytes);
}
function bytesToFloat64(bytes, offset) {
const buffer = new ArrayBuffer(8);
const view = new DataView(buffer);
for (let i = 0; i < 8; i++) {
view.setUint8(i, bytes[offset + i]);
}
return view.getFloat64(0, true);
}
function parseEWKB(hex) {
const bytes = hexToBytes(hex);
let offset = 0;
const byteOrder = bytes[offset];
offset += 1;
const view = new DataView(bytes.buffer);
const geomType = view.getUint32(offset, byteOrder === 1);
offset += 4;
if (geomType & 536870912) {
view.getUint32(offset, byteOrder === 1);
offset += 4;
}
if ((geomType & 65535) === 1) {
const x = bytesToFloat64(bytes, offset);
offset += 8;
const y = bytesToFloat64(bytes, offset);
offset += 8;
return [x, y];
}
throw new Error("Unsupported geometry type");
}
class PgGeometryBuilder extends PgColumnBuilder {
static [entityKind] = "PgGeometryBuilder";
constructor(name) {
super(name, "array", "PgGeometry");
}
/** @internal */
build(table) {
return new PgGeometry(
table,
this.config
);
}
}
class PgGeometry extends PgColumn {
static [entityKind] = "PgGeometry";
getSQLType() {
return "geometry(point)";
}
mapFromDriverValue(value) {
return parseEWKB(value);
}
mapToDriverValue(value) {
return `point(${value[0]} ${value[1]})`;
}
}
class PgGeometryObjectBuilder extends PgColumnBuilder {
static [entityKind] = "PgGeometryObjectBuilder";
constructor(name) {
super(name, "json", "PgGeometryObject");
}
/** @internal */
build(table) {
return new PgGeometryObject(
table,
this.config
);
}
}
class PgGeometryObject extends PgColumn {
static [entityKind] = "PgGeometryObject";
getSQLType() {
return "geometry(point)";
}
mapFromDriverValue(value) {
const parsed = parseEWKB(value);
return { x: parsed[0], y: parsed[1] };
}
mapToDriverValue(value) {
return `point(${value.x} ${value.y})`;
}
}
function geometry(a, b) {
const { name, config } = getColumnNameAndConfig(a, b);
if (!config?.mode || config.mode === "tuple") {
return new PgGeometryBuilder(name);
}
return new PgGeometryObjectBuilder(name);
}
class PgRealBuilder extends PgColumnBuilder {
static [entityKind] = "PgRealBuilder";
constructor(name, length) {
super(name, "number", "PgReal");
this.config.length = length;
}
/** @internal */
build(table) {
return new PgReal(table, this.config);
}
}
class PgReal extends PgColumn {
static [entityKind] = "PgReal";
constructor(table, config) {
super(table, config);
}
getSQLType() {
return "real";
}
mapFromDriverValue = (value) => {
if (typeof value === "string") {
return Number.parseFloat(value);
}
return value;
};
}
function real(name) {
return new PgRealBuilder(name ?? "");
}
class PgSerialBuilder extends PgColumnBuilder {
static [entityKind] = "PgSerialBuilder";
constructor(name) {
super(name, "number", "PgSerial");
this.config.hasDefault = true;
this.config.notNull = true;
}
/** @internal */
build(table) {
return new PgSerial(table, this.config);
}
}
class PgSerial extends PgColumn {
static [entityKind] = "PgSerial";
getSQLType() {
return "serial";
}
}
function serial(name) {
return new PgSerialBuilder(name ?? "");
}
class PgSmallIntBuilder extends PgIntColumnBaseBuilder {
static [entityKind] = "PgSmallIntBuilder";
constructor(name) {
super(name, "number", "PgSmallInt");
}
/** @internal */
build(table) {
return new PgSmallInt(table, this.config);
}
}
class PgSmallInt extends PgColumn {
static [entityKind] = "PgSmallInt";
getSQLType() {
return "smallint";
}
mapFromDriverValue = (value) => {
if (typeof value === "string") {
return Number(value);
}
return value;
};
}
function smallint(name) {
return new PgSmallIntBuilder(name ?? "");
}
class PgSmallSerialBuilder extends PgColumnBuilder {
static [entityKind] = "PgSmallSerialBuilder";
constructor(name) {
super(name, "number", "PgSmallSerial");
this.config.hasDefault = true;
this.config.notNull = true;
}
/** @internal */
build(table) {
return new PgSmallSerial(
table,
this.config
);
}
}
class PgSmallSerial extends PgColumn {
static [entityKind] = "PgSmallSerial";
getSQLType() {
return "smallserial";
}
}
function smallserial(name) {
return new PgSmallSerialBuilder(name ?? "");
}
class PgTextBuilder extends PgColumnBuilder {
static [entityKind] = "PgTextBuilder";
constructor(name, config) {
super(name, "string", "PgText");
this.config.enumValues = config.enum;
}
/** @internal */
build(table) {
return new PgText(table, this.config);
}
}
class PgText extends PgColumn {
static [entityKind] = "PgText";
enumValues = this.config.enumValues;
getSQLType() {
return "text";
}
}
function text(a, b = {}) {
const { name, config } = getColumnNameAndConfig(a, b);
return new PgTextBuilder(name, config);
}
class PgTimeBuilder extends PgDateColumnBaseBuilder {
constructor(name, withTimezone, precision) {
super(name, "string", "PgTime");
this.withTimezone = withTimezone;
this.precision = precision;
this.config.withTimezone = withTimezone;
this.config.precision = precision;
}
static [entityKind] = "PgTimeBuilder";
/** @internal */
build(table) {
return new PgTime(table, this.config);
}
}
class PgTime extends PgColumn {
static [entityKind] = "PgTime";
withTimezone;
precision;
constructor(table, config) {
super(table, config);
this.withTimezone = config.withTimezone;
this.precision = config.precision;
}
getSQLType() {
const precision = this.precision === void 0 ? "" : `(${this.precision})`;
return `time${precision}${this.withTimezone ? " with time zone" : ""}`;
}
}
function time(a, b = {}) {
const { name, config } = getColumnNameAndConfig(a, b);
return new PgTimeBuilder(name, config.withTimezone ?? false, config.precision);
}
class PgTimestampBuilder extends PgDateColumnBaseBuilder {
static [entityKind] = "PgTimestampBuilder";
constructor(name, withTimezone, precision) {
super(name, "date", "PgTimestamp");
this.config.withTimezone = withTimezone;
this.config.precision = precision;
}
/** @internal */
build(table) {
return new PgTimestamp(table, this.config);
}
}
class PgTimestamp extends PgColumn {
static [entityKind] = "PgTimestamp";
withTimezone;
precision;
constructor(table, config) {
super(table, config);
this.withTimezone = config.withTimezone;
this.precision = config.precision;
}
getSQLType() {
const precision = this.precision === void 0 ? "" : ` (${this.precision})`;
return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`;
}
mapFromDriverValue(value) {
if (typeof value === "string") return new Date(this.withTimezone ? value : value + "+0000");
return value;
}
mapToDriverValue = (value) => {
return value.toISOString();
};
}
class PgTimestampStringBuilder extends PgDateColumnBaseBuilder {
static [entityKind] = "PgTimestampStringBuilder";
constructor(name, withTimezone, precision) {
super(name, "string", "PgTimestampString");
this.config.withTimezone = withTimezone;
this.config.precision = precision;
}
/** @internal */
build(table) {
return new PgTimestampString(
table,
this.config
);
}
}
class PgTimestampString extends PgColumn {
static [entityKind] = "PgTimestampString";
withTimezone;
precision;
constructor(table, config) {
super(table, config);
this.withTimezone = config.withTimezone;
this.precision = config.precision;
}
getSQLType() {
const precision = this.precision === void 0 ? "" : `(${this.precision})`;
return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`;
}
mapFromDriverValue(value) {
if (typeof value === "string") return value;
const shortened = value.toISOString().slice(0, -1).replace("T", " ");
if (this.withTimezone) {
const offset = value.getTimezoneOffset();
const sign = offset <= 0 ? "+" : "-";
return `${shortened}${sign}${Math.floor(Math.abs(offset) / 60).toString().padStart(2, "0")}`;
}
return shortened;
}
}
function timestamp(a, b = {}) {
const { name, config } = getColumnNameAndConfig(a, b);
if (config?.mode === "string") {
return new PgTimestampStringBuilder(name, config.withTimezone ?? false, config.precision);
}
return new PgTimestampBuilder(name, config?.withTimezone ?? false, config?.precision);
}
class PgUUIDBuilder extends PgColumnBuilder {
static [entityKind] = "PgUUIDBuilder";
constructor(name) {
super(name, "string", "PgUUID");
}
/**
* Adds `default gen_random_uuid()` to the column definition.
*/
defaultRandom() {
return this.default(sql`gen_random_uuid()`);
}
/** @internal */
build(table) {
return new PgUUID(table, this.config);
}
}
class PgUUID extends PgColumn {
static [entityKind] = "PgUUID";
getSQLType() {
return "uuid";
}
}
function uuid(name) {
return new PgUUIDBuilder(name ?? "");
}
class PgVarcharBuilder extends PgColumnBuilder {
static [entityKind] = "PgVarcharBuilder";
constructor(name, config) {
super(name, "string", "PgVarchar");
this.config.length = config.length;
this.config.enumValues = config.enum;
}
/** @internal */
build(table) {
return new PgVarchar(
table,
this.config
);
}
}
class PgVarchar extends PgColumn {
static [entityKind] = "PgVarchar";
length = this.config.length;
enumValues = this.config.enumValues;
getSQLType() {
return this.length === void 0 ? `varchar` : `varchar(${this.length})`;
}
}
function varchar(a, b = {}) {
const { name, config } = getColumnNameAndConfig(a, b);
return new PgVarcharBuilder(name, config);
}
class PgBinaryVectorBuilder extends PgColumnBuilder {
static [entityKind] = "PgBinaryVectorBuilder";
constructor(name, config) {
super(name, "string", "PgBinaryVector");
this.config.dimensions = config.dimensions;
}
/** @internal */
build(table) {
return new PgBinaryVector(
table,
this.config
);
}
}
class PgBinaryVector extends PgColumn {
static [entityKind] = "PgBinaryVector";
dimensions = this.config.dimensions;
getSQLType() {
return `bit(${this.dimensions})`;
}
}
function bit(a, b) {
const { name, config } = getColumnNameAndConfig(a, b);
return new PgBinaryVectorBuilder(name, config);
}
class PgHalfVectorBuilder extends PgColumnBuilder {
static [entityKind] = "PgHalfVectorBuilder";
constructor(name, config) {
super(name, "array", "PgHalfVector");
this.config.dimensions = config.dimensions;
}
/** @internal */
build(table) {
return new PgHalfVector(
table,
this.config
);
}
}
class PgHalfVector extends PgColumn {
static [entityKind] = "PgHalfVector";
dimensions = this.config.dimensions;
getSQLType() {
return `halfvec(${this.dimensions})`;
}
mapToDriverValue(value) {
return JSON.stringify(value);
}
mapFromDriverValue(value) {
return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v));
}
}
function halfvec(a, b) {
const { name, config } = getColumnNameAndConfig(a, b);
return new PgHalfVectorBuilder(name, config);
}
class PgSparseVectorBuilder extends PgColumnBuilder {
static [entityKind] = "PgSparseVectorBuilder";
constructor(name, config) {
super(name, "string", "PgSparseVector");
this.config.dimensions = config.dimensions;
}
/** @internal */
build(table) {
return new PgSparseVector(
table,
this.config
);
}
}
class PgSparseVector extends PgColumn {
static [entityKind] = "PgSparseVector";
dimensions = this.config.dimensions;
getSQLType() {
return `sparsevec(${this.dimensions})`;
}
}
function sparsevec(a, b) {
const { name, config } = getColumnNameAndConfig(a, b);
return new PgSparseVectorBuilder(name, config);
}
class PgVectorBuilder extends PgColumnBuilder {
static [entityKind] = "PgVectorBuilder";
constructor(name, config) {
super(name, "array", "PgVector");
this.config.dimensions = config.dimensions;
}
/** @internal */
build(table) {
return new PgVector(
table,
this.config
);
}
}
class PgVector extends PgColumn {
static [entityKind] = "PgVector";
dimensions = this.config.dimensions;
getSQLType() {
return `vector(${this.dimensions})`;
}
mapToDriverValue(value) {
return JSON.stringify(value);
}
mapFromDriverValue(value) {
return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v));
}
}
function vector(a, b) {
const { name, config } = getColumnNameAndConfig(a, b);
return new PgVectorBuilder(name, config);
}
function getPgColumnBuilders() {
return {
bigint,
bigserial,
boolean,
char,
cidr,
customType,
date,
doublePrecision,
inet,
integer,
interval,
json,
jsonb,
line,
macaddr,
macaddr8,
numeric,
point,
geometry,
real,
serial,
smallint,
smallserial,
text,
time,
timestamp,
uuid,
varchar,
bit,
halfvec,
sparsevec,
vector
};
}
const InlineForeignKeys = Symbol.for("drizzle:PgInlineForeignKeys");
const EnableRLS = Symbol.for("drizzle:EnableRLS");
class PgTable extends Table {
static [entityKind] = "PgTable";
/** @internal */
static Symbol = Object.assign({}, Table.Symbol, {
InlineForeignKeys,
EnableRLS
});
/**@internal */
[InlineForeignKeys] = [];
/** @internal */
[EnableRLS] = false;
/** @internal */
[Table.Symbol.ExtraConfigBuilder] = void 0;
/** @internal */
[Table.Symbol.ExtraConfigColumns] = {};
}
function pgTableWithSchema(name, columns, extraConfig, schema, baseName = name) {
const rawTable = new PgTable(name, schema, baseName);
const parsedColumns = typeof columns === "function" ? columns(getPgColumnBuilders()) : columns;
const builtColumns = Object.fromEntries(
Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {
const colBuilder = colBuilderBase;
colBuilder.setName(name2);
const column = colBuilder.build(rawTable);
rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));
return [name2, column];
})
);
const builtColumnsForExtraConfig = Object.fromEntries(
Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {
const colBuilder = colBuilderBase;
colBuilder.setName(name2);
const column = colBuilder.buildExtraConfigColumn(rawTable);
return [name2, column];
})
);
const table = Object.assign(rawTable, builtColumns);
table[Table.Symbol.Columns] = builtColumns;
table[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig;
if (extraConfig) {
table[PgTable.Symbol.ExtraConfigBuilder] = extraConfig;
}
return Object.assign(table, {
enableRLS: () => {
table[PgTable.Symbol.EnableRLS] = true;
return table;
}
});
}
const pgTable = (name, columns, extraConfig) => {
return pgTableWithSchema(name, columns, extraConfig, void 0);
};
class PrimaryKeyBuilder {
static [entityKind] = "PgPrimaryKeyBuilder";
/** @internal */
columns;
/** @internal */
name;
constructor(columns, name) {
this.columns = columns;
this.name = name;
}
/** @internal */
build(table) {
return new PrimaryKey(table, this.columns, this.name);
}
}
class PrimaryKey {
constructor(table, columns, name) {
this.table = table;
this.columns = columns;
this.name = name;
}
static [entityKind] = "PgPrimaryKey";
columns;
name;
getName() {
return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
}
}
function bindIfParam(value, column) {
if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
return new Param(value, column);
}
return value;
}
const eq = (left, right) => {
return sql`${left} = ${bindIfParam(right, left)}`;
};
const ne = (left, right) => {
return sql`${left} <> ${bindIfParam(right, left)}`;
};
function and(...unfilteredConditions) {
const conditions = unfilteredConditions.filter(
(c) => c !== void 0
);
if (conditions.length === 0) {
return void 0;
}
if (conditions.length === 1) {
return new SQL(conditions);
}
return new SQL([
new StringChunk("("),
sql.join(conditions, new StringChunk(" and ")),
new StringChunk(")")
]);
}
function or(...unfilteredConditions) {
const conditions = unfilteredConditions.filter(
(c) => c !== void 0
);
if (conditions.length === 0) {
return void 0;
}
if (conditions.length === 1) {
return new SQL(conditions);
}
return new SQL([
new StringChunk("("),
sql.join(conditions, new StringChunk(" or ")),
new StringChunk(")")
]);
}
function not(condition) {
return sql`not ${condition}`;
}
const gt = (left, right) => {
return sql`${left} > ${bindIfParam(right, left)}`;
};
const gte = (left, right) => {
return sql`${left} >= ${bindIfParam(right, left)}`;
};
const lt = (left, right) => {
return sql`${left} < ${bindIfParam(right, left)}`;
};
const lte = (left, right) => {
return sql`${left} <= ${bindIfParam(right, left)}`;
};
function inArray(column, values) {
if (Array.isArray(values)) {
if (values.length === 0) {
return sql`false`;
}
return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;
}
return sql`${column} in ${bindIfParam(values, column)}`;
}
function notInArray(column, values) {
if (Array.isArray(values)) {
if (values.length === 0) {
return sql`true`;
}
return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;
}
return sql`${column} not in ${bindIfParam(values, column)}`;
}
function isNull(value) {
return sql`${value} is null`;
}
function isNotNull(value) {
return sql`${value} is not null`;
}
function exists(subquery) {
return sql`exists ${subquery}`;
}
function notExists(subquery) {
return sql`not exists ${subquery}`;
}
function between(column, min, max) {
return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(
max,
column
)}`;
}
function notBetween(column, min, max) {
return sql`${column} not between ${bindIfParam(
min,
column
)} and ${bindIfParam(max, column)}`;
}
function like(column, value) {
return sql`${column} like ${value}`;
}
function notLike(column, value) {
return sql`${column} not like ${value}`;
}
function ilike(column, value) {
return sql`${column} ilike ${value}`;
}
function notIlike(column, value) {
return sql`${column} not ilike ${value}`;
}
function asc(column) {
return sql`${column} asc`;
}
function desc(column) {
return sql`${column} desc`;
}
class Relation {
constructor(sourceTable, referencedTable, relationName) {
this.sourceTable = sourceTable;
this.referencedTable = referencedTable;
this.relationName = relationName;
this.referencedTableName = referencedTable[Table.Symbol.Name];
}
static [entityKind] = "Relation";
referencedTableName;
fieldName;
}
class Relations {
constructor(table, config) {
this.table = table;
this.config = config;
}
static [entityKind] = "Relations";
}
class One extends Relation {
constructor(sourceTable, referencedTable, config, isNullable) {
super(sourceTable, referencedTable, config?.relationName);
this.config = config;
this.isNullable = isNullable;
}
static [entityKind] = "One";
withFieldName(fieldName) {
const relation = new One(
this.sourceTable,
this.referencedTable,
this.config,
this.isNullable
);
relation.fieldName = fieldName;
return relation;
}
}
class Many extends Relation {
constructor(sourceTable, referencedTable, config) {
super(sourceTable, referencedTable, config?.relationName);
this.config = config;
}
static [entityKind] = "Many";
withFieldName(fieldName) {
const relation = new Many(
this.sourceTable,
this.referencedTable,
this.config
);
relation.fieldName = fieldName;
return relation;
}
}
function getOperators() {
return {
and,
between,
eq,
exists,
gt,
gte,
ilike,
inArray,
isNull,
isNotNull,
like,
lt,
lte,
ne,
not,
notBetween,
notExists,
notLike,
notIlike,
notInArray,
or,
sql
};
}
function getOrderByOperators() {
return {
sql,
asc,
desc
};
}
function extractTablesRelationalConfig(schema, configHelpers) {
if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) {
schema = schema["default"];
}
const tableNamesMap = {};
const relationsBuffer = {};
const tablesConfig = {};
for (const [key, value] of Object.entries(schema)) {
if (is(value, Table)) {
const dbName = getTableUniqueName(value);
const bufferedRelations = relationsBuffer[dbName];
tableNamesMap[dbName] = key;
tablesConfig[key] = {
tsName: key,
dbName: value[Table.Symbol.Name],
schema: value[Table.Symbol.Schema],
columns: value[Table.Symbol.Columns],
relations: bufferedRelations?.relations ?? {},
primaryKey: bufferedRelations?.primaryKey ?? []
};
for (const column of Object.values(
value[Table.Symbol.Columns]
)) {
if (column.primary) {
tablesConfig[key].primaryKey.push(column);
}
}
const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]);
if (extraConfig) {
for (const configEntry of Object.values(extraConfig)) {
if (is(configEntry, PrimaryKeyBuilder)) {
tablesConfig[key].primaryKey.push(...configEntry.columns);
}
}
}
} else if (is(value, Relations)) {
const dbName = getTableUniqueName(value.table);
const tableName = tableNamesMap[dbName];
const relations2 = value.config(
configHelpers(value.table)
);
let primaryKey;
for (const [relationName, relation] of Object.entries(relations2)) {
if (tableName) {
const tableConfig = tablesConfig[tableName];
tableConfig.relations[relationName] = relation;
} else {
if (!(dbName in relationsBuffer)) {
relationsBuffer[dbName] = {
relations: {},
primaryKey
};
}
relationsBuffer[dbName].relations[relationName] = relation;
}
}
}
}
return { tables: tablesConfig, tableNamesMap };
}
function relations(table, relations2) {
return new Relations(
table,
(helpers) => Object.fromEntries(
Object.entries(relations2(helpers)).map(([key, value]) => [
key,
value.withFieldName(key)
])
)
);
}
function createOne(sourceTable) {
return function one(table, config) {
return new One(
sourceTable,
table,
config,
config?.fields.reduce((res, f) => res && f.notNull, true) ?? false
);
};
}
function createMany(sourceTable) {
return function many(referencedTable, config) {
return new Many(sourceTable, referencedTable, config);
};
}
function normalizeRelation(schema, tableNamesMap, relation) {
if (is(relation, One) && relation.config) {
return {
fields: relation.config.fields,
references: relation.config.references
};
}
const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
if (!referencedTableTsName) {
throw new Error(
`Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema`
);
}
const referencedTableConfig = schema[referencedTableTsName];
if (!referencedTableConfig) {
throw new Error(`Table "${referencedTableTsName}" not found in schema`);
}
const sourceTable = relation.sourceTable;
const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];
if (!sourceTableTsName) {
throw new Error(
`Table "${sourceTable[Table.Symbol.Name]}" not found in schema`
);
}
const reverseRelations = [];
for (const referencedTableRelation of Object.values(
referencedTableConfig.relations
)) {
if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) {
reverseRelations.push(referencedTableRelation);
}
}
if (reverseRelations.length > 1) {
throw relation.relationName ? new Error(
`There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`
) : new Error(
`There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name`
);
}
if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) {
return {
fields: reverseRelations[0].config.references,
references: reverseRelations[0].config.fields
};
}
throw new Error(
`There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`
);
}
function createTableRelationsHelpers(sourceTable) {
return {
one: createOne(sourceTable),
many: createMany(sourceTable)
};
}
function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) {
const result = {};
for (const [
selectionItemIndex,
selectionItem
] of buildQueryResultSelection.entries()) {
if (selectionItem.isJson) {
const relation = tableConfig.relations[selectionItem.tsKey];
const rawSubRows = row[selectionItemIndex];
const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;
result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow(
tablesConfig,
tablesConfig[selectionItem.relationTableTsKey],
subRows,
selectionItem.selection,
mapColumnValue
) : subRows.map(
(subRow) => mapRelationalRow(
tablesConfig,
tablesConfig[selectionItem.relationTableTsKey],
subRow,
selectionItem.selection,
mapColumnValue
)
);
} else {
const value = mapColumnValue(row[selectionItemIndex]);
const field = selectionItem.field;
let decoder;
if (is(field, Column)) {
decoder = field;
} else if (is(field, SQL)) {
decoder = field.decoder;
} else {
decoder = field.sql.decoder;
}
result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);
}
}
return result;
}
class SelectionProxyHandler {
static [entityKind] = "SelectionProxyHandler";
config;
constructor(config) {
this.config = { ...config };
}
get(subquery, prop) {
if (prop === "_") {
return {
...subquery["_"],
selectedFields: new Proxy(
subquery._.selectedFields,
this
)
};
}
if (prop === ViewBaseConfig) {
return {
...subquery[ViewBaseConfig],
selectedFields: new Proxy(
subquery[ViewBaseConfig].selectedFields,
this
)
};
}
if (typeof prop === "symbol") {
return subquery[prop];
}
const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery;
const value = columns[prop];
if (is(value, SQL.Aliased)) {
if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) {
return value.sql;
}
const newValue = value.clone();
newValue.isSelectionField = true;
return newValue;
}
if (is(value, SQL)) {
if (this.config.sqlBehavior === "sql") {
return value;
}
throw new Error(
`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`
);
}
if (is(value, Column)) {
if (this.config.alias) {
return new Proxy(
value,
new ColumnAliasProxyHandler(
new Proxy(
value.table,
new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false)
)
)
);
}
return value;
}
if (typeof value !== "object" || value === null) {
return value;
}
return new Proxy(value, new SelectionProxyHandler(this.config));
}
}
class IndexBuilderOn {
constructor(unique, name) {
this.unique = unique;
this.name = name;
}
static [entityKind] = "PgIndexBuilderOn";
on(...columns) {
return new IndexBuilder(
columns.map((it) => {
if (is(it, SQL)) {
return it;
}
it = it;
const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));
return clonedIndexedColumn;
}),
this.unique,
false,
this.name
);
}
onOnly(...columns) {
return new IndexBuilder(
columns.map((it) => {
if (is(it, SQL)) {
return it;
}
it = it;
const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
it.indexConfig = it.defaultConfig;
return clonedIndexedColumn;
}),
this.unique,
true,
this.name
);
}
/**
* Specify what index method to use. Choices are `btree`, `hash`, `gist`, `spgist`, `gin`, `brin`, or user-installed access methods like `bloom`. The default method is `btree.
*
* If you have the `pg_vector` extension installed in your database, you can use the `hnsw` and `ivfflat` options, which are predefined types.
*
* **You can always specify any string you want in the method, in case Drizzle doesn't have it natively in its types**
*
* @param method The name of the index method to be used
* @param columns
* @returns
*/
using(method, ...columns) {
return new IndexBuilder(
columns.map((it) => {
if (is(it, SQL)) {
return it;
}
it = it;
const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));
return clonedIndexedColumn;
}),
this.unique,
true,
this.name,
method
);
}
}
class IndexBuilder {
static [entityKind] = "PgIndexBuilder";
/** @internal */
config;
constructor(columns, unique, only, name, method = "btree") {
this.config = {
name,
columns,
unique,
only,
method
};
}
concurrently() {
this.config.concurrently = true;
return this;
}
with(obj) {
this.config.with = obj;
return this;
}
where(condition) {
this.config.where = condition;
return this;
}
/** @internal */
build(table) {
return new Index(this.config, table);
}
}
class Index {
static [entityKind] = "PgIndex";
config;
constructor(config, table) {
this.config = { ...config, table };
}
}
function index(name) {
return new IndexBuilderOn(false, name);
}
function uniqueIndex(name) {
return new IndexBuilderOn(true, name);
}
function toSnakeCase(input) {
const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
return words.map((word) => word.toLowerCase()).join("_");
}
function toCamelCase(input) {
const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
return words.reduce((acc, word, i) => {
const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`;
return acc + formattedWord;
}, "");
}
function noopCase(input) {
return input;
}
class CasingCache {
static [entityKind] = "CasingCache";
/** @internal */
cache = {};
cachedTables = {};
convert;
constructor(casing) {
this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase;
}
getColumnCasing(column) {
if (!column.keyAsName) return column.name;
const schema = column.table[Table.Symbol.Schema] ?? "public";
const tableName = column.table[Table.Symbol.OriginalName];
const key = `${schema}.${tableName}.${column.name}`;
if (!this.cache[key]) {
this.cacheTable(column.table);
}
return this.cache[key];
}
cacheTable(table) {
const schema = table[Table.Symbol.Schema] ?? "public";
const tableName = table[Table.Symbol.OriginalName];
const tableKey = `${schema}.${tableName}`;
if (!this.cachedTables[tableKey]) {
for (const column of Object.values(table[Table.Symbol.Columns])) {
const columnKey = `${tableKey}.${column.name}`;
this.cache[columnKey] = this.convert(column.name);
}
this.cachedTables[tableKey] = true;
}
}
clearCache() {
this.cache = {};
this.cachedTables = {};
}
}
class PgViewBase extends View {
static [entityKind] = "PgViewBase";
}
class PgDialect {
static [entityKind] = "PgDialect";
/** @internal */
casing;
constructor(config) {
this.casing = new CasingCache(config?.casing);
}
async migrate(migrations, session, config) {
const migrationsTable = typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
const migrationsSchema = typeof config === "string" ? "drizzle" : config.migrationsSchema ?? "drizzle";
const migrationTableCreate = sql`
CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} (
id SERIAL PRIMARY KEY,
hash text NOT NULL,
created_at bigint
)
`;
await session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`);
await session.execute(migrationTableCreate);
const dbMigrations = await session.all(
sql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} order by created_at desc limit 1`
);
const lastDbMigration = dbMigrations[0];
await session.transaction(async (tx) => {
for await (const migration of migrations) {
if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
for (const stmt of migration.sql) {
await tx.execute(sql.raw(stmt));
}
await tx.execute(
sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`
);
}
}
});
}
escapeName(name) {
return `"${name}"`;
}
escapeParam(num) {
return `$${num + 1}`;
}
escapeString(str) {
return `'${str.replace(/'/g, "''")}'`;
}
buildWithCTE(queries) {
if (!queries?.length) return void 0;
const withSqlChunks = [sql`with `];
for (const [i, w] of queries.entries()) {
withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
if (i < queries.length - 1) {
withSqlChunks.push(sql`, `);
}
}
withSqlChunks.push(sql` `);
return sql.join(withSqlChunks);
}
buildDeleteQuery({ table, where, returning, withList }) {
const withSql = this.buildWithCTE(withList);
const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
const whereSql = where ? sql` where ${where}` : void 0;
return sql`${withSql}delete from ${table}${whereSql}${returningSql}`;
}
buildUpdateSet(table, set) {
const tableColumns = table[Table.Symbol.Columns];
const columnNames = Object.keys(tableColumns).filter(
(colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
);
const setSize = columnNames.length;
return sql.join(columnNames.flatMap((colName, i) => {
const col = tableColumns[colName];
const onUpdateFnResult = col.onUpdateFn?.();
const value = set[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col));
const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
if (i < setSize - 1) {
return [res, sql.raw(", ")];
}
return [res];
}));
}
buildUpdateQuery({ table, set, where, returning, withList, from, joins }) {
const withSql = this.buildWithCTE(withList);
const tableName = table[PgTable.Symbol.Name];
const tableSchema = table[PgTable.Symbol.Schema];
const origTableName = table[PgTable.Symbol.OriginalName];
const alias = tableName === origTableName ? void 0 : tableName;
const tableSql = sql`${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}`;
const setSql = this.buildUpdateSet(table, set);
const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
const joinsSql = this.buildJoins(joins);
const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : void 0;
const whereSql = where ? sql` where ${where}` : void 0;
return sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`;
}
/**
* Builds selection SQL with provided fields/expressions
*
* Examples:
*
* `select <selection> from`
*
* `insert ... returning <selection>`
*
* If `isSingleTable` is true, then columns won't be prefixed with table name
*/
buildSelection(fields, { isSingleTable = false } = {}) {
const columnsLen = fields.length;
const chunks = fields.flatMap(({ field }, i) => {
const chunk = [];
if (is(field, SQL.Aliased) && field.isSelectionField) {
chunk.push(sql.identifier(field.fieldAlias));
} else if (is(field, SQL.Aliased) || is(field, SQL)) {
const query = is(field, SQL.Aliased) ? field.sql : field;
if (isSingleTable) {
chunk.push(
new SQL(
query.queryChunks.map((c) => {
if (is(c, PgColumn)) {
return sql.identifier(this.casing.getColumnCasing(c));
}
return c;
})
)
);
} else {
chunk.push(query);
}
if (is(field, SQL.Aliased)) {
chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
}
} else if (is(field, Column)) {
if (isSingleTable) {
chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
} else {
chunk.push(field);
}
} else if (is(field, Subquery)) {
const entries = Object.entries(field._.selectedFields);
if (entries.length === 1) {
const entry = entries[0][1];
const fieldDecoder = is(entry, SQL) ? entry.decoder : is(entry, Column) ? { mapFromDriverValue: (v) => entry.mapFromDriverValue(v) } : entry.sql.decoder;
if (fieldDecoder) {
field._.sql.decoder = fieldDecoder;
}
}
chunk.push(field);
}
if (i < columnsLen - 1) {
chunk.push(sql`, `);
}
return chunk;
});
return sql.join(chunks);
}
buildJoins(joins) {
if (!joins || joins.length === 0) {
return void 0;
}
const joinsArray = [];
for (const [index, joinMeta] of joins.entries()) {
if (index === 0) {
joinsArray.push(sql` `);
}
const table = joinMeta.table;
const lateralSql = joinMeta.lateral ? sql` lateral` : void 0;
const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;
if (is(table, PgTable)) {
const tableName = table[PgTable.Symbol.Name];
const tableSchema = table[PgTable.Symbol.Schema];
const origTableName = table[PgTable.Symbol.OriginalName];
const alias = tableName === origTableName ? void 0 : joinMeta.alias;
joinsArray.push(
sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`
);
} else if (is(table, View)) {
const viewName = table[ViewBaseConfig].name;
const viewSchema = table[ViewBaseConfig].schema;
const origViewName = table[ViewBaseConfig].originalName;
const alias = viewName === origViewName ? void 0 : joinMeta.alias;
joinsArray.push(
sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`
);
} else {
joinsArray.push(
sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table}${onSql}`
);
}
if (index < joins.length - 1) {
joinsArray.push(sql` `);
}
}
return sql.join(joinsArray);
}
buildFromTable(table) {
if (is(table, Table) && table[Table.Symbol.IsAlias]) {
let fullName = sql`${sql.identifier(table[Table.Symbol.OriginalName])}`;
if (table[Table.Symbol.Schema]) {
fullName = sql`${sql.identifier(table[Table.Symbol.Schema])}.${fullName}`;
}
return sql`${fullName} ${sql.identifier(table[Table.Symbol.Name])}`;
}
return table;
}
buildSelectQuery({
withList,
fields,
fieldsFlat,
where,
having,
table,
joins,
orderBy,
groupBy,
limit,
offset,
lockingClause,
distinct,
setOperators
}) {
const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
for (const f of fieldsList) {
if (is(f.field, Column) && getTableName(f.field.table) !== (is(table, Subquery) ? table._.alias : is(table, PgViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : getTableName(table)) && !((table2) => joins?.some(
({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName])
))(f.field.table)) {
const tableName = getTableName(f.field.table);
throw new Error(
`Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
);
}
}
const isSingleTable = !joins || joins.length === 0;
const withSql = this.buildWithCTE(withList);
let distinctSql;
if (distinct) {
distinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`;
}
const selection = this.buildSelection(fieldsList, { isSingleTable });
const tableSql = this.buildFromTable(table);
const joinsSql = this.buildJoins(joins);
const whereSql = where ? sql` where ${where}` : void 0;
const havingSql = having ? sql` having ${having}` : void 0;
let orderBySql;
if (orderBy && orderBy.length > 0) {
orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`;
}
let groupBySql;
if (groupBy && groupBy.length > 0) {
groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`;
}
const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
const offsetSql = offset ? sql` offset ${offset}` : void 0;
const lockingClauseSql = sql.empty();
if (lockingClause) {
const clauseSql = sql` for ${sql.raw(lockingClause.strength)}`;
if (lockingClause.config.of) {
clauseSql.append(
sql` of ${sql.join(
Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of],
sql`, `
)}`
);
}
if (lockingClause.config.noWait) {
clauseSql.append(sql` nowait`);
} else if (lockingClause.config.skipLocked) {
clauseSql.append(sql` skip locked`);
}
lockingClauseSql.append(clauseSql);
}
const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`;
if (setOperators.length > 0) {
return this.buildSetOperations(finalQuery, setOperators);
}
return finalQuery;
}
buildSetOperations(leftSelect, setOperators) {
const [setOperator, ...rest] = setOperators;
if (!setOperator) {
throw new Error("Cannot pass undefined values to any set operator");
}
if (rest.length === 0) {
return this.buildSetOperationQuery({ leftSelect, setOperator });
}
return this.buildSetOperations(
this.buildSetOperationQuery({ leftSelect, setOperator }),
rest
);
}
buildSetOperationQuery({
leftSelect,
setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
}) {
const leftChunk = sql`(${leftSelect.getSQL()}) `;
const rightChunk = sql`(${rightSelect.getSQL()})`;
let orderBySql;
if (orderBy && orderBy.length > 0) {
const orderByValues = [];
for (const singleOrderBy of orderBy) {
if (is(singleOrderBy, PgColumn)) {
orderByValues.push(sql.identifier(singleOrderBy.name));
} else if (is(singleOrderBy, SQL)) {
for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
const chunk = singleOrderBy.queryChunks[i];
if (is(chunk, PgColumn)) {
singleOrderBy.queryChunks[i] = sql.identifier(chunk.name);
}
}
orderByValues.push(sql`${singleOrderBy}`);
} else {
orderByValues.push(sql`${singleOrderBy}`);
}
}
orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `;
}
const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
const offsetSql = offset ? sql` offset ${offset}` : void 0;
return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
}
buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_ }) {
const valuesSqlList = [];
const columns = table[Table.Symbol.Columns];
const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());
const insertOrder = colEntries.map(
([, column]) => sql.identifier(this.casing.getColumnCasing(column))
);
if (select) {
const select2 = valuesOrSelect;
if (is(select2, SQL)) {
valuesSqlList.push(select2);
} else {
valuesSqlList.push(select2.getSQL());
}
} else {
const values = valuesOrSelect;
valuesSqlList.push(sql.raw("values "));
for (const [valueIndex, value] of values.entries()) {
const valueList = [];
for (const [fieldName, col] of colEntries) {
const colValue = value[fieldName];
if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
if (col.defaultFn !== void 0) {
const defaultFnResult = col.defaultFn();
const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
valueList.push(defaultValue);
} else if (!col.default && col.onUpdateFn !== void 0) {
const onUpdateFnResult = col.onUpdateFn();
const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
valueList.push(newValue);
} else {
valueList.push(sql`default`);
}
} else {
valueList.push(colValue);
}
}
valuesSqlList.push(valueList);
if (valueIndex < values.length - 1) {
valuesSqlList.push(sql`, `);
}
}
}
const withSql = this.buildWithCTE(withList);
const valuesSql = sql.join(valuesSqlList);
const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;
const overridingSql = overridingSystemValue_ === true ? sql`overriding system value ` : void 0;
return sql`${withSql}insert into ${table} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`;
}
buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) {
const concurrentlySql = concurrently ? sql` concurrently` : void 0;
const withNoDataSql = withNoData ? sql` with no data` : void 0;
return sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`;
}
prepareTyping(encoder) {
if (is(encoder, PgJsonb) || is(encoder, PgJson)) {
return "json";
} else if (is(encoder, PgNumeric)) {
return "decimal";
} else if (is(encoder, PgTime)) {
return "time";
} else if (is(encoder, PgTimestamp) || is(encoder, PgTimestampString)) {
return "timestamp";
} else if (is(encoder, PgDate) || is(encoder, PgDateString)) {
return "date";
} else if (is(encoder, PgUUID)) {
return "uuid";
} else {
return "none";
}
}
sqlToQuery(sql2, invokeSource) {
return sql2.toQuery({
casing: this.casing,
escapeName: this.escapeName,
escapeParam: this.escapeParam,
escapeString: this.escapeString,
prepareTyping: this.prepareTyping,
invokeSource
});
}
// buildRelationalQueryWithPK({
// fullSchema,
// schema,
// tableNamesMap,
// table,
// tableConfig,
// queryConfig: config,
// tableAlias,
// isRoot = false,
// joinOn,
// }: {
// fullSchema: Record<string, unknown>;
// schema: TablesRelationalConfig;
// tableNamesMap: Record<string, string>;
// table: PgTable;
// tableConfig: TableRelationalConfig;
// queryConfig: true | DBQueryConfig<'many', true>;
// tableAlias: string;
// isRoot?: boolean;
// joinOn?: SQL;
// }): BuildRelationalQueryResult<PgTable, PgColumn> {
// // For { "<relation>": true }, return a table with selection of all columns
// if (config === true) {
// const selectionEntries = Object.entries(tableConfig.columns);
// const selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = selectionEntries.map((
// [key, value],
// ) => ({
// dbKey: value.name,
// tsKey: key,
// field: value as PgColumn,
// relationTableTsKey: undefined,
// isJson: false,
// selection: [],
// }));
// return {
// tableTsKey: tableConfig.tsName,
// sql: table,
// selection,
// };
// }
// // let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
// // let selectionForBuild = selection;
// const aliasedColumns = Object.fromEntries(
// Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]),
// );
// const aliasedRelations = Object.fromEntries(
// Object.entries(tableConfig.relations).map(([key, value]) => [key, aliasedRelation(value, tableAlias)]),
// );
// const aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations);
// let where, hasUserDefinedWhere;
// if (config.where) {
// const whereSql = typeof config.where === 'function' ? config.where(aliasedFields, operators) : config.where;
// where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
// hasUserDefinedWhere = !!where;
// }
// where = and(joinOn, where);
// // const fieldsSelection: { tsKey: string; value: PgColumn | SQL.Aliased; isExtra?: boolean }[] = [];
// let joins: Join[] = [];
// let selectedColumns: string[] = [];
// // Figure out which columns to select
// if (config.columns) {
// let isIncludeMode = false;
// for (const [field, value] of Object.entries(config.columns)) {
// if (value === undefined) {
// continue;
// }
// if (field in tableConfig.columns) {
// if (!isIncludeMode && value === true) {
// isIncludeMode = true;
// }
// selectedColumns.push(field);
// }
// }
// if (selectedColumns.length > 0) {
// selectedColumns = isIncludeMode
// ? selectedColumns.filter((c) => config.columns?.[c] === true)
// : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
// }
// } else {
// // Select all columns if selection is not specified
// selectedColumns = Object.keys(tableConfig.columns);
// }
// // for (const field of selectedColumns) {
// // const column = tableConfig.columns[field]! as PgColumn;
// // fieldsSelection.push({ tsKey: field, value: column });
// // }
// let initiallySelectedRelations: {
// tsKey: string;
// queryConfig: true | DBQueryConfig<'many', false>;
// relation: Relation;
// }[] = [];
// // let selectedRelations: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
// // Figure out which relations to select
// if (config.with) {
// initiallySelectedRelations = Object.entries(config.with)
// .filter((entry): entry is [typeof entry[0], NonNullable<typeof entry[1]>] => !!entry[1])
// .map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));
// }
// const manyRelations = initiallySelectedRelations.filter((r) =>
// is(r.relation, Many)
// && (schema[tableNamesMap[r.relation.referencedTable[Table.Symbol.Name]]!]?.primaryKey.length ?? 0) > 0
// );
// // If this is the last Many relation (or there are no Many relations), we are on the innermost subquery level
// const isInnermostQuery = manyRelations.length < 2;
// const selectedExtras: {
// tsKey: string;
// value: SQL.Aliased;
// }[] = [];
// // Figure out which extras to select
// if (isInnermostQuery && config.extras) {
// const extras = typeof config.extras === 'function'
// ? config.extras(aliasedFields, { sql })
// : config.extras;
// for (const [tsKey, value] of Object.entries(extras)) {
// selectedExtras.push({
// tsKey,
// value: mapColumnsInAliasedSQLToAlias(value, tableAlias),
// });
// }
// }
// // Transform `fieldsSelection` into `selection`
// // `fieldsSelection` shouldn't be used after this point
// // for (const { tsKey, value, isExtra } of fieldsSelection) {
// // selection.push({
// // dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,
// // tsKey,
// // field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
// // relationTableTsKey: undefined,
// // isJson: false,
// // isExtra,
// // selection: [],
// // });
// // }
// let orderByOrig = typeof config.orderBy === 'function'
// ? config.orderBy(aliasedFields, orderByOperators)
// : config.orderBy ?? [];
// if (!Array.isArray(orderByOrig)) {
// orderByOrig = [orderByOrig];
// }
// const orderBy = orderByOrig.map((orderByValue) => {
// if (is(orderByValue, Column)) {
// return aliasedTableColumn(orderByValue, tableAlias) as PgColumn;
// }
// return mapColumnsInSQLToAlias(orderByValue, tableAlias);
// });
// const limit = isInnermostQuery ? config.limit : undefined;
// const offset = isInnermostQuery ? config.offset : undefined;
// // For non-root queries without additional config except columns, return a table with selection
// if (
// !isRoot
// && initiallySelectedRelations.length === 0
// && selectedExtras.length === 0
// && !where
// && orderBy.length === 0
// && limit === undefined
// && offset === undefined
// ) {
// return {
// tableTsKey: tableConfig.tsName,
// sql: table,
// selection: selectedColumns.map((key) => ({
// dbKey: tableConfig.columns[key]!.name,
// tsKey: key,
// field: tableConfig.columns[key] as PgColumn,
// relationTableTsKey: undefined,
// isJson: false,
// selection: [],
// })),
// };
// }
// const selectedRelationsWithoutPK:
// // Process all relations without primary keys, because they need to be joined differently and will all be on the same query level
// for (
// const {
// tsKey: selectedRelationTsKey,
// queryConfig: selectedRelationConfigValue,
// relation,
// } of initiallySelectedRelations
// ) {
// const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
// const relationTableName = relation.referencedTable[Table.Symbol.Name];
// const relationTableTsName = tableNamesMap[relationTableName]!;
// const relationTable = schema[relationTableTsName]!;
// if (relationTable.primaryKey.length > 0) {
// continue;
// }
// const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
// const joinOn = and(
// ...normalizedRelation.fields.map((field, i) =>
// eq(
// aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
// aliasedTableColumn(field, tableAlias),
// )
// ),
// );
// const builtRelation = this.buildRelationalQueryWithoutPK({
// fullSchema,
// schema,
// tableNamesMap,
// table: fullSchema[relationTableTsName] as PgTable,
// tableConfig: schema[relationTableTsName]!,
// queryConfig: selectedRelationConfigValue,
// tableAlias: relationTableAlias,
// joinOn,
// nestedQueryRelation: relation,
// });
// const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);
// joins.push({
// on: sql`true`,
// table: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias),
// alias: relationTableAlias,
// joinType: 'left',
// lateral: true,
// });
// selectedRelations.push({
// dbKey: selectedRelationTsKey,
// tsKey: selectedRelationTsKey,
// field,
// relationTableTsKey: relationTableTsName,
// isJson: true,
// selection: builtRelation.selection,
// });
// }
// const oneRelations = initiallySelectedRelations.filter((r): r is typeof r & { relation: One } =>
// is(r.relation, One)
// );
// // Process all One relations with PKs, because they can all be joined on the same level
// for (
// const {
// tsKey: selectedRelationTsKey,
// queryConfig: selectedRelationConfigValue,
// relation,
// } of oneRelations
// ) {
// const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
// const relationTableName = relation.referencedTable[Table.Symbol.Name];
// const relationTableTsName = tableNamesMap[relationTableName]!;
// const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
// const relationTable = schema[relationTableTsName]!;
// if (relationTable.primaryKey.length === 0) {
// continue;
// }
// const joinOn = and(
// ...normalizedRelation.fields.map((field, i) =>
// eq(
// aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
// aliasedTableColumn(field, tableAlias),
// )
// ),
// );
// const builtRelation = this.buildRelationalQueryWithPK({
// fullSchema,
// schema,
// tableNamesMap,
// table: fullSchema[relationTableTsName] as PgTable,
// tableConfig: schema[relationTableTsName]!,
// queryConfig: selectedRelationConfigValue,
// tableAlias: relationTableAlias,
// joinOn,
// });
// const field = sql`case when ${sql.identifier(relationTableAlias)} is null then null else json_build_array(${
// sql.join(
// builtRelation.selection.map(({ field }) =>
// is(field, SQL.Aliased)
// ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
// : is(field, Column)
// ? aliasedTableColumn(field, relationTableAlias)
// : field
// ),
// sql`, `,
// )
// }) end`.as(selectedRelationTsKey);
// const isLateralJoin = is(builtRelation.sql, SQL);
// joins.push({
// on: isLateralJoin ? sql`true` : joinOn,
// table: is(builtRelation.sql, SQL)
// ? new Subquery(builtRelation.sql, {}, relationTableAlias)
// : aliasedTable(builtRelation.sql, relationTableAlias),
// alias: relationTableAlias,
// joinType: 'left',
// lateral: is(builtRelation.sql, SQL),
// });
// selectedRelations.push({
// dbKey: selectedRelationTsKey,
// tsKey: selectedRelationTsKey,
// field,
// relationTableTsKey: relationTableTsName,
// isJson: true,
// selection: builtRelation.selection,
// });
// }
// let distinct: PgSelectConfig['distinct'];
// let tableFrom: PgTable | Subquery = table;
// // Process first Many relation - each one requires a nested subquery
// const manyRelation = manyRelations[0];
// if (manyRelation) {
// const {
// tsKey: selectedRelationTsKey,
// queryConfig: selectedRelationQueryConfig,
// relation,
// } = manyRelation;
// distinct = {
// on: tableConfig.primaryKey.map((c) => aliasedTableColumn(c as PgColumn, tableAlias)),
// };
// const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
// const relationTableName = relation.referencedTable[Table.Symbol.Name];
// const relationTableTsName = tableNamesMap[relationTableName]!;
// const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
// const joinOn = and(
// ...normalizedRelation.fields.map((field, i) =>
// eq(
// aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
// aliasedTableColumn(field, tableAlias),
// )
// ),
// );
// const builtRelationJoin = this.buildRelationalQueryWithPK({
// fullSchema,
// schema,
// tableNamesMap,
// table: fullSchema[relationTableTsName] as PgTable,
// tableConfig: schema[relationTableTsName]!,
// queryConfig: selectedRelationQueryConfig,
// tableAlias: relationTableAlias,
// joinOn,
// });
// const builtRelationSelectionField = sql`case when ${
// sql.identifier(relationTableAlias)
// } is null then '[]' else json_agg(json_build_array(${
// sql.join(
// builtRelationJoin.selection.map(({ field }) =>
// is(field, SQL.Aliased)
// ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
// : is(field, Column)
// ? aliasedTableColumn(field, relationTableAlias)
// : field
// ),
// sql`, `,
// )
// })) over (partition by ${sql.join(distinct.on, sql`, `)}) end`.as(selectedRelationTsKey);
// const isLateralJoin = is(builtRelationJoin.sql, SQL);
// joins.push({
// on: isLateralJoin ? sql`true` : joinOn,
// table: isLateralJoin
// ? new Subquery(builtRelationJoin.sql as SQL, {}, relationTableAlias)
// : aliasedTable(builtRelationJoin.sql as PgTable, relationTableAlias),
// alias: relationTableAlias,
// joinType: 'left',
// lateral: isLateralJoin,
// });
// // Build the "from" subquery with the remaining Many relations
// const builtTableFrom = this.buildRelationalQueryWithPK({
// fullSchema,
// schema,
// tableNamesMap,
// table,
// tableConfig,
// queryConfig: {
// ...config,
// where: undefined,
// orderBy: undefined,
// limit: undefined,
// offset: undefined,
// with: manyRelations.slice(1).reduce<NonNullable<typeof config['with']>>(
// (result, { tsKey, queryConfig: configValue }) => {
// result[tsKey] = configValue;
// return result;
// },
// {},
// ),
// },
// tableAlias,
// });
// selectedRelations.push({
// dbKey: selectedRelationTsKey,
// tsKey: selectedRelationTsKey,
// field: builtRelationSelectionField,
// relationTableTsKey: relationTableTsName,
// isJson: true,
// selection: builtRelationJoin.selection,
// });
// // selection = builtTableFrom.selection.map((item) =>
// // is(item.field, SQL.Aliased)
// // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
// // : item
// // );
// // selectionForBuild = [{
// // dbKey: '*',
// // tsKey: '*',
// // field: sql`${sql.identifier(tableAlias)}.*`,
// // selection: [],
// // isJson: false,
// // relationTableTsKey: undefined,
// // }];
// // const newSelectionItem: (typeof selection)[number] = {
// // dbKey: selectedRelationTsKey,
// // tsKey: selectedRelationTsKey,
// // field,
// // relationTableTsKey: relationTableTsName,
// // isJson: true,
// // selection: builtRelationJoin.selection,
// // };
// // selection.push(newSelectionItem);
// // selectionForBuild.push(newSelectionItem);
// tableFrom = is(builtTableFrom.sql, PgTable)
// ? builtTableFrom.sql
// : new Subquery(builtTableFrom.sql, {}, tableAlias);
// }
// if (selectedColumns.length === 0 && selectedRelations.length === 0 && selectedExtras.length === 0) {
// throw new DrizzleError(`No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`);
// }
// let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'];
// function prepareSelectedColumns() {
// return selectedColumns.map((key) => ({
// dbKey: tableConfig.columns[key]!.name,
// tsKey: key,
// field: tableConfig.columns[key] as PgColumn,
// relationTableTsKey: undefined,
// isJson: false,
// selection: [],
// }));
// }
// function prepareSelectedExtras() {
// return selectedExtras.map((item) => ({
// dbKey: item.value.fieldAlias,
// tsKey: item.tsKey,
// field: item.value,
// relationTableTsKey: undefined,
// isJson: false,
// selection: [],
// }));
// }
// if (isRoot) {
// selection = [
// ...prepareSelectedColumns(),
// ...prepareSelectedExtras(),
// ];
// }
// if (hasUserDefinedWhere || orderBy.length > 0) {
// tableFrom = new Subquery(
// this.buildSelectQuery({
// table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
// fields: {},
// fieldsFlat: selectionForBuild.map(({ field }) => ({
// path: [],
// field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
// })),
// joins,
// distinct,
// }),
// {},
// tableAlias,
// );
// selectionForBuild = selection.map((item) =>
// is(item.field, SQL.Aliased)
// ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
// : item
// );
// joins = [];
// distinct = undefined;
// }
// const result = this.buildSelectQuery({
// table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
// fields: {},
// fieldsFlat: selectionForBuild.map(({ field }) => ({
// path: [],
// field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
// })),
// where,
// limit,
// offset,
// joins,
// orderBy,
// distinct,
// });
// return {
// tableTsKey: tableConfig.tsName,
// sql: result,
// selection,
// };
// }
buildRelationalQueryWithoutPK({
fullSchema,
schema,
tableNamesMap,
table,
tableConfig,
queryConfig: config,
tableAlias,
nestedQueryRelation,
joinOn
}) {
let selection = [];
let limit, offset, orderBy = [], where;
const joins = [];
if (config === true) {
const selectionEntries = Object.entries(tableConfig.columns);
selection = selectionEntries.map(([key, value]) => ({
dbKey: value.name,
tsKey: key,
field: aliasedTableColumn(value, tableAlias),
relationTableTsKey: void 0,
isJson: false,
selection: []
}));
} else {
const aliasedColumns = Object.fromEntries(
Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
);
if (config.where) {
const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
}
const fieldsSelection = [];
let selectedColumns = [];
if (config.columns) {
let isIncludeMode = false;
for (const [field, value] of Object.entries(config.columns)) {
if (value === void 0) {
continue;
}
if (field in tableConfig.columns) {
if (!isIncludeMode && value === true) {
isIncludeMode = true;
}
selectedColumns.push(field);
}
}
if (selectedColumns.length > 0) {
selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
}
} else {
selectedColumns = Object.keys(tableConfig.columns);
}
for (const field of selectedColumns) {
const column = tableConfig.columns[field];
fieldsSelection.push({ tsKey: field, value: column });
}
let selectedRelations = [];
if (config.with) {
selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
}
let extras;
if (config.extras) {
extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
for (const [tsKey, value] of Object.entries(extras)) {
fieldsSelection.push({
tsKey,
value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
});
}
}
for (const { tsKey, value } of fieldsSelection) {
selection.push({
dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
tsKey,
field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
relationTableTsKey: void 0,
isJson: false,
selection: []
});
}
let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
if (!Array.isArray(orderByOrig)) {
orderByOrig = [orderByOrig];
}
orderBy = orderByOrig.map((orderByValue) => {
if (is(orderByValue, Column)) {
return aliasedTableColumn(orderByValue, tableAlias);
}
return mapColumnsInSQLToAlias(orderByValue, tableAlias);
});
limit = config.limit;
offset = config.offset;
for (const {
tsKey: selectedRelationTsKey,
queryConfig: selectedRelationConfigValue,
relation
} of selectedRelations) {
const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
const relationTableName = getTableUniqueName(relation.referencedTable);
const relationTableTsName = tableNamesMap[relationTableName];
const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
const joinOn2 = and(
...normalizedRelation.fields.map(
(field2, i) => eq(
aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
aliasedTableColumn(field2, tableAlias)
)
)
);
const builtRelation = this.buildRelationalQueryWithoutPK({
fullSchema,
schema,
tableNamesMap,
table: fullSchema[relationTableTsName],
tableConfig: schema[relationTableTsName],
queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
tableAlias: relationTableAlias,
joinOn: joinOn2,
nestedQueryRelation: relation
});
const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey);
joins.push({
on: sql`true`,
table: new Subquery(builtRelation.sql, {}, relationTableAlias),
alias: relationTableAlias,
joinType: "left",
lateral: true
});
selection.push({
dbKey: selectedRelationTsKey,
tsKey: selectedRelationTsKey,
field,
relationTableTsKey: relationTableTsName,
isJson: true,
selection: builtRelation.selection
});
}
}
if (selection.length === 0) {
throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
}
let result;
where = and(joinOn, where);
if (nestedQueryRelation) {
let field = sql`json_build_array(${sql.join(
selection.map(
({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2
),
sql`, `
)})`;
if (is(nestedQueryRelation, Many)) {
field = sql`coalesce(json_agg(${field}${orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0}), '[]'::json)`;
}
const nestedSelection = [{
dbKey: "data",
tsKey: "data",
field: field.as("data"),
isJson: true,
relationTableTsKey: tableConfig.tsName,
selection
}];
const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
if (needsSubquery) {
result = this.buildSelectQuery({
table: aliasedTable(table, tableAlias),
fields: {},
fieldsFlat: [{
path: [],
field: sql.raw("*")
}],
where,
limit,
offset,
orderBy,
setOperators: []
});
where = void 0;
limit = void 0;
offset = void 0;
orderBy = [];
} else {
result = aliasedTable(table, tableAlias);
}
result = this.buildSelectQuery({
table: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias),
fields: {},
fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
path: [],
field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2
})),
joins,
where,
limit,
offset,
orderBy,
setOperators: []
});
} else {
result = this.buildSelectQuery({
table: aliasedTable(table, tableAlias),
fields: {},
fieldsFlat: selection.map(({ field }) => ({
path: [],
field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field
})),
joins,
where,
limit,
offset,
orderBy,
setOperators: []
});
}
return {
tableTsKey: tableConfig.tsName,
sql: result,
selection
};
}
}
class TypedQueryBuilder {
static [entityKind] = "TypedQueryBuilder";
/** @internal */
getSelectedFields() {
return this._.selectedFields;
}
}
class PgSelectBuilder {
static [entityKind] = "PgSelectBuilder";
fields;
session;
dialect;
withList = [];
distinct;
constructor(config) {
this.fields = config.fields;
this.session = config.session;
this.dialect = config.dialect;
if (config.withList) {
this.withList = config.withList;
}
this.distinct = config.distinct;
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
/**
* Specify the table, subquery, or other target that you're
* building a select query against.
*
* {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation}
*/
from(source) {
const isPartialSelect = !!this.fields;
const src = source;
let fields;
if (this.fields) {
fields = this.fields;
} else if (is(src, Subquery)) {
fields = Object.fromEntries(
Object.keys(src._.selectedFields).map((key) => [key, src[key]])
);
} else if (is(src, PgViewBase)) {
fields = src[ViewBaseConfig].selectedFields;
} else if (is(src, SQL)) {
fields = {};
} else {
fields = getTableColumns(src);
}
return new PgSelectBase({
table: src,
fields,
isPartialSelect,
session: this.session,
dialect: this.dialect,
withList: this.withList,
distinct: this.distinct
}).setToken(this.authToken);
}
}
class PgSelectQueryBuilderBase extends TypedQueryBuilder {
static [entityKind] = "PgSelectQueryBuilder";
_;
config;
joinsNotNullableMap;
tableName;
isPartialSelect;
session;
dialect;
cacheConfig = void 0;
usedTables = /* @__PURE__ */ new Set();
constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
super();
this.config = {
withList,
table,
fields: { ...fields },
distinct,
setOperators: []
};
this.isPartialSelect = isPartialSelect;
this.session = session;
this.dialect = dialect;
this._ = {
selectedFields: fields,
config: this.config
};
this.tableName = getTableLikeName(table);
this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
for (const item of extractUsedTable(table)) this.usedTables.add(item);
}
/** @internal */
getUsedTables() {
return [...this.usedTables];
}
createJoin(joinType, lateral) {
return (table, on) => {
const baseTableName = this.tableName;
const tableName = getTableLikeName(table);
for (const item of extractUsedTable(table)) this.usedTables.add(item);
if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
throw new Error(`Alias "${tableName}" is already used in this query`);
}
if (!this.isPartialSelect) {
if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
this.config.fields = {
[baseTableName]: this.config.fields
};
}
if (typeof tableName === "string" && !is(table, SQL)) {
const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns];
this.config.fields[tableName] = selection;
}
}
if (typeof on === "function") {
on = on(
new Proxy(
this.config.fields,
new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
)
);
}
if (!this.config.joins) {
this.config.joins = [];
}
this.config.joins.push({ on, table, joinType, alias: tableName, lateral });
if (typeof tableName === "string") {
switch (joinType) {
case "left": {
this.joinsNotNullableMap[tableName] = false;
break;
}
case "right": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = true;
break;
}
case "cross":
case "inner": {
this.joinsNotNullableMap[tableName] = true;
break;
}
case "full": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = false;
break;
}
}
}
return this;
};
}
/**
* Executes a `left join` operation by adding another table to the current query.
*
* Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
leftJoin = this.createJoin("left", false);
/**
* Executes a `left join lateral` operation by adding subquery to the current query.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#left-join-lateral}
*
* @param table the subquery to join.
* @param on the `on` clause.
*/
leftJoinLateral = this.createJoin("left", true);
/**
* Executes a `right join` operation by adding another table to the current query.
*
* Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
rightJoin = this.createJoin("right", false);
/**
* Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
*
* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
innerJoin = this.createJoin("inner", false);
/**
* Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join-lateral}
*
* @param table the subquery to join.
* @param on the `on` clause.
*/
innerJoinLateral = this.createJoin("inner", true);
/**
* Executes a `full join` operation by combining rows from two tables into a new table.
*
* Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select()
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
fullJoin = this.createJoin("full", false);
/**
* Executes a `cross join` operation by combining rows from two tables into a new table.
*
* Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
*
* @param table the table to join.
*
* @example
*
* ```ts
* // Select all users, each user with every pet
* const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
* .from(users)
* .crossJoin(pets)
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .crossJoin(pets)
* ```
*/
crossJoin = this.createJoin("cross", false);
/**
* Executes a `cross join lateral` operation by combining rows from two queries into a new table.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* Calling this method retrieves all rows from both main and joined queries, merging all rows from each query.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral}
*
* @param table the query to join.
*/
crossJoinLateral = this.createJoin("cross", true);
createSetOperator(type, isAll) {
return (rightSelection) => {
const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators()) : rightSelection;
if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
throw new Error(
"Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
);
}
this.config.setOperators.push({ type, isAll, rightSelect });
return this;
};
}
/**
* Adds `union` set operator to the query.
*
* Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
*
* @example
*
* ```ts
* // Select all unique names from customers and users tables
* await db.select({ name: users.name })
* .from(users)
* .union(
* db.select({ name: customers.name }).from(customers)
* );
* // or
* import { union } from 'drizzle-orm/pg-core'
*
* await union(
* db.select({ name: users.name }).from(users),
* db.select({ name: customers.name }).from(customers)
* );
* ```
*/
union = this.createSetOperator("union", false);
/**
* Adds `union all` set operator to the query.
*
* Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
*
* @example
*
* ```ts
* // Select all transaction ids from both online and in-store sales
* await db.select({ transaction: onlineSales.transactionId })
* .from(onlineSales)
* .unionAll(
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* // or
* import { unionAll } from 'drizzle-orm/pg-core'
*
* await unionAll(
* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* ```
*/
unionAll = this.createSetOperator("union", true);
/**
* Adds `intersect` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
*
* @example
*
* ```ts
* // Select course names that are offered in both departments A and B
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .intersect(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* import { intersect } from 'drizzle-orm/pg-core'
*
* await intersect(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
intersect = this.createSetOperator("intersect", false);
/**
* Adds `intersect all` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets including all duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
*
* @example
*
* ```ts
* // Select all products and quantities that are ordered by both regular and VIP customers
* await db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders)
* .intersectAll(
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* // or
* import { intersectAll } from 'drizzle-orm/pg-core'
*
* await intersectAll(
* db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders),
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* ```
*/
intersectAll = this.createSetOperator("intersect", true);
/**
* Adds `except` set operator to the query.
*
* Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
*
* @example
*
* ```ts
* // Select all courses offered in department A but not in department B
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .except(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* import { except } from 'drizzle-orm/pg-core'
*
* await except(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
except = this.createSetOperator("except", false);
/**
* Adds `except all` set operator to the query.
*
* Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
*
* @example
*
* ```ts
* // Select all products that are ordered by regular customers but not by VIP customers
* await db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered,
* })
* .from(regularCustomerOrders)
* .exceptAll(
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered,
* })
* .from(vipCustomerOrders)
* );
* // or
* import { exceptAll } from 'drizzle-orm/pg-core'
*
* await exceptAll(
* db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders),
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* ```
*/
exceptAll = this.createSetOperator("except", true);
/** @internal */
addSetOperators(setOperators) {
this.config.setOperators.push(...setOperators);
return this;
}
/**
* Adds a `where` clause to the query.
*
* Calling this method will select only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/select#filtering}
*
* @param where the `where` clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be selected.
*
* ```ts
* // Select all cars with green color
* await db.select().from(cars).where(eq(cars.color, 'green'));
* // or
* await db.select().from(cars).where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Select all BMW cars with a green color
* await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Select all cars with the green or blue color
* await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
if (typeof where === "function") {
where = where(
new Proxy(
this.config.fields,
new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
)
);
}
this.config.where = where;
return this;
}
/**
* Adds a `having` clause to the query.
*
* Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
*
* @param having the `having` clause.
*
* @example
*
* ```ts
* // Select all brands with more than one car
* await db.select({
* brand: cars.brand,
* count: sql<number>`cast(count(${cars.id}) as int)`,
* })
* .from(cars)
* .groupBy(cars.brand)
* .having(({ count }) => gt(count, 1));
* ```
*/
having(having) {
if (typeof having === "function") {
having = having(
new Proxy(
this.config.fields,
new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
)
);
}
this.config.having = having;
return this;
}
groupBy(...columns) {
if (typeof columns[0] === "function") {
const groupBy = columns[0](
new Proxy(
this.config.fields,
new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
)
);
this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
} else {
this.config.groupBy = columns;
}
return this;
}
orderBy(...columns) {
if (typeof columns[0] === "function") {
const orderBy = columns[0](
new Proxy(
this.config.fields,
new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
)
);
const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).orderBy = orderByArray;
} else {
this.config.orderBy = orderByArray;
}
} else {
const orderByArray = columns;
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).orderBy = orderByArray;
} else {
this.config.orderBy = orderByArray;
}
}
return this;
}
/**
* Adds a `limit` clause to the query.
*
* Calling this method will set the maximum number of rows that will be returned by this query.
*
* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
*
* @param limit the `limit` clause.
*
* @example
*
* ```ts
* // Get the first 10 people from this query.
* await db.select().from(people).limit(10);
* ```
*/
limit(limit) {
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).limit = limit;
} else {
this.config.limit = limit;
}
return this;
}
/**
* Adds an `offset` clause to the query.
*
* Calling this method will skip a number of rows when returning results from this query.
*
* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
*
* @param offset the `offset` clause.
*
* @example
*
* ```ts
* // Get the 10th-20th people from this query.
* await db.select().from(people).offset(10).limit(10);
* ```
*/
offset(offset) {
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).offset = offset;
} else {
this.config.offset = offset;
}
return this;
}
/**
* Adds a `for` clause to the query.
*
* Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.
*
* See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE}
*
* @param strength the lock strength.
* @param config the lock configuration.
*/
for(strength, config = {}) {
this.config.lockingClause = { strength, config };
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildSelectQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
as(alias) {
const usedTables = [];
usedTables.push(...extractUsedTable(this.config.table));
if (this.config.joins) {
for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table));
}
return new Proxy(
new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
);
}
/** @internal */
getSelectedFields() {
return new Proxy(
this.config.fields,
new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
);
}
$dynamic() {
return this;
}
$withCache(config) {
this.cacheConfig = config === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config };
return this;
}
}
class PgSelectBase extends PgSelectQueryBuilderBase {
static [entityKind] = "PgSelect";
/** @internal */
_prepare(name) {
const { session, config, dialect, joinsNotNullableMap, authToken, cacheConfig, usedTables } = this;
if (!session) {
throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
}
const { fields } = config;
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
const fieldsList = orderSelectedFields(fields);
const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true, void 0, {
type: "select",
tables: [...usedTables]
}, cacheConfig);
query.joinsNotNullableMap = joinsNotNullableMap;
return query.setToken(authToken);
});
}
/**
* Create a prepared statement for this query. This allows
* the database to remember this query for the given session
* and call it by name, rather than specifying the full query.
*
* {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation}
*/
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues, this.authToken);
});
};
}
applyMixins(PgSelectBase, [QueryPromise]);
function createSetOperator(type, isAll) {
return (leftSelect, rightSelect, ...restSelects) => {
const setOperators = [rightSelect, ...restSelects].map((select) => ({
type,
isAll,
rightSelect: select
}));
for (const setOperator of setOperators) {
if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
throw new Error(
"Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
);
}
}
return leftSelect.addSetOperators(setOperators);
};
}
const getPgSetOperators = () => ({
union,
unionAll,
intersect,
intersectAll,
except,
exceptAll
});
const union = createSetOperator("union", false);
const unionAll = createSetOperator("union", true);
const intersect = createSetOperator("intersect", false);
const intersectAll = createSetOperator("intersect", true);
const except = createSetOperator("except", false);
const exceptAll = createSetOperator("except", true);
class QueryBuilder {
static [entityKind] = "PgQueryBuilder";
dialect;
dialectConfig;
constructor(dialect) {
this.dialect = is(dialect, PgDialect) ? dialect : void 0;
this.dialectConfig = is(dialect, PgDialect) ? void 0 : dialect;
}
$with = (alias, selection) => {
const queryBuilder = this;
const as = (qb) => {
if (typeof qb === "function") {
qb = qb(queryBuilder);
}
return new Proxy(
new WithSubquery(
qb.getSQL(),
selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
alias,
true
),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
);
};
return { as };
};
with(...queries) {
const self = this;
function select(fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
withList: queries
});
}
function selectDistinct(fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
distinct: true
});
}
function selectDistinctOn(on, fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
distinct: { on }
});
}
return { select, selectDistinct, selectDistinctOn };
}
select(fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect()
});
}
selectDistinct(fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect(),
distinct: true
});
}
selectDistinctOn(on, fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect(),
distinct: { on }
});
}
// Lazy load dialect to avoid circular dependency
getDialect() {
if (!this.dialect) {
this.dialect = new PgDialect(this.dialectConfig);
}
return this.dialect;
}
}
function extractUsedTable(table) {
if (is(table, PgTable)) {
return [table[Schema] ? `${table[Schema]}.${table[Table.Symbol.BaseName]}` : table[Table.Symbol.BaseName]];
}
if (is(table, Subquery)) {
return table._.usedTables ?? [];
}
if (is(table, SQL)) {
return table.usedTables ?? [];
}
return [];
}
class PgDeleteBase extends QueryPromise {
constructor(table, session, dialect, withList) {
super();
this.session = session;
this.dialect = dialect;
this.config = { table, withList };
}
static [entityKind] = "PgDelete";
config;
cacheConfig;
/**
* Adds a `where` clause to the query.
*
* Calling this method will delete only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/delete}
*
* @param where the `where` clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be deleted.
*
* ```ts
* // Delete all cars with green color
* await db.delete(cars).where(eq(cars.color, 'green'));
* // or
* await db.delete(cars).where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Delete all BMW cars with a green color
* await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Delete all cars with the green or blue color
* await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
this.config.where = where;
return this;
}
returning(fields = this.config.table[Table.Symbol.Columns]) {
this.config.returningFields = fields;
this.config.returning = orderSelectedFields(fields);
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildDeleteQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
/** @internal */
_prepare(name) {
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, {
type: "delete",
tables: extractUsedTable(this.config.table)
}, this.cacheConfig);
});
}
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues, this.authToken);
});
};
/** @internal */
getSelectedFields() {
return this.config.returningFields ? new Proxy(
this.config.returningFields,
new SelectionProxyHandler({
alias: getTableName(this.config.table),
sqlAliasedBehavior: "alias",
sqlBehavior: "error"
})
) : void 0;
}
$dynamic() {
return this;
}
}
class PgInsertBuilder {
constructor(table, session, dialect, withList, overridingSystemValue_) {
this.table = table;
this.session = session;
this.dialect = dialect;
this.withList = withList;
this.overridingSystemValue_ = overridingSystemValue_;
}
static [entityKind] = "PgInsertBuilder";
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
overridingSystemValue() {
this.overridingSystemValue_ = true;
return this;
}
values(values) {
values = Array.isArray(values) ? values : [values];
if (values.length === 0) {
throw new Error("values() must be called with at least one value");
}
const mappedValues = values.map((entry) => {
const result = {};
const cols = this.table[Table.Symbol.Columns];
for (const colKey of Object.keys(entry)) {
const colValue = entry[colKey];
result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
}
return result;
});
return new PgInsertBase(
this.table,
mappedValues,
this.session,
this.dialect,
this.withList,
false,
this.overridingSystemValue_
).setToken(this.authToken);
}
select(selectQuery) {
const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery;
if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
throw new Error(
"Insert select error: selected fields are not the same or are in a different order compared to the table definition"
);
}
return new PgInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
}
}
class PgInsertBase extends QueryPromise {
constructor(table, values, session, dialect, withList, select, overridingSystemValue_) {
super();
this.session = session;
this.dialect = dialect;
this.config = { table, values, withList, select, overridingSystemValue_ };
}
static [entityKind] = "PgInsert";
config;
cacheConfig;
returning(fields = this.config.table[Table.Symbol.Columns]) {
this.config.returningFields = fields;
this.config.returning = orderSelectedFields(fields);
return this;
}
/**
* Adds an `on conflict do nothing` clause to the query.
*
* Calling this method simply avoids inserting a row as its alternative action.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
*
* @param config The `target` and `where` clauses.
*
* @example
* ```ts
* // Insert one row and cancel the insert if there's a conflict
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoNothing();
*
* // Explicitly specify conflict target
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoNothing({ target: cars.id });
* ```
*/
onConflictDoNothing(config = {}) {
if (config.target === void 0) {
this.config.onConflict = sql`do nothing`;
} else {
let targetColumn = "";
targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
const whereSql = config.where ? sql` where ${config.where}` : void 0;
this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
}
return this;
}
/**
* Adds an `on conflict do update` clause to the query.
*
* Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
*
* @param config The `target`, `set` and `where` clauses.
*
* @example
* ```ts
* // Update the row if there's a conflict
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoUpdate({
* target: cars.id,
* set: { brand: 'Porsche' }
* });
*
* // Upsert with 'where' clause
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoUpdate({
* target: cars.id,
* set: { brand: 'newBMW' },
* targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
* });
* ```
*/
onConflictDoUpdate(config) {
if (config.where && (config.targetWhere || config.setWhere)) {
throw new Error(
'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
);
}
const whereSql = config.where ? sql` where ${config.where}` : void 0;
const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
let targetColumn = "";
targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildInsertQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
/** @internal */
_prepare(name) {
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, {
type: "insert",
tables: extractUsedTable(this.config.table)
}, this.cacheConfig);
});
}
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues, this.authToken);
});
};
/** @internal */
getSelectedFields() {
return this.config.returningFields ? new Proxy(
this.config.returningFields,
new SelectionProxyHandler({
alias: getTableName(this.config.table),
sqlAliasedBehavior: "alias",
sqlBehavior: "error"
})
) : void 0;
}
$dynamic() {
return this;
}
}
class PgRefreshMaterializedView extends QueryPromise {
constructor(view, session, dialect) {
super();
this.session = session;
this.dialect = dialect;
this.config = { view };
}
static [entityKind] = "PgRefreshMaterializedView";
config;
concurrently() {
if (this.config.withNoData !== void 0) {
throw new Error("Cannot use concurrently and withNoData together");
}
this.config.concurrently = true;
return this;
}
withNoData() {
if (this.config.concurrently !== void 0) {
throw new Error("Cannot use concurrently and withNoData together");
}
this.config.withNoData = true;
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildRefreshMaterializedViewQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
/** @internal */
_prepare(name) {
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name, true);
});
}
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues, this.authToken);
});
};
}
class PgUpdateBuilder {
constructor(table, session, dialect, withList) {
this.table = table;
this.session = session;
this.dialect = dialect;
this.withList = withList;
}
static [entityKind] = "PgUpdateBuilder";
authToken;
setToken(token) {
this.authToken = token;
return this;
}
set(values) {
return new PgUpdateBase(
this.table,
mapUpdateSet(this.table, values),
this.session,
this.dialect,
this.withList
).setToken(this.authToken);
}
}
class PgUpdateBase extends QueryPromise {
constructor(table, set, session, dialect, withList) {
super();
this.session = session;
this.dialect = dialect;
this.config = { set, table, withList, joins: [] };
this.tableName = getTableLikeName(table);
this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
}
static [entityKind] = "PgUpdate";
config;
tableName;
joinsNotNullableMap;
cacheConfig;
from(source) {
const src = source;
const tableName = getTableLikeName(src);
if (typeof tableName === "string") {
this.joinsNotNullableMap[tableName] = true;
}
this.config.from = src;
return this;
}
getTableLikeFields(table) {
if (is(table, PgTable)) {
return table[Table.Symbol.Columns];
} else if (is(table, Subquery)) {
return table._.selectedFields;
}
return table[ViewBaseConfig].selectedFields;
}
createJoin(joinType) {
return (table, on) => {
const tableName = getTableLikeName(table);
if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
throw new Error(`Alias "${tableName}" is already used in this query`);
}
if (typeof on === "function") {
const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : void 0;
on = on(
new Proxy(
this.config.table[Table.Symbol.Columns],
new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
),
from && new Proxy(
from,
new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
)
);
}
this.config.joins.push({ on, table, joinType, alias: tableName });
if (typeof tableName === "string") {
switch (joinType) {
case "left": {
this.joinsNotNullableMap[tableName] = false;
break;
}
case "right": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = true;
break;
}
case "inner": {
this.joinsNotNullableMap[tableName] = true;
break;
}
case "full": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = false;
break;
}
}
}
return this;
};
}
leftJoin = this.createJoin("left");
rightJoin = this.createJoin("right");
innerJoin = this.createJoin("inner");
fullJoin = this.createJoin("full");
/**
* Adds a 'where' clause to the query.
*
* Calling this method will update only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/update}
*
* @param where the 'where' clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be updated.
*
* ```ts
* // Update all cars with green color
* await db.update(cars).set({ color: 'red' })
* .where(eq(cars.color, 'green'));
* // or
* await db.update(cars).set({ color: 'red' })
* .where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Update all BMW cars with a green color
* await db.update(cars).set({ color: 'red' })
* .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Update all cars with the green or blue color
* await db.update(cars).set({ color: 'red' })
* .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
this.config.where = where;
return this;
}
returning(fields) {
if (!fields) {
fields = Object.assign({}, this.config.table[Table.Symbol.Columns]);
if (this.config.from) {
const tableName = getTableLikeName(this.config.from);
if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) {
const fromFields = this.getTableLikeFields(this.config.from);
fields[tableName] = fromFields;
}
for (const join of this.config.joins) {
const tableName2 = getTableLikeName(join.table);
if (typeof tableName2 === "string" && !is(join.table, SQL)) {
const fromFields = this.getTableLikeFields(join.table);
fields[tableName2] = fromFields;
}
}
}
}
this.config.returningFields = fields;
this.config.returning = orderSelectedFields(fields);
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildUpdateQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
/** @internal */
_prepare(name) {
const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, {
type: "insert",
tables: extractUsedTable(this.config.table)
}, this.cacheConfig);
query.joinsNotNullableMap = this.joinsNotNullableMap;
return query;
}
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return this._prepare().execute(placeholderValues, this.authToken);
};
/** @internal */
getSelectedFields() {
return this.config.returningFields ? new Proxy(
this.config.returningFields,
new SelectionProxyHandler({
alias: getTableName(this.config.table),
sqlAliasedBehavior: "alias",
sqlBehavior: "error"
})
) : void 0;
}
$dynamic() {
return this;
}
}
class PgCountBuilder extends SQL {
constructor(params) {
super(PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
this.params = params;
this.mapWith(Number);
this.session = params.session;
this.sql = PgCountBuilder.buildCount(
params.source,
params.filters
);
}
sql;
token;
static [entityKind] = "PgCountBuilder";
[Symbol.toStringTag] = "PgCountBuilder";
session;
static buildEmbeddedCount(source, filters) {
return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
}
static buildCount(source, filters) {
return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`;
}
/** @intrnal */
setToken(token) {
this.token = token;
return this;
}
then(onfulfilled, onrejected) {
return Promise.resolve(this.session.count(this.sql, this.token)).then(
onfulfilled,
onrejected
);
}
catch(onRejected) {
return this.then(void 0, onRejected);
}
finally(onFinally) {
return this.then(
(value) => {
onFinally?.();
return value;
},
(reason) => {
onFinally?.();
throw reason;
}
);
}
}
class RelationalQueryBuilder {
constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) {
this.fullSchema = fullSchema;
this.schema = schema;
this.tableNamesMap = tableNamesMap;
this.table = table;
this.tableConfig = tableConfig;
this.dialect = dialect;
this.session = session;
}
static [entityKind] = "PgRelationalQueryBuilder";
findMany(config) {
return new PgRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? config : {},
"many"
);
}
findFirst(config) {
return new PgRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? { ...config, limit: 1 } : { limit: 1 },
"first"
);
}
}
class PgRelationalQuery extends QueryPromise {
constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, mode) {
super();
this.fullSchema = fullSchema;
this.schema = schema;
this.tableNamesMap = tableNamesMap;
this.table = table;
this.tableConfig = tableConfig;
this.dialect = dialect;
this.session = session;
this.config = config;
this.mode = mode;
}
static [entityKind] = "PgRelationalQuery";
/** @internal */
_prepare(name) {
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
const { query, builtQuery } = this._toSQL();
return this.session.prepareQuery(
builtQuery,
void 0,
name,
true,
(rawRows, mapColumnValue) => {
const rows = rawRows.map(
(row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
);
if (this.mode === "first") {
return rows[0];
}
return rows;
}
);
});
}
prepare(name) {
return this._prepare(name);
}
_getQuery() {
return this.dialect.buildRelationalQueryWithoutPK({
fullSchema: this.fullSchema,
schema: this.schema,
tableNamesMap: this.tableNamesMap,
table: this.table,
tableConfig: this.tableConfig,
queryConfig: this.config,
tableAlias: this.tableConfig.tsName
});
}
/** @internal */
getSQL() {
return this._getQuery().sql;
}
_toSQL() {
const query = this._getQuery();
const builtQuery = this.dialect.sqlToQuery(query.sql);
return { query, builtQuery };
}
toSQL() {
return this._toSQL().builtQuery;
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute() {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(void 0, this.authToken);
});
}
}
class PgRaw extends QueryPromise {
constructor(execute, sql, query, mapBatchResult) {
super();
this.execute = execute;
this.sql = sql;
this.query = query;
this.mapBatchResult = mapBatchResult;
}
static [entityKind] = "PgRaw";
/** @internal */
getSQL() {
return this.sql;
}
getQuery() {
return this.query;
}
mapResult(result, isFromBatch) {
return isFromBatch ? this.mapBatchResult(result) : result;
}
_prepare() {
return this;
}
/** @internal */
isResponseInArrayMode() {
return false;
}
}
class PgDatabase {
constructor(dialect, session, schema) {
this.dialect = dialect;
this.session = session;
this._ = schema ? {
schema: schema.schema,
fullSchema: schema.fullSchema,
tableNamesMap: schema.tableNamesMap,
session
} : {
schema: void 0,
fullSchema: {},
tableNamesMap: {},
session
};
this.query = {};
if (this._.schema) {
for (const [tableName, columns] of Object.entries(this._.schema)) {
this.query[tableName] = new RelationalQueryBuilder(
schema.fullSchema,
this._.schema,
this._.tableNamesMap,
schema.fullSchema[tableName],
columns,
dialect,
session
);
}
}
this.$cache = { invalidate: async (_params) => {
} };
}
static [entityKind] = "PgDatabase";
query;
/**
* Creates a subquery that defines a temporary named result set as a CTE.
*
* It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
*
* See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
*
* @param alias The alias for the subquery.
*
* Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
*
* @example
*
* ```ts
* // Create a subquery with alias 'sq' and use it in the select query
* const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
*
* const result = await db.with(sq).select().from(sq);
* ```
*
* To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
*
* ```ts
* // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
* const sq = db.$with('sq').as(db.select({
* name: sql<string>`upper(${users.name})`.as('name'),
* })
* .from(users));
*
* const result = await db.with(sq).select({ name: sq.name }).from(sq);
* ```
*/
$with = (alias, selection) => {
const self = this;
const as = (qb) => {
if (typeof qb === "function") {
qb = qb(new QueryBuilder(self.dialect));
}
return new Proxy(
new WithSubquery(
qb.getSQL(),
selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
alias,
true
),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
);
};
return { as };
};
$count(source, filters) {
return new PgCountBuilder({ source, filters, session: this.session });
}
$cache;
/**
* Incorporates a previously defined CTE (using `$with`) into the main query.
*
* This method allows the main query to reference a temporary named result set.
*
* See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
*
* @param queries The CTEs to incorporate into the main query.
*
* @example
*
* ```ts
* // Define a subquery 'sq' as a CTE using $with
* const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
*
* // Incorporate the CTE 'sq' into the main query and select from it
* const result = await db.with(sq).select().from(sq);
* ```
*/
with(...queries) {
const self = this;
function select(fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: self.session,
dialect: self.dialect,
withList: queries
});
}
function selectDistinct(fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: self.session,
dialect: self.dialect,
withList: queries,
distinct: true
});
}
function selectDistinctOn(on, fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: self.session,
dialect: self.dialect,
withList: queries,
distinct: { on }
});
}
function update(table) {
return new PgUpdateBuilder(table, self.session, self.dialect, queries);
}
function insert(table) {
return new PgInsertBuilder(table, self.session, self.dialect, queries);
}
function delete_(table) {
return new PgDeleteBase(table, self.session, self.dialect, queries);
}
return { select, selectDistinct, selectDistinctOn, update, insert, delete: delete_ };
}
select(fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: this.session,
dialect: this.dialect
});
}
selectDistinct(fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: this.session,
dialect: this.dialect,
distinct: true
});
}
selectDistinctOn(on, fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: this.session,
dialect: this.dialect,
distinct: { on }
});
}
/**
* Creates an update query.
*
* Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
*
* Use `.set()` method to specify which values to update.
*
* See docs: {@link https://orm.drizzle.team/docs/update}
*
* @param table The table to update.
*
* @example
*
* ```ts
* // Update all rows in the 'cars' table
* await db.update(cars).set({ color: 'red' });
*
* // Update rows with filters and conditions
* await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
*
* // Update with returning clause
* const updatedCar: Car[] = await db.update(cars)
* .set({ color: 'red' })
* .where(eq(cars.id, 1))
* .returning();
* ```
*/
update(table) {
return new PgUpdateBuilder(table, this.session, this.dialect);
}
/**
* Creates an insert query.
*
* Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
*
* See docs: {@link https://orm.drizzle.team/docs/insert}
*
* @param table The table to insert into.
*
* @example
*
* ```ts
* // Insert one row
* await db.insert(cars).values({ brand: 'BMW' });
*
* // Insert multiple rows
* await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
*
* // Insert with returning clause
* const insertedCar: Car[] = await db.insert(cars)
* .values({ brand: 'BMW' })
* .returning();
* ```
*/
insert(table) {
return new PgInsertBuilder(table, this.session, this.dialect);
}
/**
* Creates a delete query.
*
* Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
*
* See docs: {@link https://orm.drizzle.team/docs/delete}
*
* @param table The table to delete from.
*
* @example
*
* ```ts
* // Delete all rows in the 'cars' table
* await db.delete(cars);
*
* // Delete rows with filters and conditions
* await db.delete(cars).where(eq(cars.color, 'green'));
*
* // Delete with returning clause
* const deletedCar: Car[] = await db.delete(cars)
* .where(eq(cars.id, 1))
* .returning();
* ```
*/
delete(table) {
return new PgDeleteBase(table, this.session, this.dialect);
}
refreshMaterializedView(view) {
return new PgRefreshMaterializedView(view, this.session, this.dialect);
}
authToken;
execute(query) {
const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
const builtQuery = this.dialect.sqlToQuery(sequel);
const prepared = this.session.prepareQuery(
builtQuery,
void 0,
void 0,
false
);
return new PgRaw(
() => prepared.execute(void 0, this.authToken),
sequel,
builtQuery,
(result) => prepared.mapResult(result, true)
);
}
transaction(transaction, config) {
return this.session.transaction(transaction, config);
}
}
class Cache {
static [entityKind] = "Cache";
}
class NoopCache extends Cache {
strategy() {
return "all";
}
static [entityKind] = "NoopCache";
async get(_key) {
return void 0;
}
async put(_hashedQuery, _response, _tables, _config) {
}
async onMutate(_params) {
}
}
async function hashQuery(sql, params) {
const dataToHash = `${sql}-${JSON.stringify(params)}`;
const encoder = new TextEncoder();
const data = encoder.encode(dataToHash);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
const hashArray = [...new Uint8Array(hashBuffer)];
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
return hashHex;
}
class PgPreparedQuery {
constructor(query, cache, queryMetadata, cacheConfig) {
this.query = query;
this.cache = cache;
this.queryMetadata = queryMetadata;
this.cacheConfig = cacheConfig;
if (cache && cache.strategy() === "all" && cacheConfig === void 0) {
this.cacheConfig = { enable: true, autoInvalidate: true };
}
if (!this.cacheConfig?.enable) {
this.cacheConfig = void 0;
}
}
authToken;
getQuery() {
return this.query;
}
mapResult(response, _isFromBatch) {
return response;
}
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
static [entityKind] = "PgPreparedQuery";
/** @internal */
joinsNotNullableMap;
/** @internal */
async queryWithCache(queryString, params, query) {
if (this.cache === void 0 || is(this.cache, NoopCache) || this.queryMetadata === void 0) {
try {
return await query();
} catch (e) {
throw new DrizzleQueryError(queryString, params, e);
}
}
if (this.cacheConfig && !this.cacheConfig.enable) {
try {
return await query();
} catch (e) {
throw new DrizzleQueryError(queryString, params, e);
}
}
if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) {
try {
const [res] = await Promise.all([
query(),
this.cache.onMutate({ tables: this.queryMetadata.tables })
]);
return res;
} catch (e) {
throw new DrizzleQueryError(queryString, params, e);
}
}
if (!this.cacheConfig) {
try {
return await query();
} catch (e) {
throw new DrizzleQueryError(queryString, params, e);
}
}
if (this.queryMetadata.type === "select") {
const fromCache = await this.cache.get(
this.cacheConfig.tag ?? (await hashQuery(queryString, params)),
this.queryMetadata.tables,
this.cacheConfig.tag !== void 0,
this.cacheConfig.autoInvalidate
);
if (fromCache === void 0) {
let result;
try {
result = await query();
} catch (e) {
throw new DrizzleQueryError(queryString, params, e);
}
await this.cache.put(
this.cacheConfig.tag ?? (await hashQuery(queryString, params)),
result,
// make sure we send tables that were used in a query only if user wants to invalidate it on each write
this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [],
this.cacheConfig.tag !== void 0,
this.cacheConfig.config
);
return result;
}
return fromCache;
}
try {
return await query();
} catch (e) {
throw new DrizzleQueryError(queryString, params, e);
}
}
}
class PgSession {
constructor(dialect) {
this.dialect = dialect;
}
static [entityKind] = "PgSession";
/** @internal */
execute(query, token) {
return tracer.startActiveSpan("drizzle.operation", () => {
const prepared = tracer.startActiveSpan("drizzle.prepareQuery", () => {
return this.prepareQuery(
this.dialect.sqlToQuery(query),
void 0,
void 0,
false
);
});
return prepared.setToken(token).execute(void 0, token);
});
}
all(query) {
return this.prepareQuery(
this.dialect.sqlToQuery(query),
void 0,
void 0,
false
).all();
}
/** @internal */
async count(sql2, token) {
const res = await this.execute(sql2, token);
return Number(
res[0]["count"]
);
}
}
class PgTransaction extends PgDatabase {
constructor(dialect, session, schema, nestedIndex = 0) {
super(dialect, session, schema);
this.schema = schema;
this.nestedIndex = nestedIndex;
}
static [entityKind] = "PgTransaction";
rollback() {
throw new TransactionRollbackError();
}
/** @internal */
getTransactionConfigSQL(config) {
const chunks = [];
if (config.isolationLevel) {
chunks.push(`isolation level ${config.isolationLevel}`);
}
if (config.accessMode) {
chunks.push(config.accessMode);
}
if (typeof config.deferrable === "boolean") {
chunks.push(config.deferrable ? "deferrable" : "not deferrable");
}
return sql.raw(chunks.join(" "));
}
setTransaction(config) {
return this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config)}`);
}
}
class PostgresJsPreparedQuery extends PgPreparedQuery {
constructor(client, queryString, params, logger, cache, queryMetadata, cacheConfig, fields, _isResponseInArrayMode, customResultMapper) {
super({ sql: queryString, params }, cache, queryMetadata, cacheConfig);
this.client = client;
this.queryString = queryString;
this.params = params;
this.logger = logger;
this.fields = fields;
this._isResponseInArrayMode = _isResponseInArrayMode;
this.customResultMapper = customResultMapper;
}
static [entityKind] = "PostgresJsPreparedQuery";
async execute(placeholderValues = {}) {
return tracer.startActiveSpan("drizzle.execute", async (span) => {
const params = fillPlaceholders(this.params, placeholderValues);
span?.setAttributes({
"drizzle.query.text": this.queryString,
"drizzle.query.params": JSON.stringify(params)
});
this.logger.logQuery(this.queryString, params);
const { fields, queryString: query, client, joinsNotNullableMap, customResultMapper } = this;
if (!fields && !customResultMapper) {
return tracer.startActiveSpan("drizzle.driver.execute", () => {
return this.queryWithCache(query, params, async () => {
return await client.unsafe(query, params);
});
});
}
const rows = await tracer.startActiveSpan("drizzle.driver.execute", () => {
span?.setAttributes({
"drizzle.query.text": query,
"drizzle.query.params": JSON.stringify(params)
});
return this.queryWithCache(query, params, async () => {
return await client.unsafe(query, params).values();
});
});
return tracer.startActiveSpan("drizzle.mapResponse", () => {
return customResultMapper ? customResultMapper(rows) : rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap));
});
});
}
all(placeholderValues = {}) {
return tracer.startActiveSpan("drizzle.execute", async (span) => {
const params = fillPlaceholders(this.params, placeholderValues);
span?.setAttributes({
"drizzle.query.text": this.queryString,
"drizzle.query.params": JSON.stringify(params)
});
this.logger.logQuery(this.queryString, params);
return tracer.startActiveSpan("drizzle.driver.execute", () => {
span?.setAttributes({
"drizzle.query.text": this.queryString,
"drizzle.query.params": JSON.stringify(params)
});
return this.queryWithCache(this.queryString, params, async () => {
return this.client.unsafe(this.queryString, params);
});
});
});
}
/** @internal */
isResponseInArrayMode() {
return this._isResponseInArrayMode;
}
}
class PostgresJsSession extends PgSession {
constructor(client, dialect, schema, options = {}) {
super(dialect);
this.client = client;
this.schema = schema;
this.options = options;
this.logger = options.logger ?? new NoopLogger();
this.cache = options.cache ?? new NoopCache();
}
static [entityKind] = "PostgresJsSession";
logger;
cache;
prepareQuery(query, fields, name, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) {
return new PostgresJsPreparedQuery(
this.client,
query.sql,
query.params,
this.logger,
this.cache,
queryMetadata,
cacheConfig,
fields,
isResponseInArrayMode,
customResultMapper
);
}
query(query, params) {
this.logger.logQuery(query, params);
return this.client.unsafe(query, params).values();
}
queryObjects(query, params) {
return this.client.unsafe(query, params);
}
transaction(transaction, config) {
return this.client.begin(async (client) => {
const session = new PostgresJsSession(
client,
this.dialect,
this.schema,
this.options
);
const tx = new PostgresJsTransaction(this.dialect, session, this.schema);
if (config) {
await tx.setTransaction(config);
}
return transaction(tx);
});
}
}
class PostgresJsTransaction extends PgTransaction {
constructor(dialect, session, schema, nestedIndex = 0) {
super(dialect, session, schema, nestedIndex);
this.session = session;
}
static [entityKind] = "PostgresJsTransaction";
transaction(transaction) {
return this.session.client.savepoint((client) => {
const session = new PostgresJsSession(
client,
this.dialect,
this.schema,
this.session.options
);
const tx = new PostgresJsTransaction(this.dialect, session, this.schema);
return transaction(tx);
});
}
}
class PostgresJsDatabase extends PgDatabase {
static [entityKind] = "PostgresJsDatabase";
}
function construct(client, config = {}) {
const transparentParser = (val) => val;
for (const type of ["1184", "1082", "1083", "1114", "1182", "1185", "1115", "1231"]) {
client.options.parsers[type] = transparentParser;
client.options.serializers[type] = transparentParser;
}
client.options.serializers["114"] = transparentParser;
client.options.serializers["3802"] = transparentParser;
const dialect = new PgDialect({ casing: config.casing });
let logger;
if (config.logger === true) {
logger = new DefaultLogger();
} else if (config.logger !== false) {
logger = config.logger;
}
let schema;
if (config.schema) {
const tablesConfig = extractTablesRelationalConfig(
config.schema,
createTableRelationsHelpers
);
schema = {
fullSchema: config.schema,
schema: tablesConfig.tables,
tableNamesMap: tablesConfig.tableNamesMap
};
}
const session = new PostgresJsSession(client, dialect, schema, { logger, cache: config.cache });
const db = new PostgresJsDatabase(dialect, session, schema);
db.$client = client;
db.$cache = config.cache;
if (db.$cache) {
db.$cache["invalidate"] = config.cache?.onMutate;
}
return db;
}
function drizzle(...params) {
if (typeof params[0] === "string") {
const instance = pgClient(params[0]);
return construct(instance, params[1]);
}
if (isConfig(params[0])) {
const { connection, client, ...drizzleConfig } = params[0];
if (client) return construct(client, drizzleConfig);
if (typeof connection === "object" && connection.url !== void 0) {
const { url, ...config } = connection;
const instance2 = pgClient(url, config);
return construct(instance2, drizzleConfig);
}
const instance = pgClient(connection);
return construct(instance, drizzleConfig);
}
return construct(params[0], params[1]);
}
((drizzle2) => {
function mock(config) {
return construct({
options: {
parsers: {},
serializers: {}
}
}, config);
}
drizzle2.mock = mock;
})(drizzle || (drizzle = {}));
const user = pgTable("user", {
id: text("id").primaryKey(),
name: text("name").notNull(),
email: text("email").notNull().unique(),
emailVerified: boolean("email_verified").default(false).notNull(),
image: text("image"),
// ── Staff role: 'player' | 'referee' | 'admin' ──
role: text("role").default("player").notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").defaultNow().$onUpdate(() => /* @__PURE__ */ new Date()).notNull()
});
const session = pgTable(
"session",
{
id: text("id").primaryKey(),
expiresAt: timestamp("expires_at").notNull(),
token: text("token").notNull().unique(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").$onUpdate(() => /* @__PURE__ */ new Date()).notNull(),
ipAddress: text("ip_address"),
userAgent: text("user_agent"),
userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" })
},
(table) => [index("session_userId_idx").on(table.userId)]
);
const account = pgTable(
"account",
{
id: text("id").primaryKey(),
accountId: text("account_id").notNull(),
providerId: text("provider_id").notNull(),
userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
accessToken: text("access_token"),
refreshToken: text("refresh_token"),
idToken: text("id_token"),
accessTokenExpiresAt: timestamp("access_token_expires_at"),
refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
scope: text("scope"),
password: text("password"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").$onUpdate(() => /* @__PURE__ */ new Date()).notNull()
},
(table) => [index("account_userId_idx").on(table.userId)]
);
const verification = pgTable(
"verification",
{
id: text("id").primaryKey(),
identifier: text("identifier").notNull(),
value: text("value").notNull(),
expiresAt: timestamp("expires_at").notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").defaultNow().$onUpdate(() => /* @__PURE__ */ new Date()).notNull()
},
(table) => [index("verification_identifier_idx").on(table.identifier)]
);
const userRelations = relations(user, ({ many }) => ({
sessions: many(session),
accounts: many(account)
}));
const sessionRelations = relations(session, ({ one }) => ({
user: one(user, {
fields: [session.userId],
references: [user.id]
})
}));
const accountRelations = relations(account, ({ one }) => ({
user: one(user, {
fields: [account.userId],
references: [user.id]
})
}));
const team = pgTable("team", {
id: uuid("id").primaryKey().defaultRandom(),
name: text("name").notNull(),
isPersonal: boolean("is_personal").default(false).notNull(),
ownerId: text("owner_id"),
avatarUrl: text("avatar_url"),
createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull()
});
const teamMember = pgTable("team_member", {
id: uuid("id").primaryKey().defaultRandom(),
teamId: uuid("team_id").notNull().references(() => team.id, { onDelete: "cascade" }),
userId: text("user_id").notNull(),
role: text("role").default("member"),
joinedAt: timestamp("joined_at", { withTimezone: true }).defaultNow()
});
const mappool = pgTable("mappool", {
id: uuid("id").primaryKey().defaultRandom(),
name: text("name").notNull(),
createdBy: text("created_by"),
createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull()
});
const mappoolSlot = pgTable("mappool_slot", {
id: uuid("id").primaryKey().defaultRandom(),
mappoolId: uuid("mappool_id").notNull().references(() => mappool.id, { onDelete: "cascade" }),
category: text("category").notNull(),
orderInCategory: integer("order_in_category").notNull(),
beatmapId: text("beatmap_id").notNull(),
starRating: real("star_rating"),
mods: text("mods").array().default([]).notNull()
});
const match = pgTable(
"match",
{
id: uuid("id").primaryKey().defaultRandom(),
name: text("name"),
state: text("state").default("CREATED").notNull(),
config: jsonb("config").notNull(),
mappoolId: uuid("mappool_id").references(() => mappool.id),
osuLobbyId: integer("osu_lobby_id"),
scheduledAt: timestamp("scheduled_at", { withTimezone: true }),
startedAt: timestamp("started_at", { withTimezone: true }),
finishedAt: timestamp("finished_at", { withTimezone: true }),
winnerId: uuid("winner_id").references(() => team.id),
createdBy: text("created_by"),
createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull()
},
(t) => [index("idx_match_state").on(t.state)]
);
const matchParticipant = pgTable(
"match_participant",
{
id: uuid("id").primaryKey().defaultRandom(),
matchId: uuid("match_id").notNull().references(() => match.id, { onDelete: "cascade" }),
teamId: uuid("team_id").notNull().references(() => team.id),
slot: integer("slot").notNull(),
score: integer("score").default(0).notNull(),
rollValue: integer("roll_value"),
pickOrder: integer("pick_order")
},
(t) => [
index("idx_mp_match_team").on(t.matchId, t.teamId),
uniqueIndex("idx_mp_match_slot").on(t.matchId, t.slot),
index("idx_mp_match").on(t.matchId)
]
);
const matchParticipantPlayer = pgTable(
"match_participant_player",
{
id: uuid("id").primaryKey().defaultRandom(),
participantId: uuid("participant_id").notNull().references(() => matchParticipant.id, { onDelete: "cascade" }),
userId: text("user_id").notNull()
},
(t) => [
uniqueIndex("idx_mpp_participant_user").on(t.participantId, t.userId),
index("idx_mpp_participant").on(t.participantId)
]
);
const matchGame = pgTable(
"match_game",
{
id: uuid("id").primaryKey().defaultRandom(),
matchId: uuid("match_id").notNull().references(() => match.id, { onDelete: "cascade" }),
gameNumber: integer("game_number").notNull(),
mappoolSlotId: uuid("mappool_slot_id").notNull().references(() => mappoolSlot.id),
pickedByParticipantId: uuid("picked_by_participant_id").references(() => matchParticipant.id),
winnerParticipantId: uuid("winner_participant_id").references(() => matchParticipant.id),
state: text("state").default("PENDING").notNull(),
startedAt: timestamp("started_at", { withTimezone: true }),
finishedAt: timestamp("finished_at", { withTimezone: true })
},
(t) => [index("idx_match_game_match").on(t.matchId)]
);
const matchGameScore = pgTable(
"match_game_score",
{
id: uuid("id").primaryKey().defaultRandom(),
matchGameId: uuid("match_game_id").notNull().references(() => matchGame.id, { onDelete: "cascade" }),
playerId: uuid("player_id").notNull().references(() => matchParticipantPlayer.id),
score: integer("score").default(0).notNull(),
accuracy: real("accuracy").default(0).notNull(),
maxCombo: integer("max_combo").default(0).notNull(),
count300: integer("count_300").default(0).notNull(),
count100: integer("count_100").default(0).notNull(),
count50: integer("count_50").default(0).notNull(),
countMiss: integer("count_miss").default(0).notNull(),
mods: text("mods").array().default([]).notNull(),
passed: boolean("passed").default(false).notNull()
},
(t) => [index("idx_mgs_game").on(t.matchGameId)]
);
const matchQueue = pgTable(
"match_queue",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: text("user_id").notNull(),
teamId: uuid("team_id").notNull().references(() => team.id),
elo: integer("elo").default(1e3).notNull(),
joinedAt: timestamp("joined_at", { withTimezone: true }).defaultNow().notNull()
},
(t) => [
uniqueIndex("idx_queue_user").on(t.userId),
index("idx_queue_elo").on(t.elo)
]
);
const playerRating = pgTable("player_rating", {
id: uuid("id").primaryKey().defaultRandom(),
userId: text("user_id").notNull().unique(),
elo: integer("elo").default(1e3).notNull(),
wins: integer("wins").default(0).notNull(),
losses: integer("losses").default(0).notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull()
});
const teamRelations = relations(team, ({ many }) => ({
members: many(teamMember)
}));
const teamMemberRelations = relations(teamMember, ({ one }) => ({
team: one(team, { fields: [teamMember.teamId], references: [team.id] })
}));
const mappoolRelations = relations(mappool, ({ many }) => ({
slots: many(mappoolSlot)
}));
const mappoolSlotRelations = relations(mappoolSlot, ({ one }) => ({
mappool: one(mappool, { fields: [mappoolSlot.mappoolId], references: [mappool.id] })
}));
const matchRelations = relations(match, ({ one, many }) => ({
mappool: one(mappool, { fields: [match.mappoolId], references: [mappool.id] }),
participants: many(matchParticipant),
games: many(matchGame)
}));
const matchParticipantRelations = relations(matchParticipant, ({ one, many }) => ({
match: one(match, { fields: [matchParticipant.matchId], references: [match.id] }),
team: one(team, { fields: [matchParticipant.teamId], references: [team.id] }),
players: many(matchParticipantPlayer)
}));
const matchParticipantPlayerRelations = relations(matchParticipantPlayer, ({ one }) => ({
participant: one(matchParticipant, {
fields: [matchParticipantPlayer.participantId],
references: [matchParticipant.id]
})
}));
const matchGameRelations = relations(matchGame, ({ one, many }) => ({
match: one(match, { fields: [matchGame.matchId], references: [match.id] }),
slot: one(mappoolSlot, { fields: [matchGame.mappoolSlotId], references: [mappoolSlot.id] }),
scores: many(matchGameScore)
}));
const matchGameScoreRelations = relations(matchGameScore, ({ one }) => ({
game: one(matchGame, { fields: [matchGameScore.matchGameId], references: [matchGame.id] }),
player: one(matchParticipantPlayer, {
fields: [matchGameScore.playerId],
references: [matchParticipantPlayer.id]
})
}));
const matchQueueRelations = relations(matchQueue, ({ one }) => ({
team: one(team, { fields: [matchQueue.teamId], references: [team.id] })
}));
const schema = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
account,
accountRelations,
mappool,
mappoolRelations,
mappoolSlot,
mappoolSlotRelations,
match,
matchGame,
matchGameRelations,
matchGameScore,
matchGameScoreRelations,
matchParticipant,
matchParticipantPlayer,
matchParticipantPlayerRelations,
matchParticipantRelations,
matchQueue,
matchQueueRelations,
matchRelations,
playerRating,
session,
sessionRelations,
team,
teamMember,
teamMemberRelations,
teamRelations,
user,
userRelations,
verification
}, Symbol.toStringTag, { value: "Module" }));
if (!private_env.DATABASE_URL) throw new Error("DATABASE_URL is not set");
const client = pgClient(private_env.DATABASE_URL);
const db = drizzle(client, { schema });
export { matchGameScore as A, matchQueue as B, desc as a, mappool as b, mappoolSlot as c, db as d, eq as e, and as f, matchGame as g, account as h, inArray as i, teamMember as j, asc as k, like as l, match as m, notInArray as n, lt as o, playerRating as p, lte as q, ne as r, gt as s, team as t, user as u, gte as v, or as w, sql as x, matchParticipant as y, matchParticipantPlayer as z };
//# sourceMappingURL=index2-B7hVh_Qf.js.map