🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@prisma-next/sql-relational-core

Package Overview
Dependencies
Maintainers
4
Versions
898
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@prisma-next/sql-relational-core - npm Package Compare versions

Comparing version
0.14.0-dev.18
to
0.14.0-dev.19
+1308
dist/types-CaGVAsoT.mjs
import { ifDefined } from "@prisma-next/utils/defined";
//#region src/ast/types.ts
function frozenArrayCopy(values) {
return Object.freeze([...values]);
}
function frozenOptionalRecordCopy(value) {
return value === void 0 ? void 0 : Object.freeze({ ...value });
}
function frozenRecordCopy(record) {
return Object.freeze({ ...record });
}
function frozenCodecRef(codec) {
const typeParams = codec.typeParams === void 0 ? void 0 : structuredClone(codec.typeParams);
const base = typeParams === void 0 ? { codecId: codec.codecId } : {
codecId: codec.codecId,
typeParams
};
return Object.freeze(codec.many ? {
...base,
many: true
} : base);
}
function freezeRows(rows) {
return Object.freeze(rows.map((row) => Object.freeze({ ...row })));
}
function combineAll(folder, thunks) {
let result = folder.empty;
for (const thunk of thunks) {
if (folder.isAbsorbing?.(result)) return result;
result = folder.combine(result, thunk());
}
return result;
}
function rewriteComparable(value, rewriter) {
switch (value.kind) {
case "param-ref": return rewriter.paramRef ? rewriter.paramRef(value) : value;
case "prepared-param-ref": return rewriter.preparedParamRef ? rewriter.preparedParamRef(value) : value;
case "literal": return rewriter.literal ? rewriter.literal(value) : value;
case "list":
if (rewriter.list) return rewriter.list(value);
return value.rewrite(rewriter);
default: return value.rewrite(rewriter);
}
}
function foldComparable(value, folder) {
switch (value.kind) {
case "param-ref": return folder.paramRef ? folder.paramRef(value) : folder.empty;
case "prepared-param-ref": return folder.preparedParamRef ? folder.preparedParamRef(value) : folder.empty;
case "literal": return folder.literal ? folder.literal(value) : folder.empty;
case "list": return value.fold(folder);
default: return value.fold(folder);
}
}
function collectColumnRefsWith(node) {
return node.fold({
empty: [],
combine: (a, b) => [...a, ...b],
columnRef: (columnRef) => [columnRef],
select: (ast) => ast.collectColumnRefs()
});
}
function collectParamRefsWith(node) {
return node.fold({
empty: [],
combine: (a, b) => [...a, ...b],
paramRef: (paramRef) => [paramRef],
preparedParamRef: (paramRef) => [paramRef],
select: (ast) => ast.collectParamRefs()
});
}
function rewriteTableSource(table, rewriter) {
return rewriter.tableSource ? rewriter.tableSource(table) : table;
}
function rewriteProjectionItem(item, rewriter) {
const rewrittenExpr = item.expr.kind === "literal" ? rewriter.literal ? rewriter.literal(item.expr) : item.expr : item.expr.rewrite(rewriter);
return new ProjectionItem(item.alias, rewrittenExpr, item.codec);
}
function rewriteInsertValue(value, rewriter) {
switch (value.kind) {
case "param-ref": return rewriter.paramRef ? rewriteParamRefForInsert(value, rewriter) : value;
case "prepared-param-ref": return rewriter.preparedParamRef ? rewriter.preparedParamRef(value) : value;
case "column-ref": return rewriter.columnRef ? rewriteColumnRefForInsert(value, rewriter) : value;
case "default-value": return value;
case "raw-expr": return value;
}
}
function rewriteParamRefForInsert(value, rewriter) {
const rewritten = rewriter.paramRef ? rewriter.paramRef(value) : value;
return rewritten.kind === "param-ref" ? rewritten : value;
}
function rewriteColumnRefForInsert(value, rewriter) {
const rewritten = rewriter.columnRef ? rewriter.columnRef(value) : value;
return rewritten.kind === "column-ref" ? rewritten : value;
}
function rewriteInsertRow(row, rewriter) {
const result = {};
for (const [key, value] of Object.entries(row)) result[key] = rewriteInsertValue(value, rewriter);
return result;
}
function rewriteUpdateSet(set, rewriter) {
const result = {};
for (const [key, value] of Object.entries(set)) result[key] = value.rewrite(rewriter);
return result;
}
function rewriteLimitOffset(value, rewriter) {
if (value === void 0 || typeof value === "number") return value;
return value.rewrite(rewriter);
}
function rewriteOnConflict(onConflict, rewriter) {
const columns = onConflict.columns.map((columnRef) => {
const rewritten = rewriter.columnRef ? rewriter.columnRef(columnRef) : columnRef;
return rewritten.kind === "column-ref" ? rewritten : columnRef;
});
if (onConflict.action.kind === "do-nothing") return new InsertOnConflict(columns, new DoNothingConflictAction());
return new InsertOnConflict(columns, new DoUpdateSetConflictAction(rewriteUpdateSet(onConflict.action.set, rewriter)));
}
var AstNode = class {
freeze() {
Object.freeze(this);
}
};
var QueryAst = class extends AstNode {};
var FromSource = class extends AstNode {};
var Expression = class extends AstNode {
collectColumnRefs() {
return collectColumnRefsWith(this);
}
collectParamRefs() {
return collectParamRefsWith(this);
}
baseColumnRef() {
throw new Error(`${this.constructor.name} does not expose a base column reference`);
}
toExpr() {
return this;
}
not() {
return new NotExpr(this);
}
};
var TableSource = class TableSource extends FromSource {
kind = "table-source";
name;
alias;
/**
* Resolved storage namespace coordinate for this table, stamped when the
* table proxy constructs the AST. Renderers qualify via the namespace
* concretion's `qualifyTable()` using this id — never by re-resolving the
* bare table name at render time.
*/
namespaceId;
constructor(name, alias, namespaceId) {
super();
this.name = name;
this.alias = alias;
this.namespaceId = namespaceId;
}
static named(name, alias, namespaceId) {
const source = new TableSource(name, alias, namespaceId);
source.freeze();
return source;
}
rewrite(rewriter) {
return rewriter.tableSource ? rewriter.tableSource(this) : this;
}
toFromSource() {
return this;
}
};
var DerivedTableSource = class DerivedTableSource extends FromSource {
kind = "derived-table-source";
alias;
query;
constructor(alias, query) {
super();
this.alias = alias;
this.query = query;
this.freeze();
}
static as(alias, query) {
return new DerivedTableSource(alias, query);
}
rewrite(rewriter) {
return new DerivedTableSource(this.alias, this.query.rewrite(rewriter));
}
toFromSource() {
return this;
}
};
var FunctionSource = class FunctionSource extends FromSource {
kind = "function-source";
fn;
args;
alias;
constructor(fn, args, alias) {
super();
this.fn = fn;
this.args = frozenArrayCopy(args);
this.alias = alias;
this.freeze();
}
static of(fn, args, alias) {
return new FunctionSource(fn, args, alias);
}
rewrite(rewriter) {
const rewrittenArgs = this.args.map((arg) => rewriteComparable(arg, rewriter));
if (rewrittenArgs.every((arg, i) => arg === this.args[i])) return this;
return new FunctionSource(this.fn, rewrittenArgs, this.alias);
}
toFromSource() {
return this;
}
};
var ColumnRef = class ColumnRef extends Expression {
kind = "column-ref";
table;
column;
constructor(table, column) {
super();
this.table = table;
this.column = column;
this.freeze();
}
static of(table, column) {
return new ColumnRef(table, column);
}
accept(visitor) {
return visitor.columnRef(this);
}
rewrite(rewriter) {
return rewriter.columnRef ? rewriter.columnRef(this) : this;
}
fold(folder) {
return folder.columnRef ? folder.columnRef(this) : folder.empty;
}
baseColumnRef() {
return this;
}
};
var IdentifierRef = class IdentifierRef extends Expression {
kind = "identifier-ref";
name;
constructor(name) {
super();
this.name = name;
this.freeze();
}
static of(name) {
return new IdentifierRef(name);
}
accept(visitor) {
return visitor.identifierRef(this);
}
rewrite(rewriter) {
return rewriter.identifierRef ? rewriter.identifierRef(this) : this;
}
fold(folder) {
return folder.identifierRef ? folder.identifierRef(this) : folder.empty;
}
};
var ParamRef = class ParamRef extends Expression {
kind = "param-ref";
value;
name;
/**
* Codec identity carried by every column-bound `ParamRef`. The encode-side dispatch path materialises the per-instance codec through `contractCodecs.forCodecRef(codec)` — content-keyed memoisation on `(codecId, canonicalize(typeParams))` keeps repeated lookups for the same logical column on one shared {@link Codec}.
*
* `codec` may be `undefined` for `ParamRef`s constructed without a column-bound site (literals, transient builder state); the runtime treats those as untyped passthroughs.
*/
codec;
constructor(value, options) {
super();
this.value = value;
this.name = options?.name;
this.codec = options?.codec ? frozenCodecRef(options.codec) : void 0;
this.freeze();
}
static of(value, options) {
return new ParamRef(value, options);
}
accept(visitor) {
return visitor.param(this);
}
rewrite(rewriter) {
return rewriter.paramRef ? rewriter.paramRef(this) : this;
}
fold(folder) {
return folder.paramRef ? folder.paramRef(this) : folder.empty;
}
};
/**
* Bind-site placeholder: occupies the same positions as `ParamRef` in the
* AST, but carries no value — the value is supplied per-execute by the
* `PreparedStatement.execute(params)` caller and matched to this node by
* `name`.
*/
var PreparedParamRef = class PreparedParamRef extends Expression {
kind = "prepared-param-ref";
name;
codec;
constructor(name, codec) {
super();
this.name = name;
this.codec = frozenCodecRef(codec);
this.freeze();
}
static of(name, codec) {
return new PreparedParamRef(name, codec);
}
accept(visitor) {
return visitor.preparedParam(this);
}
rewrite(rewriter) {
return rewriter.preparedParamRef ? rewriter.preparedParamRef(this) : this;
}
fold(folder) {
return folder.preparedParamRef ? folder.preparedParamRef(this) : folder.empty;
}
};
var DefaultValueExpr = class extends AstNode {
kind = "default-value";
constructor() {
super();
this.freeze();
}
};
var LiteralExpr = class LiteralExpr extends Expression {
kind = "literal";
value;
constructor(value) {
super();
this.value = value;
this.freeze();
}
static of(value) {
return new LiteralExpr(value);
}
accept(visitor) {
return visitor.literal(this);
}
rewrite(rewriter) {
return rewriter.literal ? rewriter.literal(this) : this;
}
fold(folder) {
return folder.literal ? folder.literal(this) : folder.empty;
}
};
var SubqueryExpr = class SubqueryExpr extends Expression {
kind = "subquery";
query;
constructor(query) {
super();
this.query = query;
this.freeze();
}
static of(query) {
return new SubqueryExpr(query);
}
accept(visitor) {
return visitor.subquery(this);
}
rewrite(rewriter) {
return new SubqueryExpr(this.query.rewrite(rewriter));
}
fold(folder) {
return folder.select ? folder.select(this.query) : folder.empty;
}
};
var OperationExpr = class OperationExpr extends Expression {
kind = "operation";
method;
self;
args;
returns;
lowering;
constructor(options) {
super();
this.method = options.method;
this.self = options.self;
this.args = frozenArrayCopy(options.args ?? []);
this.returns = options.returns;
this.lowering = options.lowering;
this.freeze();
}
accept(visitor) {
return visitor.operation(this);
}
rewrite(rewriter) {
return new OperationExpr({
method: this.method,
self: this.self.rewrite(rewriter),
args: this.args.map((arg) => rewriteComparable(arg, rewriter)),
returns: this.returns,
lowering: this.lowering
});
}
fold(folder) {
return combineAll(folder, [() => this.self.fold(folder), ...this.args.map((arg) => () => foldComparable(arg, folder))]);
}
baseColumnRef() {
return this.self.baseColumnRef();
}
};
var RawExpr = class extends Expression {
kind = "raw-expr";
parts;
returns;
constructor(options) {
super();
this.parts = frozenArrayCopy(options.parts);
this.returns = options.returns;
this.freeze();
}
accept(visitor) {
return visitor.rawExpr(this);
}
rewrite(rewriter) {
return rewriter.rawExpr ? rewriter.rawExpr(this) : this;
}
fold(folder) {
if (folder.rawExpr) return folder.rawExpr(this);
return combineAll(folder, this.parts.filter((p) => typeof p !== "string").map((p) => () => p.fold(folder)));
}
};
var AggregateExpr = class AggregateExpr extends Expression {
kind = "aggregate";
fn;
expr;
constructor(fn, expr) {
super();
if (fn !== "count" && expr === void 0) throw new Error(`Aggregate function "${fn}" requires an expression`);
this.fn = fn;
this.expr = expr;
this.freeze();
}
static count(expr) {
return new AggregateExpr("count", expr);
}
static sum(expr) {
return new AggregateExpr("sum", expr);
}
static avg(expr) {
return new AggregateExpr("avg", expr);
}
static min(expr) {
return new AggregateExpr("min", expr);
}
static max(expr) {
return new AggregateExpr("max", expr);
}
accept(visitor) {
return visitor.aggregate(this);
}
rewrite(rewriter) {
return this.expr === void 0 ? this : new AggregateExpr(this.fn, this.expr.rewrite(rewriter));
}
fold(folder) {
return this.expr ? this.expr.fold(folder) : folder.empty;
}
};
/**
* Window function call: `fn(args) OVER (PARTITION BY ... ORDER BY ...)`.
*
* Both `partitionBy` and `orderBy` are optional; an empty `OVER ()`
* clause is legal SQL but rarely useful. For `ROW_NUMBER`, `RANK`, and
* `DENSE_RANK` the standard mandates an `ORDER BY` for deterministic
* results — callers are expected to provide one, but the AST does not
* enforce it.
*
* The `args` slot exists for future window function additions that take
* arguments (e.g. `COUNT(*) OVER`, `SUM(x) OVER`); `ROW_NUMBER` and the
* other ranking functions take no arguments.
*/
var WindowFuncExpr = class WindowFuncExpr extends Expression {
kind = "window-func";
fn;
args;
partitionBy;
orderBy;
constructor(options) {
super();
this.fn = options.fn;
this.args = options.args && options.args.length > 0 ? frozenArrayCopy(options.args) : [];
this.partitionBy = options.partitionBy && options.partitionBy.length > 0 ? frozenArrayCopy(options.partitionBy) : void 0;
this.orderBy = options.orderBy && options.orderBy.length > 0 ? frozenArrayCopy(options.orderBy) : void 0;
this.freeze();
}
static rowNumber(options) {
return new WindowFuncExpr({
fn: "row_number",
...options
});
}
accept(visitor) {
return visitor.windowFunc(this);
}
rewrite(rewriter) {
return new WindowFuncExpr({
fn: this.fn,
args: this.args.map((arg) => arg.rewrite(rewriter)),
...ifDefined("partitionBy", this.partitionBy?.map((expr) => expr.rewrite(rewriter))),
...ifDefined("orderBy", this.orderBy?.map((orderItem) => orderItem.rewrite(rewriter)))
});
}
fold(folder) {
return combineAll(folder, [
...this.args.map((arg) => () => arg.fold(folder)),
...(this.partitionBy ?? []).map((expr) => () => expr.fold(folder)),
...(this.orderBy ?? []).map((orderItem) => () => orderItem.expr.fold(folder))
]);
}
};
var JsonObjectExpr = class JsonObjectExpr extends Expression {
kind = "json-object";
entries;
constructor(entries) {
super();
this.entries = frozenArrayCopy(entries.map((entry) => Object.freeze({ ...entry })));
this.freeze();
}
static entry(key, value) {
return {
key,
value
};
}
static fromEntries(entries) {
return new JsonObjectExpr(entries);
}
accept(visitor) {
return visitor.jsonObject(this);
}
rewrite(rewriter) {
return new JsonObjectExpr(this.entries.map((entry) => ({
key: entry.key,
value: entry.value.kind === "literal" ? rewriter.literal ? rewriter.literal(entry.value) : entry.value : entry.value.rewrite(rewriter)
})));
}
fold(folder) {
return combineAll(folder, this.entries.map((entry) => () => entry.value.kind === "literal" ? folder.literal ? folder.literal(entry.value) : folder.empty : entry.value.fold(folder)));
}
};
var OrderByItem = class OrderByItem extends AstNode {
kind = "order-by-item";
expr;
dir;
constructor(expr, dir) {
super();
this.expr = expr;
this.dir = dir;
this.freeze();
}
static asc(expr) {
return new OrderByItem(expr, "asc");
}
static desc(expr) {
return new OrderByItem(expr, "desc");
}
rewrite(rewriter) {
return new OrderByItem(this.expr.rewrite(rewriter), this.dir);
}
/**
* A new frozen item with the sort direction flipped and `expr` unchanged.
* Integrations that own pagination (e.g. backward cursor pagination) use
* this to reverse a user's sort order without reaching into the AST.
*/
reverse() {
return new OrderByItem(this.expr, this.dir === "asc" ? "desc" : "asc");
}
};
var JsonArrayAggExpr = class JsonArrayAggExpr extends Expression {
kind = "json-array-agg";
expr;
onEmpty;
orderBy;
constructor(expr, onEmpty = "null", orderBy) {
super();
this.expr = expr;
this.onEmpty = onEmpty;
this.orderBy = orderBy && orderBy.length > 0 ? frozenArrayCopy(orderBy) : void 0;
this.freeze();
}
static of(expr, onEmpty = "null", orderBy) {
return new JsonArrayAggExpr(expr, onEmpty, orderBy);
}
accept(visitor) {
return visitor.jsonArrayAgg(this);
}
rewrite(rewriter) {
return new JsonArrayAggExpr(this.expr.rewrite(rewriter), this.onEmpty, this.orderBy?.map((orderItem) => orderItem.rewrite(rewriter)));
}
fold(folder) {
return combineAll(folder, [() => this.expr.fold(folder), ...(this.orderBy ?? []).map((orderItem) => () => orderItem.expr.fold(folder))]);
}
};
var ListExpression = class ListExpression extends Expression {
kind = "list";
values;
constructor(values) {
super();
this.values = frozenArrayCopy(values);
this.freeze();
}
static of(values) {
return new ListExpression(values);
}
static fromValues(values) {
return new ListExpression(values.map((value) => new LiteralExpr(value)));
}
accept(visitor) {
return visitor.list(this);
}
rewrite(rewriter) {
if (rewriter.list) return rewriter.list(this);
return new ListExpression(this.values.map((value) => value.rewrite(rewriter)));
}
fold(folder) {
if (folder.list) return folder.list(this);
return combineAll(folder, this.values.map((value) => () => value.fold(folder)));
}
};
var BinaryExpr = class BinaryExpr extends Expression {
kind = "binary";
op;
left;
right;
constructor(op, left, right) {
super();
this.op = op;
this.left = left;
this.right = right;
this.freeze();
}
static eq(left, right) {
return new BinaryExpr("eq", left, right);
}
static neq(left, right) {
return new BinaryExpr("neq", left, right);
}
static gt(left, right) {
return new BinaryExpr("gt", left, right);
}
static lt(left, right) {
return new BinaryExpr("lt", left, right);
}
static gte(left, right) {
return new BinaryExpr("gte", left, right);
}
static lte(left, right) {
return new BinaryExpr("lte", left, right);
}
static like(left, right) {
return new BinaryExpr("like", left, right);
}
static in(left, right) {
return new BinaryExpr("in", left, right);
}
static notIn(left, right) {
return new BinaryExpr("notIn", left, right);
}
accept(visitor) {
return visitor.binary(this);
}
rewrite(rewriter) {
return new BinaryExpr(this.op, rewriteComparable(this.left, rewriter), rewriteComparable(this.right, rewriter));
}
fold(folder) {
return combineAll(folder, [() => foldComparable(this.left, folder), () => foldComparable(this.right, folder)]);
}
};
var AndExpr = class AndExpr extends Expression {
kind = "and";
exprs;
constructor(exprs) {
super();
this.exprs = frozenArrayCopy(exprs);
this.freeze();
}
static of(exprs) {
return new AndExpr(exprs);
}
static true() {
return new AndExpr([]);
}
accept(visitor) {
return visitor.and(this);
}
rewrite(rewriter) {
return new AndExpr(this.exprs.map((expr) => expr.rewrite(rewriter)));
}
fold(folder) {
return combineAll(folder, this.exprs.map((expr) => () => expr.fold(folder)));
}
};
var OrExpr = class OrExpr extends Expression {
kind = "or";
exprs;
constructor(exprs) {
super();
this.exprs = frozenArrayCopy(exprs);
this.freeze();
}
static of(exprs) {
return new OrExpr(exprs);
}
static false() {
return new OrExpr([]);
}
accept(visitor) {
return visitor.or(this);
}
rewrite(rewriter) {
return new OrExpr(this.exprs.map((expr) => expr.rewrite(rewriter)));
}
fold(folder) {
return combineAll(folder, this.exprs.map((expr) => () => expr.fold(folder)));
}
};
var ExistsExpr = class ExistsExpr extends Expression {
kind = "exists";
notExists;
subquery;
constructor(subquery, notExists = false) {
super();
this.notExists = notExists;
this.subquery = subquery;
this.freeze();
}
static exists(subquery) {
return new ExistsExpr(subquery, false);
}
static notExists(subquery) {
return new ExistsExpr(subquery, true);
}
accept(visitor) {
return visitor.exists(this);
}
rewrite(rewriter) {
return new ExistsExpr(this.subquery.rewrite(rewriter), this.notExists);
}
fold(folder) {
return folder.select ? folder.select(this.subquery) : folder.empty;
}
};
var NullCheckExpr = class NullCheckExpr extends Expression {
kind = "null-check";
expr;
isNull;
constructor(expr, isNull) {
super();
this.expr = expr;
this.isNull = isNull;
this.freeze();
}
static isNull(expr) {
return new NullCheckExpr(expr, true);
}
static isNotNull(expr) {
return new NullCheckExpr(expr, false);
}
accept(visitor) {
return visitor.nullCheck(this);
}
rewrite(rewriter) {
return new NullCheckExpr(this.expr.rewrite(rewriter), this.isNull);
}
fold(folder) {
return this.expr.fold(folder);
}
};
var NotExpr = class NotExpr extends Expression {
kind = "not";
expr;
constructor(expr) {
super();
this.expr = expr;
this.freeze();
}
toWhereExpr() {
return this;
}
accept(visitor) {
return visitor.not(this);
}
rewrite(rewriter) {
return new NotExpr(this.expr.rewrite(rewriter));
}
fold(folder) {
return this.expr.fold(folder);
}
};
var EqColJoinOn = class EqColJoinOn extends AstNode {
kind = "eq-col-join-on";
left;
right;
constructor(left, right) {
super();
this.left = left;
this.right = right;
this.freeze();
}
static of(left, right) {
return new EqColJoinOn(left, right);
}
rewrite(rewriter) {
return rewriter.eqColJoinOn ? rewriter.eqColJoinOn(this) : this;
}
};
var JoinAst = class JoinAst extends AstNode {
kind = "join";
joinType;
source;
lateral;
on;
constructor(joinType, source, on, lateral = false) {
super();
this.joinType = joinType;
this.source = source;
this.lateral = lateral;
this.on = on;
this.freeze();
}
static inner(source, on, lateral = false) {
return new JoinAst("inner", source, on, lateral);
}
static left(source, on, lateral = false) {
return new JoinAst("left", source, on, lateral);
}
static right(source, on, lateral = false) {
return new JoinAst("right", source, on, lateral);
}
static full(source, on, lateral = false) {
return new JoinAst("full", source, on, lateral);
}
rewrite(rewriter) {
return new JoinAst(this.joinType, this.source.rewrite(rewriter), this.on.kind === "eq-col-join-on" ? this.on.rewrite(rewriter) : this.on.rewrite(rewriter), this.lateral);
}
};
var ProjectionItem = class ProjectionItem extends AstNode {
kind = "projection-item";
alias;
expr;
/**
* Codec identity for the projected cell. Decode-side dispatch resolves the per-instance codec through `contractCodecs.forCodecRef(codec)` — content-keyed memoisation collapses repeated lookups for the same logical column onto one shared {@link Codec}.
*
* Stays `undefined` for non-column-bound projections (computed expressions, subqueries, raw aliases) whose decoded type the runtime cannot infer from a single contract column.
*/
codec;
constructor(alias, expr, codec) {
super();
this.alias = alias;
this.expr = expr;
this.codec = codec ? frozenCodecRef(codec) : void 0;
this.freeze();
}
static of(alias, expr, codec) {
return new ProjectionItem(alias, expr, codec);
}
withCodec(codec) {
return new ProjectionItem(this.alias, this.expr, codec);
}
};
var SelectAst = class SelectAst extends QueryAst {
kind = "select";
from;
joins;
projection;
where;
orderBy;
distinct;
distinctOn;
groupBy;
having;
limit;
offset;
selectAllIntent;
constructor(options) {
super();
this.from = options.from;
this.joins = options.joins && options.joins.length > 0 ? frozenArrayCopy(options.joins) : void 0;
this.projection = frozenArrayCopy(options.projection);
this.where = options.where;
this.orderBy = options.orderBy && options.orderBy.length > 0 ? frozenArrayCopy(options.orderBy) : void 0;
this.distinct = options.distinct;
this.distinctOn = options.distinctOn && options.distinctOn.length > 0 ? frozenArrayCopy(options.distinctOn) : void 0;
this.groupBy = options.groupBy && options.groupBy.length > 0 ? frozenArrayCopy(options.groupBy) : void 0;
this.having = options.having;
this.limit = options.limit;
this.offset = options.offset;
this.selectAllIntent = frozenOptionalRecordCopy(options.selectAllIntent);
this.freeze();
}
static from(from) {
return new SelectAst({
from,
joins: void 0,
projection: [],
where: void 0,
orderBy: void 0,
distinct: void 0,
distinctOn: void 0,
groupBy: void 0,
having: void 0,
limit: void 0,
offset: void 0,
selectAllIntent: void 0
});
}
static noFrom() {
return new SelectAst({
joins: void 0,
projection: [],
where: void 0,
orderBy: void 0,
distinct: void 0,
distinctOn: void 0,
groupBy: void 0,
having: void 0,
limit: void 0,
offset: void 0,
selectAllIntent: void 0
});
}
toOptions() {
return {
...this.from !== void 0 ? { from: this.from } : {},
joins: this.joins,
projection: this.projection,
where: this.where,
orderBy: this.orderBy,
distinct: this.distinct,
distinctOn: this.distinctOn,
groupBy: this.groupBy,
having: this.having,
limit: this.limit,
offset: this.offset,
selectAllIntent: this.selectAllIntent
};
}
withFrom(from) {
return new SelectAst({
...this.toOptions(),
from
});
}
withJoins(joins) {
return new SelectAst({
...this.toOptions(),
joins: joins.length > 0 ? joins : void 0
});
}
withProjection(projection) {
return new SelectAst({
...this.toOptions(),
projection
});
}
addProjection(alias, expr) {
return new SelectAst({
...this.toOptions(),
projection: [...this.projection, new ProjectionItem(alias, expr)]
});
}
withWhere(where) {
return new SelectAst({
...this.toOptions(),
where
});
}
withOrderBy(orderBy) {
return new SelectAst({
...this.toOptions(),
orderBy: orderBy.length > 0 ? orderBy : void 0
});
}
withDistinct(enabled = true) {
return new SelectAst({
...this.toOptions(),
distinct: enabled ? true : void 0
});
}
withDistinctOn(distinctOn) {
return new SelectAst({
...this.toOptions(),
distinctOn: distinctOn.length > 0 ? distinctOn : void 0
});
}
withGroupBy(groupBy) {
return new SelectAst({
...this.toOptions(),
groupBy: groupBy.length > 0 ? groupBy : void 0
});
}
withHaving(having) {
return new SelectAst({
...this.toOptions(),
having
});
}
withLimit(limit) {
return new SelectAst({
...this.toOptions(),
limit
});
}
withOffset(offset) {
return new SelectAst({
...this.toOptions(),
offset
});
}
withSelectAllIntent(selectAllIntent) {
return new SelectAst({
...this.toOptions(),
selectAllIntent
});
}
rewrite(rewriter) {
const rewrittenFrom = this.from?.rewrite(rewriter);
const rewritten = new SelectAst({
...rewrittenFrom !== void 0 ? { from: rewrittenFrom } : {},
joins: this.joins?.map((join) => join.rewrite(rewriter)),
projection: this.projection.map((projection) => new ProjectionItem(projection.alias, projection.expr.kind === "literal" ? rewriter.literal ? rewriter.literal(projection.expr) : projection.expr : projection.expr.rewrite(rewriter), projection.codec)),
where: this.where?.rewrite(rewriter),
orderBy: this.orderBy?.map((orderItem) => orderItem.rewrite(rewriter)),
distinct: this.distinct,
distinctOn: this.distinctOn?.map((expr) => expr.rewrite(rewriter)),
groupBy: this.groupBy?.map((expr) => expr.rewrite(rewriter)),
having: this.having?.rewrite(rewriter),
limit: rewriteLimitOffset(this.limit, rewriter),
offset: rewriteLimitOffset(this.offset, rewriter),
selectAllIntent: this.selectAllIntent
});
return rewriter.select ? rewriter.select(rewritten) : rewritten;
}
collectColumnRefs() {
const refs = [];
const pushRefs = (columns) => {
refs.push(...columns);
};
if (this.from?.kind === "derived-table-source") pushRefs(this.from.query.collectColumnRefs());
else if (this.from?.kind === "function-source") for (const arg of this.from.args) pushRefs(arg.collectColumnRefs());
for (const projection of this.projection) if (!(projection.expr.kind === "literal")) pushRefs(projection.expr.collectColumnRefs());
if (this.where) pushRefs(this.where.collectColumnRefs());
if (this.having) pushRefs(this.having.collectColumnRefs());
for (const orderItem of this.orderBy ?? []) pushRefs(orderItem.expr.collectColumnRefs());
for (const expr of this.distinctOn ?? []) pushRefs(expr.collectColumnRefs());
for (const expr of this.groupBy ?? []) pushRefs(expr.collectColumnRefs());
for (const join of this.joins ?? []) {
if (join.source.kind === "derived-table-source") pushRefs(join.source.query.collectColumnRefs());
else if (join.source.kind === "function-source") for (const arg of join.source.args) pushRefs(arg.collectColumnRefs());
if (join.on.kind === "eq-col-join-on") refs.push(join.on.left, join.on.right);
else pushRefs(join.on.collectColumnRefs());
}
if (typeof this.limit === "object") pushRefs(this.limit.collectColumnRefs());
if (typeof this.offset === "object") pushRefs(this.offset.collectColumnRefs());
return refs;
}
collectParamRefs() {
const refs = [];
const pushRefs = (params) => {
refs.push(...params);
};
if (this.from?.kind === "derived-table-source") pushRefs(this.from.query.collectParamRefs());
else if (this.from?.kind === "function-source") for (const arg of this.from.args) pushRefs(arg.collectParamRefs());
for (const projection of this.projection) if (!(projection.expr.kind === "literal")) pushRefs(projection.expr.collectParamRefs());
if (this.where) pushRefs(this.where.collectParamRefs());
if (this.having) pushRefs(this.having.collectParamRefs());
for (const orderItem of this.orderBy ?? []) pushRefs(orderItem.expr.collectParamRefs());
for (const expr of this.distinctOn ?? []) pushRefs(expr.collectParamRefs());
for (const expr of this.groupBy ?? []) pushRefs(expr.collectParamRefs());
for (const join of this.joins ?? []) {
if (join.source.kind === "derived-table-source") pushRefs(join.source.query.collectParamRefs());
else if (join.source.kind === "function-source") for (const arg of join.source.args) pushRefs(arg.collectParamRefs());
if (!(join.on.kind === "eq-col-join-on")) pushRefs(join.on.collectParamRefs());
}
if (typeof this.limit === "object") pushRefs(this.limit.collectParamRefs());
if (typeof this.offset === "object") pushRefs(this.offset.collectParamRefs());
return refs;
}
toQueryAst() {
return this;
}
};
var InsertOnConflictAction = class extends AstNode {};
var DoNothingConflictAction = class extends InsertOnConflictAction {
kind = "do-nothing";
constructor() {
super();
this.freeze();
}
toInsertOnConflictAction() {
return this;
}
};
var DoUpdateSetConflictAction = class extends InsertOnConflictAction {
kind = "do-update-set";
set;
constructor(set) {
super();
this.set = frozenRecordCopy(set);
this.freeze();
}
toInsertOnConflictAction() {
return this;
}
};
var InsertOnConflict = class InsertOnConflict extends AstNode {
kind = "insert-on-conflict";
columns;
action;
constructor(columns, action) {
super();
this.columns = frozenArrayCopy(columns);
this.action = action;
this.freeze();
}
static on(columns) {
return new InsertOnConflict(columns, new DoNothingConflictAction());
}
doNothing() {
return new InsertOnConflict(this.columns, new DoNothingConflictAction());
}
doUpdateSet(set) {
return new InsertOnConflict(this.columns, new DoUpdateSetConflictAction(set));
}
};
var InsertAst = class InsertAst extends QueryAst {
kind = "insert";
table;
rows;
onConflict;
returning;
constructor(table, rows = [{}], onConflict, returning) {
super();
this.table = table;
this.rows = freezeRows(rows);
this.onConflict = onConflict;
this.returning = returning && returning.length > 0 ? frozenArrayCopy(returning) : void 0;
this.freeze();
}
static into(table) {
return new InsertAst(table);
}
withRows(rows) {
return new InsertAst(this.table, rows.map((row) => ({ ...row })), this.onConflict, this.returning);
}
withReturning(returning) {
return new InsertAst(this.table, this.rows.map((row) => ({ ...row })), this.onConflict, returning);
}
withOnConflict(onConflict) {
return new InsertAst(this.table, this.rows.map((row) => ({ ...row })), onConflict, this.returning);
}
rewrite(rewriter) {
return new InsertAst(rewriteTableSource(this.table, rewriter), this.rows.map((row) => rewriteInsertRow(row, rewriter)), this.onConflict ? rewriteOnConflict(this.onConflict, rewriter) : void 0, this.returning?.map((item) => rewriteProjectionItem(item, rewriter)));
}
collectParamRefs() {
const refs = [];
for (const row of this.rows) for (const value of Object.values(row)) if (value.kind === "param-ref" || value.kind === "prepared-param-ref") refs.push(value);
else if (value.kind === "raw-expr") refs.push(...value.collectParamRefs());
if (this.onConflict?.action.kind === "do-update-set") {
for (const value of Object.values(this.onConflict.action.set)) if (value.kind === "param-ref" || value.kind === "prepared-param-ref") refs.push(value);
}
for (const item of this.returning ?? []) if (item.expr.kind !== "literal") refs.push(...item.expr.collectParamRefs());
return refs;
}
toQueryAst() {
return this;
}
};
var UpdateAst = class UpdateAst extends QueryAst {
kind = "update";
table;
set;
where;
returning;
constructor(table, set = {}, where, returning) {
super();
this.table = table;
this.set = frozenRecordCopy(set);
this.where = where;
this.returning = returning && returning.length > 0 ? frozenArrayCopy(returning) : void 0;
this.freeze();
}
static table(table) {
return new UpdateAst(table);
}
withSet(set) {
return new UpdateAst(this.table, set, this.where, this.returning);
}
withWhere(where) {
return new UpdateAst(this.table, this.set, where, this.returning);
}
withReturning(returning) {
return new UpdateAst(this.table, this.set, this.where, returning);
}
rewrite(rewriter) {
return new UpdateAst(rewriteTableSource(this.table, rewriter), rewriteUpdateSet(this.set, rewriter), this.where?.rewrite(rewriter), this.returning?.map((item) => rewriteProjectionItem(item, rewriter)));
}
collectParamRefs() {
const refs = [];
for (const value of Object.values(this.set)) refs.push(...value.collectParamRefs());
if (this.where) refs.push(...this.where.collectParamRefs());
for (const item of this.returning ?? []) if (item.expr.kind !== "literal") refs.push(...item.expr.collectParamRefs());
return refs;
}
toQueryAst() {
return this;
}
};
var DeleteAst = class DeleteAst extends QueryAst {
kind = "delete";
table;
where;
returning;
constructor(table, where, returning) {
super();
this.table = table;
this.where = where;
this.returning = returning && returning.length > 0 ? frozenArrayCopy(returning) : void 0;
this.freeze();
}
static from(table) {
return new DeleteAst(table);
}
withWhere(where) {
return new DeleteAst(this.table, where, this.returning);
}
withReturning(returning) {
return new DeleteAst(this.table, this.where, returning);
}
rewrite(rewriter) {
return new DeleteAst(rewriteTableSource(this.table, rewriter), this.where?.rewrite(rewriter), this.returning?.map((item) => rewriteProjectionItem(item, rewriter)));
}
collectParamRefs() {
const refs = [];
if (this.where) refs.push(...this.where.collectParamRefs());
for (const item of this.returning ?? []) if (item.expr.kind !== "literal") refs.push(...item.expr.collectParamRefs());
return refs;
}
toQueryAst() {
return this;
}
};
/**
* Raw-SQL query AST node carrying interpolated parameter / expression nodes
* embedded inside literal SQL fragments.
*
* `fragments` and `args` are interleaved during lowering:
* `fragments[0] + lower(args[0]) + fragments[1] + ... + fragments[n]`.
* Construction enforces `fragments.length === args.length + 1`.
*
* Extends {@link QueryAst} (whole-query AST, not a sub-expression).
* Construction does not validate that each arg is a `ParamRef` /
* `AnyExpression`: the type system already rejects bare values because
* `args` is typed `readonly AnyExpression[]`. The user-facing `raw\`...\``
* factory (separate `sql-raw-factory` component) layers stricter
* type-level rejection on top of this AST node.
*/
var RawSqlExpr = class RawSqlExpr extends QueryAst {
kind = "raw-sql";
fragments;
args;
constructor(fragments, args) {
super();
if (fragments.length !== args.length + 1) throw new Error(`RawSqlExpr: fragments.length must equal args.length + 1 (got fragments=${fragments.length}, args=${args.length})`);
this.fragments = Object.freeze([...fragments]);
this.args = Object.freeze([...args]);
this.freeze();
}
static of(fragments, args) {
return new RawSqlExpr(fragments, args);
}
collectParamRefs() {
const refs = [];
for (const arg of this.args) if (arg.kind === "param-ref") refs.push(arg);
else refs.push(...arg.collectParamRefs());
return refs;
}
toQueryAst() {
return this;
}
};
const queryAstKinds = new Set([
"select",
"insert",
"update",
"delete",
"raw-sql"
]);
const whereExprKinds = new Set([
"binary",
"and",
"or",
"exists",
"null-check",
"not"
]);
function isQueryAst(value) {
return typeof value === "object" && value !== null && "kind" in value && queryAstKinds.has(value.kind);
}
function isWhereExpr(value) {
return typeof value === "object" && value !== null && "kind" in value && whereExprKinds.has(value.kind);
}
//#endregion
export { RawSqlExpr as A, OperationExpr as C, PreparedParamRef as D, ParamRef as E, WindowFuncExpr as F, isQueryAst as I, isWhereExpr as L, SubqueryExpr as M, TableSource as N, ProjectionItem as O, UpdateAst as P, queryAstKinds as R, NullCheckExpr as S, OrderByItem as T, JsonArrayAggExpr as _, DefaultValueExpr as a, LiteralExpr as b, DoNothingConflictAction as c, ExistsExpr as d, FunctionSource as f, JoinAst as g, InsertOnConflict as h, ColumnRef as i, SelectAst as j, RawExpr as k, DoUpdateSetConflictAction as l, InsertAst as m, AndExpr as n, DeleteAst as o, IdentifierRef as p, BinaryExpr as r, DerivedTableSource as s, AggregateExpr as t, EqColJoinOn as u, JsonObjectExpr as v, OrExpr as w, NotExpr as x, ListExpression as y, whereExprKinds as z };
//# sourceMappingURL=types-CaGVAsoT.mjs.map

Sorry, the diff of this file is too big to display

+1
-1
import { a as FunctionColumnDefault, c as UniqueConstraint, i as ForeignKeyConstraint, l as isDdlNode, n as DdlColumnDefault, o as LiteralColumnDefault, r as DdlNode, s as PrimaryKeyConstraint, t as DdlColumn } from "../ddl-types-DAox2c8w.mjs";
import { A as RawSqlExpr, C as OperationExpr, D as PreparedParamRef, E as ParamRef, F as WindowFuncExpr, I as isQueryAst, L as isWhereExpr, M as SubqueryExpr, N as TableSource, O as ProjectionItem, P as UpdateAst, R as queryAstKinds, S as NullCheckExpr, T as OrderByItem, _ as JsonArrayAggExpr, a as DefaultValueExpr, b as LiteralExpr, c as DoNothingConflictAction, d as ExistsExpr, f as FunctionSource, g as JoinAst, h as InsertOnConflict, i as ColumnRef, j as SelectAst, k as RawExpr, l as DoUpdateSetConflictAction, m as InsertAst, n as AndExpr, o as DeleteAst, p as IdentifierRef, r as BinaryExpr, s as DerivedTableSource, t as AggregateExpr, u as EqColJoinOn, v as JsonObjectExpr, w as OrExpr, x as NotExpr, y as ListExpression, z as whereExprKinds } from "../types-lJUc6cY-.mjs";
import { A as RawSqlExpr, C as OperationExpr, D as PreparedParamRef, E as ParamRef, F as WindowFuncExpr, I as isQueryAst, L as isWhereExpr, M as SubqueryExpr, N as TableSource, O as ProjectionItem, P as UpdateAst, R as queryAstKinds, S as NullCheckExpr, T as OrderByItem, _ as JsonArrayAggExpr, a as DefaultValueExpr, b as LiteralExpr, c as DoNothingConflictAction, d as ExistsExpr, f as FunctionSource, g as JoinAst, h as InsertOnConflict, i as ColumnRef, j as SelectAst, k as RawExpr, l as DoUpdateSetConflictAction, m as InsertAst, n as AndExpr, o as DeleteAst, p as IdentifierRef, r as BinaryExpr, s as DerivedTableSource, t as AggregateExpr, u as EqColJoinOn, v as JsonObjectExpr, w as OrExpr, x as NotExpr, y as ListExpression, z as whereExprKinds } from "../types-CaGVAsoT.mjs";
import { n as compact, t as collectOrderedParamRefs } from "../util-DQQgv2j1.mjs";

@@ -4,0 +4,0 @@ import { CodecDescriptorImpl, CodecImpl, column, voidParamsSchema } from "@prisma-next/framework-components/codec";

@@ -1,1 +0,1 @@

{"version":3,"file":"codec-descriptor-registry.d.mts","names":[],"sources":["../../src/codec-descriptor-registry.ts","../../src/codec-ref-for-column.ts"],"mappings":";;;;;;;;;AAgBA;;;;;;;iBAAgB,4BAAA,CACd,cAAA,EAAgB,aAAA,CAAc,kBAAA,GAC9B,OAAA,GAAU,UAAA,GACT,uBAAA;;;;;;;AAHH;;;;;;;;;;;iBCIgB,wBAAA,CACd,OAAA,EAAS,UAAA,EACT,WAAA,UACA,SAAA,UACA,UAAA,WACC,QAAQ"}
{"version":3,"file":"codec-descriptor-registry.d.mts","names":[],"sources":["../../src/codec-descriptor-registry.ts","../../src/codec-ref-for-column.ts"],"mappings":";;;;;;;;;AAgBA;;;;;;;iBAAgB,4BAAA,CACd,cAAA,EAAgB,aAAA,CAAc,kBAAA,GAC9B,OAAA,GAAU,UAAA,GACT,uBAAA;;;;;;;AAHH;;;;;;;;;;;iBCKgB,wBAAA,CACd,OAAA,EAAS,UAAA,EACT,WAAA,UACA,SAAA,UACA,UAAA,WACC,QAAQ"}
import { resolveStorageTable } from "@prisma-next/sql-contract/resolve-storage-table";
import { isStorageTypeInstance } from "@prisma-next/sql-contract/types";
import { blindCast } from "@prisma-next/utils/casts";
//#region src/codec-ref-for-column.ts

@@ -36,7 +37,17 @@ /**

}
if (columnDef.typeParams !== void 0 && Object.keys(columnDef.typeParams).length > 0) return {
if (columnDef.typeParams !== void 0 && Object.keys(columnDef.typeParams).length > 0) {
const typeParams = blindCast(columnDef.typeParams);
return columnDef.many ? {
codecId: columnDef.codecId,
typeParams,
many: true
} : {
codecId: columnDef.codecId,
typeParams
};
}
return columnDef.many ? {
codecId: columnDef.codecId,
typeParams: columnDef.typeParams
};
return { codecId: columnDef.codecId };
many: true
} : { codecId: columnDef.codecId };
}

@@ -43,0 +54,0 @@ //#endregion

@@ -1,1 +0,1 @@

{"version":3,"file":"codec-descriptor-registry.mjs","names":[],"sources":["../../src/codec-ref-for-column.ts","../../src/codec-descriptor-registry.ts"],"sourcesContent":["import type { JsonValue } from '@prisma-next/contract/types';\nimport type { CodecRef } from '@prisma-next/framework-components/codec';\nimport { resolveStorageTable } from '@prisma-next/sql-contract/resolve-storage-table';\nimport { isStorageTypeInstance, type SqlStorage } from '@prisma-next/sql-contract/types';\n\n/**\n * Derive the canonical {@link CodecRef} for a `(table, column)` pair against a {@link SqlStorage}. This is the build-time path every column-bound `ParamRef` / `ProjectionItem` uses to stamp its `codec` slot before the AST is handed to the runtime — the runtime resolver then materialises a memoised {@link import('@prisma-next/sql-relational-core/ast').Codec} for the same `CodecRef` via `forCodecRef`.\n *\n * Resolution rules over namespace `entries.table[table].columns[column]`:\n *\n * - `typeRef` column → `{codecId, typeParams}` from `storage.types[typeRef]` (multiple columns sharing the typeRef share one ref → one memoised codec).\n * - inline `typeParams` column → `{codecId, typeParams}` from the column itself.\n * - non-parameterized column → `{codecId}` with `typeParams` undefined.\n *\n * Returns `undefined` when the table or column is unknown, or when a `typeRef` column references a `storage.types` entry that does not exist.\n *\n * `namespaceId` leads the coordinate args and is always supplied: every\n * model/table sits in an explicit namespace, so the table is resolved strictly\n * within that namespace (see {@link resolveStorageTable}).\n */\nexport function codecRefForStorageColumn(\n storage: SqlStorage,\n namespaceId: string,\n tableName: string,\n columnName: string,\n): CodecRef | undefined {\n const resolved = resolveStorageTable(storage, tableName, namespaceId);\n if (resolved === undefined) return undefined;\n const tableDef = resolved.table;\n const columnDef = tableDef.columns[columnName];\n if (!columnDef) return undefined;\n if (columnDef.typeRef !== undefined) {\n const instance = storage.types?.[columnDef.typeRef];\n if (!instance) return undefined;\n if (isStorageTypeInstance(instance)) {\n const instanceParams = instance.typeParams;\n const hasParamKeys = instanceParams !== undefined && Object.keys(instanceParams).length > 0;\n return hasParamKeys\n ? { codecId: instance.codecId, typeParams: instanceParams as JsonValue }\n : { codecId: instance.codecId };\n }\n return undefined;\n }\n if (columnDef.typeParams !== undefined && Object.keys(columnDef.typeParams).length > 0) {\n return { codecId: columnDef.codecId, typeParams: columnDef.typeParams as JsonValue };\n }\n return { codecId: columnDef.codecId };\n}\n","import type { CodecDescriptor, CodecRef } from '@prisma-next/framework-components/codec';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { AnyCodecDescriptor } from './ast/codec-types';\nimport { codecRefForStorageColumn } from './codec-ref-for-column';\nimport type { CodecDescriptorRegistry } from './query-lane-context';\n\n/**\n * Build a {@link CodecDescriptorRegistry} from a flat descriptor list.\n *\n * Used by:\n * - Each codec-shipping package's `core/registry.ts` to expose a package-scoped registry as the public consumer surface (replacing raw descriptor-array exports). See ADR 208.\n * - The runtime's `buildExecutionContext` to construct the contract-bound combined registry from every contributor's `codecs:` slot.\n *\n * The descriptor map is heterogeneous in `P` — each codec id has its own params shape. The public {@link CodecDescriptorRegistry} interface widens to `CodecDescriptor<unknown>` and consumers narrow per codec id at the call site (the descriptor's `paramsSchema` validates JSON-sourced params before the factory ever sees them, so the runtime narrow is safe). The cast at registration goes through `unknown` because\n * `CodecDescriptor<P>` is invariant in `P` (the `factory` and `renderOutputType` slots use `P` contravariantly).\n */\nexport function buildCodecDescriptorRegistry(\n allDescriptors: ReadonlyArray<AnyCodecDescriptor>,\n storage?: SqlStorage,\n): CodecDescriptorRegistry {\n type AnyDescriptor = CodecDescriptor<unknown>;\n const byId = new Map<string, AnyDescriptor>();\n const byTargetType = new Map<string, Array<AnyDescriptor>>();\n\n for (const descriptor of allDescriptors) {\n if (byId.has(descriptor.codecId)) {\n throw new Error(\n `Duplicate codec descriptor id: '${descriptor.codecId}' — registered twice during registry construction. ` +\n 'Each codecId must be contributed by exactly one component (target / adapter / extension pack).',\n );\n }\n const widened = descriptor as unknown as AnyDescriptor;\n byId.set(descriptor.codecId, widened);\n for (const targetType of descriptor.targetTypes) {\n const list = byTargetType.get(targetType);\n if (list) {\n list.push(widened);\n } else {\n byTargetType.set(targetType, [widened]);\n }\n }\n }\n\n return {\n descriptorFor(codecId: string): AnyDescriptor | undefined {\n return byId.get(codecId);\n },\n codecRefForColumn(namespaceId: string, table: string, column: string): CodecRef | undefined {\n if (!storage) return undefined;\n return codecRefForStorageColumn(storage, namespaceId, table, column);\n },\n *values(): IterableIterator<AnyDescriptor> {\n yield* byId.values();\n },\n byTargetType(targetType: string): readonly AnyDescriptor[] {\n return byTargetType.get(targetType) ?? Object.freeze([]);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoBA,SAAgB,yBACd,SACA,aACA,WACA,YACsB;CACtB,MAAM,WAAW,oBAAoB,SAAS,WAAW,WAAW;CACpE,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;CAEnC,MAAM,YADW,SAAS,MACC,QAAQ;CACnC,IAAI,CAAC,WAAW,OAAO,KAAA;CACvB,IAAI,UAAU,YAAY,KAAA,GAAW;EACnC,MAAM,WAAW,QAAQ,QAAQ,UAAU;EAC3C,IAAI,CAAC,UAAU,OAAO,KAAA;EACtB,IAAI,sBAAsB,QAAQ,GAAG;GACnC,MAAM,iBAAiB,SAAS;GAEhC,OADqB,mBAAmB,KAAA,KAAa,OAAO,KAAK,cAAc,CAAC,CAAC,SAAS,IAEtF;IAAE,SAAS,SAAS;IAAS,YAAY;GAA4B,IACrE,EAAE,SAAS,SAAS,QAAQ;EAClC;EACA;CACF;CACA,IAAI,UAAU,eAAe,KAAA,KAAa,OAAO,KAAK,UAAU,UAAU,CAAC,CAAC,SAAS,GACnF,OAAO;EAAE,SAAS,UAAU;EAAS,YAAY,UAAU;CAAwB;CAErF,OAAO,EAAE,SAAS,UAAU,QAAQ;AACtC;;;;;;;;;;;;;AC/BA,SAAgB,6BACd,gBACA,SACyB;CAEzB,MAAM,uBAAO,IAAI,IAA2B;CAC5C,MAAM,+BAAe,IAAI,IAAkC;CAE3D,KAAK,MAAM,cAAc,gBAAgB;EACvC,IAAI,KAAK,IAAI,WAAW,OAAO,GAC7B,MAAM,IAAI,MACR,mCAAmC,WAAW,QAAQ,kJAExD;EAEF,MAAM,UAAU;EAChB,KAAK,IAAI,WAAW,SAAS,OAAO;EACpC,KAAK,MAAM,cAAc,WAAW,aAAa;GAC/C,MAAM,OAAO,aAAa,IAAI,UAAU;GACxC,IAAI,MACF,KAAK,KAAK,OAAO;QAEjB,aAAa,IAAI,YAAY,CAAC,OAAO,CAAC;EAE1C;CACF;CAEA,OAAO;EACL,cAAc,SAA4C;GACxD,OAAO,KAAK,IAAI,OAAO;EACzB;EACA,kBAAkB,aAAqB,OAAe,QAAsC;GAC1F,IAAI,CAAC,SAAS,OAAO,KAAA;GACrB,OAAO,yBAAyB,SAAS,aAAa,OAAO,MAAM;EACrE;EACA,CAAC,SAA0C;GACzC,OAAO,KAAK,OAAO;EACrB;EACA,aAAa,YAA8C;GACzD,OAAO,aAAa,IAAI,UAAU,KAAK,OAAO,OAAO,CAAC,CAAC;EACzD;CACF;AACF"}
{"version":3,"file":"codec-descriptor-registry.mjs","names":[],"sources":["../../src/codec-ref-for-column.ts","../../src/codec-descriptor-registry.ts"],"sourcesContent":["import type { JsonValue } from '@prisma-next/contract/types';\nimport type { CodecRef } from '@prisma-next/framework-components/codec';\nimport { resolveStorageTable } from '@prisma-next/sql-contract/resolve-storage-table';\nimport { isStorageTypeInstance, type SqlStorage } from '@prisma-next/sql-contract/types';\nimport { blindCast } from '@prisma-next/utils/casts';\n\n/**\n * Derive the canonical {@link CodecRef} for a `(table, column)` pair against a {@link SqlStorage}. This is the build-time path every column-bound `ParamRef` / `ProjectionItem` uses to stamp its `codec` slot before the AST is handed to the runtime — the runtime resolver then materialises a memoised {@link import('@prisma-next/sql-relational-core/ast').Codec} for the same `CodecRef` via `forCodecRef`.\n *\n * Resolution rules over namespace `entries.table[table].columns[column]`:\n *\n * - `typeRef` column → `{codecId, typeParams}` from `storage.types[typeRef]` (multiple columns sharing the typeRef share one ref → one memoised codec).\n * - inline `typeParams` column → `{codecId, typeParams}` from the column itself.\n * - non-parameterized column → `{codecId}` with `typeParams` undefined.\n *\n * Returns `undefined` when the table or column is unknown, or when a `typeRef` column references a `storage.types` entry that does not exist.\n *\n * `namespaceId` leads the coordinate args and is always supplied: every\n * model/table sits in an explicit namespace, so the table is resolved strictly\n * within that namespace (see {@link resolveStorageTable}).\n */\nexport function codecRefForStorageColumn(\n storage: SqlStorage,\n namespaceId: string,\n tableName: string,\n columnName: string,\n): CodecRef | undefined {\n const resolved = resolveStorageTable(storage, tableName, namespaceId);\n if (resolved === undefined) return undefined;\n const tableDef = resolved.table;\n const columnDef = tableDef.columns[columnName];\n if (!columnDef) return undefined;\n if (columnDef.typeRef !== undefined) {\n const instance = storage.types?.[columnDef.typeRef];\n if (!instance) return undefined;\n if (isStorageTypeInstance(instance)) {\n const instanceParams = instance.typeParams;\n const hasParamKeys = instanceParams !== undefined && Object.keys(instanceParams).length > 0;\n return hasParamKeys\n ? { codecId: instance.codecId, typeParams: instanceParams as JsonValue }\n : { codecId: instance.codecId };\n }\n return undefined;\n }\n if (columnDef.typeParams !== undefined && Object.keys(columnDef.typeParams).length > 0) {\n const typeParams = blindCast<\n JsonValue,\n 'column typeParams is a validated contract record; its values are JSON-serialisable'\n >(columnDef.typeParams);\n return columnDef.many\n ? { codecId: columnDef.codecId, typeParams, many: true }\n : { codecId: columnDef.codecId, typeParams };\n }\n return columnDef.many\n ? { codecId: columnDef.codecId, many: true }\n : { codecId: columnDef.codecId };\n}\n","import type { CodecDescriptor, CodecRef } from '@prisma-next/framework-components/codec';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { AnyCodecDescriptor } from './ast/codec-types';\nimport { codecRefForStorageColumn } from './codec-ref-for-column';\nimport type { CodecDescriptorRegistry } from './query-lane-context';\n\n/**\n * Build a {@link CodecDescriptorRegistry} from a flat descriptor list.\n *\n * Used by:\n * - Each codec-shipping package's `core/registry.ts` to expose a package-scoped registry as the public consumer surface (replacing raw descriptor-array exports). See ADR 208.\n * - The runtime's `buildExecutionContext` to construct the contract-bound combined registry from every contributor's `codecs:` slot.\n *\n * The descriptor map is heterogeneous in `P` — each codec id has its own params shape. The public {@link CodecDescriptorRegistry} interface widens to `CodecDescriptor<unknown>` and consumers narrow per codec id at the call site (the descriptor's `paramsSchema` validates JSON-sourced params before the factory ever sees them, so the runtime narrow is safe). The cast at registration goes through `unknown` because\n * `CodecDescriptor<P>` is invariant in `P` (the `factory` and `renderOutputType` slots use `P` contravariantly).\n */\nexport function buildCodecDescriptorRegistry(\n allDescriptors: ReadonlyArray<AnyCodecDescriptor>,\n storage?: SqlStorage,\n): CodecDescriptorRegistry {\n type AnyDescriptor = CodecDescriptor<unknown>;\n const byId = new Map<string, AnyDescriptor>();\n const byTargetType = new Map<string, Array<AnyDescriptor>>();\n\n for (const descriptor of allDescriptors) {\n if (byId.has(descriptor.codecId)) {\n throw new Error(\n `Duplicate codec descriptor id: '${descriptor.codecId}' — registered twice during registry construction. ` +\n 'Each codecId must be contributed by exactly one component (target / adapter / extension pack).',\n );\n }\n const widened = descriptor as unknown as AnyDescriptor;\n byId.set(descriptor.codecId, widened);\n for (const targetType of descriptor.targetTypes) {\n const list = byTargetType.get(targetType);\n if (list) {\n list.push(widened);\n } else {\n byTargetType.set(targetType, [widened]);\n }\n }\n }\n\n return {\n descriptorFor(codecId: string): AnyDescriptor | undefined {\n return byId.get(codecId);\n },\n codecRefForColumn(namespaceId: string, table: string, column: string): CodecRef | undefined {\n if (!storage) return undefined;\n return codecRefForStorageColumn(storage, namespaceId, table, column);\n },\n *values(): IterableIterator<AnyDescriptor> {\n yield* byId.values();\n },\n byTargetType(targetType: string): readonly AnyDescriptor[] {\n return byTargetType.get(targetType) ?? Object.freeze([]);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,yBACd,SACA,aACA,WACA,YACsB;CACtB,MAAM,WAAW,oBAAoB,SAAS,WAAW,WAAW;CACpE,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;CAEnC,MAAM,YADW,SAAS,MACC,QAAQ;CACnC,IAAI,CAAC,WAAW,OAAO,KAAA;CACvB,IAAI,UAAU,YAAY,KAAA,GAAW;EACnC,MAAM,WAAW,QAAQ,QAAQ,UAAU;EAC3C,IAAI,CAAC,UAAU,OAAO,KAAA;EACtB,IAAI,sBAAsB,QAAQ,GAAG;GACnC,MAAM,iBAAiB,SAAS;GAEhC,OADqB,mBAAmB,KAAA,KAAa,OAAO,KAAK,cAAc,CAAC,CAAC,SAAS,IAEtF;IAAE,SAAS,SAAS;IAAS,YAAY;GAA4B,IACrE,EAAE,SAAS,SAAS,QAAQ;EAClC;EACA;CACF;CACA,IAAI,UAAU,eAAe,KAAA,KAAa,OAAO,KAAK,UAAU,UAAU,CAAC,CAAC,SAAS,GAAG;EACtF,MAAM,aAAa,UAGjB,UAAU,UAAU;EACtB,OAAO,UAAU,OACb;GAAE,SAAS,UAAU;GAAS;GAAY,MAAM;EAAK,IACrD;GAAE,SAAS,UAAU;GAAS;EAAW;CAC/C;CACA,OAAO,UAAU,OACb;EAAE,SAAS,UAAU;EAAS,MAAM;CAAK,IACzC,EAAE,SAAS,UAAU,QAAQ;AACnC;;;;;;;;;;;;;ACxCA,SAAgB,6BACd,gBACA,SACyB;CAEzB,MAAM,uBAAO,IAAI,IAA2B;CAC5C,MAAM,+BAAe,IAAI,IAAkC;CAE3D,KAAK,MAAM,cAAc,gBAAgB;EACvC,IAAI,KAAK,IAAI,WAAW,OAAO,GAC7B,MAAM,IAAI,MACR,mCAAmC,WAAW,QAAQ,kJAExD;EAEF,MAAM,UAAU;EAChB,KAAK,IAAI,WAAW,SAAS,OAAO;EACpC,KAAK,MAAM,cAAc,WAAW,aAAa;GAC/C,MAAM,OAAO,aAAa,IAAI,UAAU;GACxC,IAAI,MACF,KAAK,KAAK,OAAO;QAEjB,aAAa,IAAI,YAAY,CAAC,OAAO,CAAC;EAE1C;CACF;CAEA,OAAO;EACL,cAAc,SAA4C;GACxD,OAAO,KAAK,IAAI,OAAO;EACzB;EACA,kBAAkB,aAAqB,OAAe,QAAsC;GAC1F,IAAI,CAAC,SAAS,OAAO,KAAA;GACrB,OAAO,yBAAyB,SAAS,aAAa,OAAO,MAAM;EACrE;EACA,CAAC,SAA0C;GACzC,OAAO,KAAK,OAAO;EACrB;EACA,aAAa,YAA8C;GACzD,OAAO,aAAa,IAAI,UAAU,KAAK,OAAO,OAAO,CAAC,CAAC;EACzD;CACF;AACF"}
import { a as FunctionColumnDefault, c as UniqueConstraint, i as ForeignKeyConstraint, o as LiteralColumnDefault, s as PrimaryKeyConstraint, t as DdlColumn } from "../ddl-types-DAox2c8w.mjs";
import { C as OperationExpr, E as ParamRef, N as TableSource, O as ProjectionItem, P as UpdateAst, S as NullCheckExpr, T as OrderByItem, b as LiteralExpr, d as ExistsExpr, g as JoinAst, h as InsertOnConflict, i as ColumnRef, j as SelectAst, k as RawExpr, m as InsertAst, n as AndExpr, p as IdentifierRef, r as BinaryExpr, t as AggregateExpr, w as OrExpr } from "../types-lJUc6cY-.mjs";
import { C as OperationExpr, E as ParamRef, N as TableSource, O as ProjectionItem, P as UpdateAst, S as NullCheckExpr, T as OrderByItem, b as LiteralExpr, d as ExistsExpr, g as JoinAst, h as InsertOnConflict, i as ColumnRef, j as SelectAst, k as RawExpr, m as InsertAst, n as AndExpr, p as IdentifierRef, r as BinaryExpr, t as AggregateExpr, w as OrExpr } from "../types-CaGVAsoT.mjs";
import { blindCast } from "@prisma-next/utils/casts";

@@ -4,0 +4,0 @@ //#region src/contract-free/column.ts

@@ -12,2 +12,10 @@ import { o as CodecRef } from "../codec-types-DFLA6Hmj.mjs";

/**
* Marks a list-typed (scalar-array) field. When `true`, the field is an
* array of `codecId`-typed elements; list operations target it and the
* element type is `codecId`. Absent/`false` for scalar fields. Carried so
* `X` and `X[]` stay distinct at the type level (a list expression is not
* assignable to a scalar `CodecExpression` slot).
*/
many?: boolean;
/**
* Optional {@link CodecRef} derived from contract storage at scope construction time. Builder paths that mint column-bound `ParamRef` / `ProjectionItem` nodes stamp this slot onto the AST so encode/decode dispatch resolves through `contractCodecs.forCodecRef`. Leave `undefined` when the scope was built without contract storage (rare — tests, ad-hoc scopes).

@@ -48,2 +56,8 @@ */

* - `null` when `Nullable` is true
*
* `many?: never` makes this a *scalar* slot: a list expression (whose
* `returnType` carries `many: true`) is rejected here, while scalar
* expressions — which carry no `many` key at all — pass unchanged. The
* discriminant lives on this operand slot, so scalar expression and scope
* types never have to spell out `many: false`.
*/

@@ -55,4 +69,16 @@ type CodecExpression<CodecId extends string, Nullable extends boolean, CT extends Record<string, {

nullable: Nullable;
many?: never;
}> | CodecValue<CodecId, Nullable, CT>;
/**
* A list-typed expression: an {@link Expression} whose element codec is
* `CodecId` and whose `returnType` carries `many: true`. The element identity
* is the codec id, so list operations stay generic over the element type while
* tying any element argument back to this list's `CodecId`.
*/
type ScalarListExpression<CodecId extends string, Nullable extends boolean> = Expression<{
codecId: CodecId;
nullable: Nullable;
many: true;
}>;
/**
* An expression or literal value targeting any codec whose trait set contains all the required traits.

@@ -142,3 +168,3 @@ *

//#endregion
export { BuildOperationSpec, CodecExpression, CodecTypesBase, CodecValue, Expression, RawCodecInferer, RawSqlBuilder, RawSqlTag, ScopeField, TraitExpression, buildOperation, codecOf, createRawSql, param, toExpr };
export { BuildOperationSpec, CodecExpression, CodecTypesBase, CodecValue, Expression, RawCodecInferer, RawSqlBuilder, RawSqlTag, ScalarListExpression, ScopeField, TraitExpression, buildOperation, codecOf, createRawSql, param, toExpr };
//# sourceMappingURL=expression.d.mts.map

@@ -1,1 +0,1 @@

{"version":3,"file":"expression.d.mts","names":[],"sources":["../../src/expression.ts"],"mappings":";;;;;;;KAQY,UAAA;EACV,OAAA;EACA,QAAA;;;;EAIA,KAAA,GAAQ,QAAQ;AAAA;AAAA,KAGN,cAAA,GAAiB,MAAM;EAAA,SAAoB,KAAA;EAAA,SAAyB,MAAA;AAAA;;;;KAKpE,UAAA,WAAqB,UAAA,IAAc,oBAAA;EAAA,SACpC,UAAA,EAAY,CAAA;EACrB,QAAA,IAAY,aAAA;AAAA;AAAA,KAGT,iBAAA,YACQ,MAAA;EAAA,SAA0B,KAAA;AAAA,8DAGzB,EAAA,YAAc,EAAA,CAAG,CAAA;EAAA,SAAsB,MAAA;AAAA,KAC9C,cAAA,mBAAiC,CAAA,IAChC,CAAA,yBAGA,EAAA;AAAA,KAEH,UAAA,MAAgB,CAAC;;;;;KAMV,UAAA,8DAGC,MAAA;EAAA,SAA0B,KAAA;AAAA,OAClC,OAAA,eAAsB,EAAA,GAAK,EAAA,CAAG,OAAA,sBAA6B,UAAA,CAAW,QAAA;;;;AAxBhD;AACzB;;;;KAiCU,eAAA,8DAGC,MAAA;EAAA,SAA0B,KAAA;AAAA,MACnC,UAAA;EAAa,OAAA,EAAS,OAAA;EAAS,QAAA,EAAU,QAAA;AAAA,KAAc,UAAA,CAAW,OAAA,EAAS,QAAA,EAAU,EAAA;;;;;;KAO7E,eAAA,wEAGC,MAAA;EAAA,SAA0B,KAAA;AAAA,MACnC,eAAA,CAAgB,iBAAA,CAAkB,EAAA,EAAI,MAAA,GAAS,QAAA,EAAU,EAAA;;;;;;;;iBAS7C,MAAA,CAAO,KAAA,WAAgB,KAAA,GAAQ,QAAA,GAAW,aAAa;;;AA9C7D;iBA+DM,KAAA,IAAS,KAAA,EAAO,CAAA,EAAG,IAAA;EAAQ,OAAA;AAAA,IAAoB,QAAQ;;AA7DjD;AAMtB;;;;;;;;iBAqEgB,OAAA,CAAQ,KAAA,YAAiB,QAAQ;AAAA,UAqBhC,kBAAA,WAA6B,UAAA;EAAA,SACnC,MAAA;EAvF+D;;;EAAA,SA2F/D,IAAA,YAAgB,aAAA,KAAkB,aAAA;EAAA,SAClC,OAAA,EAAS,CAAA,GAAI,SAAA;EAAA,SACb,QAAA,EAAU,eAAA;AAAA;;;;iBAML,cAAA,WAAyB,UAAA,EAAY,IAAA,EAAM,kBAAA,CAAmB,CAAA,IAAK,UAAA,CAAW,CAAA;;;AAnGX;AAUnF;;;;;;;;;UAoHiB,eAAA;EACf,UAAA,CAAW,KAAA,EAAO,aAAa;AAAA;;UAIhB,aAAA;EACf,OAAA,mBAA0B,IAAA,EAAM,CAAA,GAAI,UAAA;IAAa,OAAA,EAAS,CAAA;IAAG,QAAA;EAAA;EAC7D,OAAA,8CAAqD,IAAA;IAAA,SAC1C,OAAA,EAAS,CAAA;IAAA,SACT,QAAA,GAAW,CAAA;EAAA,IAClB,UAAA;IAAa,OAAA,EAAS,CAAA;IAAG,QAAA,EAAU,CAAA;EAAA;AAAA;;KAI7B,SAAA,IACV,OAAA,EAAS,oBAAA,KACN,MAAA,EAAQ,mBAAA,OACR,aAAA;AAAA,KAEA,mBAAA,GAAsB,UAAA,CAAW,UAAA,IAAc,QAAA,GAAW,aAAA;AA5H/D;;;;;AAAA,iBA8JgB,YAAA,CAAa,OAAA,EAAS,eAAA,GAAkB,SAAS"}
{"version":3,"file":"expression.d.mts","names":[],"sources":["../../src/expression.ts"],"mappings":";;;;;;;KAQY,UAAA;EACV,OAAA;EACA,QAAA;;;;;;;;EAQA,IAAA;EAIgB;AAGlB;;EAHE,KAAA,GAAQ,QAAQ;AAAA;AAAA,KAGN,cAAA,GAAiB,MAAM;EAAA,SAAoB,KAAA;EAAA,SAAyB,MAAA;AAAA;AAAM;AAKtF;;AALsF,KAK1E,UAAA,WAAqB,UAAA,IAAc,oBAAA;EAAA,SACpC,UAAA,EAAY,CAAA;EACrB,QAAA,IAAY,aAAA;AAAA;AAAA,KAGT,iBAAA,YACQ,MAAA;EAAA,SAA0B,KAAA;AAAA,8DAGzB,EAAA,YAAc,EAAA,CAAG,CAAA;EAAA,SAAsB,MAAA;AAAA,KAC9C,cAAA,mBAAiC,CAAA,IAChC,CAAA,yBAGA,EAAA;AAAA,KAEH,UAAA,MAAgB,CAAC;;;;AAdK;KAoBf,UAAA,8DAGC,MAAA;EAAA,SAA0B,KAAA;AAAA,OAClC,OAAA,eAAsB,EAAA,GAAK,EAAA,CAAG,OAAA,sBAA6B,UAAA,CAAW,QAAA;;;;;;;;;;;;;;;KAgB/D,eAAA,8DAGC,MAAA;EAAA,SAA0B,KAAA;AAAA,MAEnC,UAAA;EAAa,OAAA,EAAS,OAAA;EAAS,QAAA,EAAU,QAAA;EAAU,IAAA;AAAA,KACnD,UAAA,CAAW,OAAA,EAAS,QAAA,EAAU,EAAA;;;;;AAlCxB;AAAA;KA0CE,oBAAA,qDAAyE,UAAA;EACnF,OAAA,EAAS,OAAA;EACT,QAAA,EAAU,QAAA;EACV,IAAA;AAAA;;;;;;KAQU,eAAA,wEAGC,MAAA;EAAA,SAA0B,KAAA;AAAA,MACnC,eAAA,CAAgB,iBAAA,CAAkB,EAAA,EAAI,MAAA,GAAS,QAAA,EAAU,EAAA;;;;;;;;iBAS7C,MAAA,CAAO,KAAA,WAAgB,KAAA,GAAQ,QAAA,GAAW,aAAa;;;;iBAiBvD,KAAA,IAAS,KAAA,EAAO,CAAA,EAAG,IAAA;EAAQ,OAAA;AAAA,IAAoB,QAAQ;;AAvEY;AAgBnF;;;;;;;;iBAqEgB,OAAA,CAAQ,KAAA,YAAiB,QAAQ;AAAA,UAqBhC,kBAAA,WAA6B,UAAA;EAAA,SACnC,MAAA;EArFG;;;EAAA,SAyFH,IAAA,YAAgB,aAAA,KAAkB,aAAA;EAAA,SAClC,OAAA,EAAS,CAAA,GAAI,SAAA;EAAA,SACb,QAAA,EAAU,eAAA;AAAA;;;;iBAML,cAAA,WAAyB,UAAA,EAAY,IAAA,EAAM,kBAAA,CAAmB,CAAA,IAAK,UAAA,CAAW,CAAA;;;;;;;;AAjG1D;AAQpC;;;;UAoHiB,eAAA;EACf,UAAA,CAAW,KAAA,EAAO,aAAa;AAAA;;UAIhB,aAAA;EACf,OAAA,mBAA0B,IAAA,EAAM,CAAA,GAAI,UAAA;IAAa,OAAA,EAAS,CAAA;IAAG,QAAA;EAAA;EAC7D,OAAA,8CAAqD,IAAA;IAAA,SAC1C,OAAA,EAAS,CAAA;IAAA,SACT,QAAA,GAAW,CAAA;EAAA,IAClB,UAAA;IAAa,OAAA,EAAS,CAAA;IAAG,QAAA,EAAU,CAAA;EAAA;AAAA;;KAI7B,SAAA,IACV,OAAA,EAAS,oBAAA,KACN,MAAA,EAAQ,mBAAA,OACR,aAAA;AAAA,KAEA,mBAAA,GAAsB,UAAA,CAAW,UAAA,IAAc,QAAA,GAAW,aAAA;;;;;;iBAkC/C,YAAA,CAAa,OAAA,EAAS,eAAA,GAAkB,SAAS"}

@@ -1,2 +0,2 @@

import { C as OperationExpr, E as ParamRef, k as RawExpr } from "../types-lJUc6cY-.mjs";
import { C as OperationExpr, E as ParamRef, k as RawExpr } from "../types-CaGVAsoT.mjs";
import { runtimeError } from "@prisma-next/framework-components/runtime";

@@ -3,0 +3,0 @@ //#region src/expression.ts

@@ -1,1 +0,1 @@

{"version":3,"file":"expression.mjs","names":[],"sources":["../../src/expression.ts"],"sourcesContent":["import { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { ParamSpec } from '@prisma-next/operations';\nimport type { QueryOperationReturn } from '@prisma-next/sql-contract/types';\nimport type { SqlLoweringSpec } from '@prisma-next/sql-operations';\nimport type { CodecRef } from './ast/codec-types';\nimport type { AnyExpression as AstExpression, RawSqlLiteral } from './ast/types';\nimport { OperationExpr, ParamRef, RawExpr } from './ast/types';\n\nexport type ScopeField = {\n codecId: string;\n nullable: boolean;\n /**\n * Optional {@link CodecRef} derived from contract storage at scope construction time. Builder paths that mint column-bound `ParamRef` / `ProjectionItem` nodes stamp this slot onto the AST so encode/decode dispatch resolves through `contractCodecs.forCodecRef`. Leave `undefined` when the scope was built without contract storage (rare — tests, ad-hoc scopes).\n */\n codec?: CodecRef;\n};\n\nexport type CodecTypesBase = Record<string, { readonly input: unknown; readonly output: unknown }>;\n\n/**\n * A typed SQL expression. Identity is carried by the `returnType` descriptor (inherited from `QueryOperationReturn` and narrowed to `T`) — distinct `T` makes distinct Expression types structurally. `buildAst()` materialises the underlying AST node.\n */\nexport type Expression<T extends ScopeField> = QueryOperationReturn & {\n readonly returnType: T;\n buildAst(): AstExpression;\n};\n\ntype CodecIdsWithTrait<\n CT extends Record<string, { readonly input: unknown }>,\n RequiredTraits extends readonly string[],\n> = {\n [K in keyof CT & string]: CT[K] extends { readonly traits: infer T }\n ? [RequiredTraits[number]] extends [T]\n ? K\n : never\n : never;\n}[keyof CT & string];\n\ntype NullSuffix<N> = N extends true ? null : never;\n\n/**\n * Runtime value type for a slot bound to `CodecId` with the given\n * nullability — `CT[CodecId]['input']`, plus `null` when `Nullable` is true.\n */\nexport type CodecValue<\n CodecId extends string,\n Nullable extends boolean,\n CT extends Record<string, { readonly input: unknown }>,\n> = (CodecId extends keyof CT ? CT[CodecId]['input'] : never) | NullSuffix<Nullable>;\n\n/**\n * An expression or literal value targeting a specific codec.\n *\n * Accepts any of:\n * - An `Expression` whose codec matches exactly\n * - A raw JS value of the codec's `input` type\n * - `null` when `Nullable` is true\n */\nexport type CodecExpression<\n CodecId extends string,\n Nullable extends boolean,\n CT extends Record<string, { readonly input: unknown }>,\n> = Expression<{ codecId: CodecId; nullable: Nullable }> | CodecValue<CodecId, Nullable, CT>;\n\n/**\n * An expression or literal value targeting any codec whose trait set contains all the required traits.\n *\n * Resolves the trait set to the union of matching codec identities via `CodecIdsWithTrait`, then reuses `CodecExpression` for the codec-id form.\n */\nexport type TraitExpression<\n Traits extends readonly string[],\n Nullable extends boolean,\n CT extends Record<string, { readonly input: unknown }>,\n> = CodecExpression<CodecIdsWithTrait<CT, Traits>, Nullable, CT>;\n\n/**\n * Resolve a raw value or an Expression into an AST expression node.\n *\n * When `value` is an Expression (duck-typed by its `buildAst` method), the AST it wraps is returned. Otherwise the value is embedded as a ParamRef tagged with the caller-supplied {@link CodecRef} (when known). The runtime resolves the ref via `contractCodecs.forCodecRef(codec)`; content-keyed memoisation collapses repeated lookups for the same logical column onto one shared codec.\n *\n * Operation implementations that compare a column-bound expression to a user value derive the column's {@link CodecRef} from the column-bound side (via {@link codecOf}) and forward it here so encode-side dispatch resolves to the per-instance codec for parameterized codec ids (`vector(1024)` vs. `vector(1536)`).\n */\nexport function toExpr(value: unknown, codec?: CodecRef): AstExpression {\n if (isExpressionLike(value)) {\n return value.buildAst();\n }\n if (codec === undefined) {\n throw runtimeError(\n 'RUNTIME.PARAM_REF_CODEC_REQUIRED',\n `Cannot construct a ParamRef for a ${value === null ? 'null' : typeof value} value without an explicit codec. ` +\n 'Provide a CodecRef at the call site or use a column-bound builder path.',\n );\n }\n return ParamRef.of(value, { codec });\n}\n\n/**\n * Construct a `ParamRef` for a value whose codec identity is known at call time. Use this when interpolating a value into a raw SQL expression and the codec cannot be inferred from context — e.g. `param(myDate, { codecId: 'pg/timestamptz@1' })`.\n */\nexport function param<T>(value: T, opts: { codecId: string }): ParamRef {\n return ParamRef.of(value, { codec: { codecId: opts.codecId } });\n}\n\n/**\n * Derive the {@link CodecRef} carried by an expression-like value.\n *\n * Resolution order:\n * 1. `wrapper.codec` — explicit column-bound {@link CodecRef} stamped at field-proxy time.\n * 2. `wrapper.returnType.codec` — scope-level codec when the scope was built from contract storage.\n * 3. `{ codecId: wrapper.returnType.codecId }` — minimal ref derived from the expression's declared codec id (covers synthetic expressions like `count()` whose returnType has a known codec id but no explicit column binding).\n *\n * Returns `undefined` for raw scalar values (non-expression-like).\n */\nexport function codecOf(value: unknown): CodecRef | undefined {\n if (!isExpressionLike(value)) return undefined;\n const wrapper = value as {\n codec?: CodecRef;\n returnType?: { codec?: CodecRef; codecId?: string };\n };\n if (wrapper.codec) return wrapper.codec;\n if (wrapper.returnType?.codec) return wrapper.returnType.codec;\n if (wrapper.returnType?.codecId) return { codecId: wrapper.returnType.codecId };\n return undefined;\n}\n\nfunction isExpressionLike(value: unknown): value is Expression<ScopeField> {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'buildAst' in value &&\n typeof (value as { buildAst: unknown }).buildAst === 'function'\n );\n}\n\nexport interface BuildOperationSpec<R extends ScopeField> {\n readonly method: string;\n /**\n * The operation's arguments. The first element is the self argument (the value the operation is being applied to); the rest are the remaining user-supplied arguments.\n */\n readonly args: readonly [AstExpression, ...AstExpression[]];\n readonly returns: R & ParamSpec;\n readonly lowering: SqlLoweringSpec;\n}\n\n/**\n * Construct an OperationExpr AST node and wrap it as a typed Expression. Operation implementations use this to turn their user-facing arguments into the AST node the compilation pipeline eventually lowers to SQL.\n */\nexport function buildOperation<R extends ScopeField>(spec: BuildOperationSpec<R>): Expression<R> {\n const [self, ...rest] = spec.args;\n const op = new OperationExpr({\n method: spec.method,\n self,\n args: rest.length > 0 ? rest : undefined,\n returns: spec.returns,\n lowering: spec.lowering,\n });\n return {\n returnType: spec.returns,\n buildAst: () => op,\n };\n}\n\n/**\n * Resolves a codec id for a bare JavaScript value interpolated into a raw-SQL\n * template — e.g. `` rawSql`SELECT ${42}` `` calls `inferCodec(42)` to pick\n * the codec id (`pg/int4`, `sqlite/integer@1`, etc.) that will encode the\n * value as a bound parameter.\n *\n * Targets implement this once per dialect: examine the JS value's runtime\n * shape (number, bigint, string, boolean, `Uint8Array`) and return a codec\n * id known to the target's codec registry. Throw when the value falls\n * outside the supported set — callers should wrap such values with\n * `param(value, { codecId })` to declare the codec explicitly.\n */\nexport interface RawCodecInferer {\n inferCodec(value: RawSqlLiteral): string;\n}\n\n/** The one-method builder returned by a `RawSqlTag` template call before `.returns()` is called. */\nexport interface RawSqlBuilder {\n returns<S extends string>(spec: S): Expression<{ codecId: S; nullable: false }>;\n returns<S extends string, N extends boolean = false>(spec: {\n readonly codecId: S;\n readonly nullable?: N;\n }): Expression<{ codecId: S; nullable: N }>;\n}\n\n/** Tagged-template function returned by {@link createRawSql}. */\nexport type RawSqlTag = (\n strings: TemplateStringsArray,\n ...values: RawSqlInterpolation[]\n) => RawSqlBuilder;\n\ntype RawSqlInterpolation = Expression<ScopeField> | ParamRef | RawSqlLiteral;\n\nfunction resolveInterpolation(\n adapter: RawCodecInferer,\n value: RawSqlInterpolation,\n): AstExpression | ParamRef {\n if (isExpressionLike(value)) {\n return value.buildAst();\n }\n if (value instanceof ParamRef) {\n return value;\n }\n if (\n typeof value === 'number' ||\n typeof value === 'bigint' ||\n typeof value === 'string' ||\n typeof value === 'boolean' ||\n value instanceof Uint8Array\n ) {\n return ParamRef.of(value, { codec: { codecId: adapter.inferCodec(value) } });\n }\n\n value satisfies never;\n throw runtimeError(\n 'RUNTIME.RAW_SQL_UNSUPPORTED_INTERPOLATION',\n 'unsupported JS value type for raw-SQL interpolation: wrap this value in `param(...)` with an explicit codec',\n );\n}\n\n/**\n * Create a tagged-template builder for raw SQL expressions. The returned tag accepts SQL string fragments interleaved with typed {@link Expression}, {@link ParamRef}, or bare {@link RawSqlLiteral} interpolations. Call `.returns(spec)` on the result to obtain a typed {@link Expression} whose AST is a {@link RawExpr}.\n *\n * Bare {@link RawSqlLiteral} interpolations are wrapped as `ParamRef` nodes with the codec resolved via `adapter.inferCodec(value)`. Use {@link param} when the codec cannot be inferred from the value alone (e.g. `Date`).\n */\nexport function createRawSql(adapter: RawCodecInferer): RawSqlTag {\n return (strings, ...values) => {\n const parts: (string | AstExpression | ParamRef)[] = [];\n parts.push(strings[0] ?? '');\n values.forEach((value, i) => {\n parts.push(resolveInterpolation(adapter, value));\n parts.push(strings[i + 1] ?? '');\n });\n return new RawSqlBuilderImpl(parts);\n };\n}\n\nclass RawSqlBuilderImpl implements RawSqlBuilder {\n constructor(private readonly parts: readonly (string | AstExpression | ParamRef)[]) {}\n\n returns<S extends string>(spec: S): Expression<{ codecId: S; nullable: false }>;\n returns<S extends string, N extends boolean = false>(spec: {\n readonly codecId: S;\n readonly nullable?: N;\n }): Expression<{ codecId: S; nullable: N }>;\n returns(\n spec: string | { readonly codecId: string; readonly nullable?: boolean },\n ): Expression<{ codecId: string; nullable: boolean }> {\n const codecId = typeof spec === 'string' ? spec : spec.codecId;\n const nullable = typeof spec === 'string' ? false : (spec.nullable ?? false);\n const paramSpec: ParamSpec = { codecId, nullable };\n const node = new RawExpr({ parts: this.parts, returns: paramSpec });\n return {\n returnType: { codecId, nullable },\n buildAst: () => node,\n };\n }\n}\n"],"mappings":";;;;;;;;;;AAkFA,SAAgB,OAAO,OAAgB,OAAiC;CACtE,IAAI,iBAAiB,KAAK,GACxB,OAAO,MAAM,SAAS;CAExB,IAAI,UAAU,KAAA,GACZ,MAAM,aACJ,oCACA,qCAAqC,UAAU,OAAO,SAAS,OAAO,MAAM,0GAE9E;CAEF,OAAO,SAAS,GAAG,OAAO,EAAE,MAAM,CAAC;AACrC;;;;AAKA,SAAgB,MAAS,OAAU,MAAqC;CACtE,OAAO,SAAS,GAAG,OAAO,EAAE,OAAO,EAAE,SAAS,KAAK,QAAQ,EAAE,CAAC;AAChE;;;;;;;;;;;AAYA,SAAgB,QAAQ,OAAsC;CAC5D,IAAI,CAAC,iBAAiB,KAAK,GAAG,OAAO,KAAA;CACrC,MAAM,UAAU;CAIhB,IAAI,QAAQ,OAAO,OAAO,QAAQ;CAClC,IAAI,QAAQ,YAAY,OAAO,OAAO,QAAQ,WAAW;CACzD,IAAI,QAAQ,YAAY,SAAS,OAAO,EAAE,SAAS,QAAQ,WAAW,QAAQ;AAEhF;AAEA,SAAS,iBAAiB,OAAiD;CACzE,OACE,OAAO,UAAU,YACjB,UAAU,QACV,cAAc,SACd,OAAQ,MAAgC,aAAa;AAEzD;;;;AAeA,SAAgB,eAAqC,MAA4C;CAC/F,MAAM,CAAC,MAAM,GAAG,QAAQ,KAAK;CAC7B,MAAM,KAAK,IAAI,cAAc;EAC3B,QAAQ,KAAK;EACb;EACA,MAAM,KAAK,SAAS,IAAI,OAAO,KAAA;EAC/B,SAAS,KAAK;EACd,UAAU,KAAK;CACjB,CAAC;CACD,OAAO;EACL,YAAY,KAAK;EACjB,gBAAgB;CAClB;AACF;AAmCA,SAAS,qBACP,SACA,OAC0B;CAC1B,IAAI,iBAAiB,KAAK,GACxB,OAAO,MAAM,SAAS;CAExB,IAAI,iBAAiB,UACnB,OAAO;CAET,IACE,OAAO,UAAU,YACjB,OAAO,UAAU,YACjB,OAAO,UAAU,YACjB,OAAO,UAAU,aACjB,iBAAiB,YAEjB,OAAO,SAAS,GAAG,OAAO,EAAE,OAAO,EAAE,SAAS,QAAQ,WAAW,KAAK,EAAE,EAAE,CAAC;CAI7E,MAAM,aACJ,6CACA,6GACF;AACF;;;;;;AAOA,SAAgB,aAAa,SAAqC;CAChE,QAAQ,SAAS,GAAG,WAAW;EAC7B,MAAM,QAA+C,CAAC;EACtD,MAAM,KAAK,QAAQ,MAAM,EAAE;EAC3B,OAAO,SAAS,OAAO,MAAM;GAC3B,MAAM,KAAK,qBAAqB,SAAS,KAAK,CAAC;GAC/C,MAAM,KAAK,QAAQ,IAAI,MAAM,EAAE;EACjC,CAAC;EACD,OAAO,IAAI,kBAAkB,KAAK;CACpC;AACF;AAEA,IAAM,oBAAN,MAAiD;CAClB;CAA7B,YAAY,OAAwE;EAAvD,KAAA,QAAA;CAAwD;CAOrF,QACE,MACoD;EACpD,MAAM,UAAU,OAAO,SAAS,WAAW,OAAO,KAAK;EACvD,MAAM,WAAW,OAAO,SAAS,WAAW,QAAS,KAAK,YAAY;EACtE,MAAM,YAAuB;GAAE;GAAS;EAAS;EACjD,MAAM,OAAO,IAAI,QAAQ;GAAE,OAAO,KAAK;GAAO,SAAS;EAAU,CAAC;EAClE,OAAO;GACL,YAAY;IAAE;IAAS;GAAS;GAChC,gBAAgB;EAClB;CACF;AACF"}
{"version":3,"file":"expression.mjs","names":[],"sources":["../../src/expression.ts"],"sourcesContent":["import { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { ParamSpec } from '@prisma-next/operations';\nimport type { QueryOperationReturn } from '@prisma-next/sql-contract/types';\nimport type { SqlLoweringSpec } from '@prisma-next/sql-operations';\nimport type { CodecRef } from './ast/codec-types';\nimport type { AnyExpression as AstExpression, RawSqlLiteral } from './ast/types';\nimport { OperationExpr, ParamRef, RawExpr } from './ast/types';\n\nexport type ScopeField = {\n codecId: string;\n nullable: boolean;\n /**\n * Marks a list-typed (scalar-array) field. When `true`, the field is an\n * array of `codecId`-typed elements; list operations target it and the\n * element type is `codecId`. Absent/`false` for scalar fields. Carried so\n * `X` and `X[]` stay distinct at the type level (a list expression is not\n * assignable to a scalar `CodecExpression` slot).\n */\n many?: boolean;\n /**\n * Optional {@link CodecRef} derived from contract storage at scope construction time. Builder paths that mint column-bound `ParamRef` / `ProjectionItem` nodes stamp this slot onto the AST so encode/decode dispatch resolves through `contractCodecs.forCodecRef`. Leave `undefined` when the scope was built without contract storage (rare — tests, ad-hoc scopes).\n */\n codec?: CodecRef;\n};\n\nexport type CodecTypesBase = Record<string, { readonly input: unknown; readonly output: unknown }>;\n\n/**\n * A typed SQL expression. Identity is carried by the `returnType` descriptor (inherited from `QueryOperationReturn` and narrowed to `T`) — distinct `T` makes distinct Expression types structurally. `buildAst()` materialises the underlying AST node.\n */\nexport type Expression<T extends ScopeField> = QueryOperationReturn & {\n readonly returnType: T;\n buildAst(): AstExpression;\n};\n\ntype CodecIdsWithTrait<\n CT extends Record<string, { readonly input: unknown }>,\n RequiredTraits extends readonly string[],\n> = {\n [K in keyof CT & string]: CT[K] extends { readonly traits: infer T }\n ? [RequiredTraits[number]] extends [T]\n ? K\n : never\n : never;\n}[keyof CT & string];\n\ntype NullSuffix<N> = N extends true ? null : never;\n\n/**\n * Runtime value type for a slot bound to `CodecId` with the given\n * nullability — `CT[CodecId]['input']`, plus `null` when `Nullable` is true.\n */\nexport type CodecValue<\n CodecId extends string,\n Nullable extends boolean,\n CT extends Record<string, { readonly input: unknown }>,\n> = (CodecId extends keyof CT ? CT[CodecId]['input'] : never) | NullSuffix<Nullable>;\n\n/**\n * An expression or literal value targeting a specific codec.\n *\n * Accepts any of:\n * - An `Expression` whose codec matches exactly\n * - A raw JS value of the codec's `input` type\n * - `null` when `Nullable` is true\n *\n * `many?: never` makes this a *scalar* slot: a list expression (whose\n * `returnType` carries `many: true`) is rejected here, while scalar\n * expressions — which carry no `many` key at all — pass unchanged. The\n * discriminant lives on this operand slot, so scalar expression and scope\n * types never have to spell out `many: false`.\n */\nexport type CodecExpression<\n CodecId extends string,\n Nullable extends boolean,\n CT extends Record<string, { readonly input: unknown }>,\n> =\n | Expression<{ codecId: CodecId; nullable: Nullable; many?: never }>\n | CodecValue<CodecId, Nullable, CT>;\n\n/**\n * A list-typed expression: an {@link Expression} whose element codec is\n * `CodecId` and whose `returnType` carries `many: true`. The element identity\n * is the codec id, so list operations stay generic over the element type while\n * tying any element argument back to this list's `CodecId`.\n */\nexport type ScalarListExpression<CodecId extends string, Nullable extends boolean> = Expression<{\n codecId: CodecId;\n nullable: Nullable;\n many: true;\n}>;\n\n/**\n * An expression or literal value targeting any codec whose trait set contains all the required traits.\n *\n * Resolves the trait set to the union of matching codec identities via `CodecIdsWithTrait`, then reuses `CodecExpression` for the codec-id form.\n */\nexport type TraitExpression<\n Traits extends readonly string[],\n Nullable extends boolean,\n CT extends Record<string, { readonly input: unknown }>,\n> = CodecExpression<CodecIdsWithTrait<CT, Traits>, Nullable, CT>;\n\n/**\n * Resolve a raw value or an Expression into an AST expression node.\n *\n * When `value` is an Expression (duck-typed by its `buildAst` method), the AST it wraps is returned. Otherwise the value is embedded as a ParamRef tagged with the caller-supplied {@link CodecRef} (when known). The runtime resolves the ref via `contractCodecs.forCodecRef(codec)`; content-keyed memoisation collapses repeated lookups for the same logical column onto one shared codec.\n *\n * Operation implementations that compare a column-bound expression to a user value derive the column's {@link CodecRef} from the column-bound side (via {@link codecOf}) and forward it here so encode-side dispatch resolves to the per-instance codec for parameterized codec ids (`vector(1024)` vs. `vector(1536)`).\n */\nexport function toExpr(value: unknown, codec?: CodecRef): AstExpression {\n if (isExpressionLike(value)) {\n return value.buildAst();\n }\n if (codec === undefined) {\n throw runtimeError(\n 'RUNTIME.PARAM_REF_CODEC_REQUIRED',\n `Cannot construct a ParamRef for a ${value === null ? 'null' : typeof value} value without an explicit codec. ` +\n 'Provide a CodecRef at the call site or use a column-bound builder path.',\n );\n }\n return ParamRef.of(value, { codec });\n}\n\n/**\n * Construct a `ParamRef` for a value whose codec identity is known at call time. Use this when interpolating a value into a raw SQL expression and the codec cannot be inferred from context — e.g. `param(myDate, { codecId: 'pg/timestamptz@1' })`.\n */\nexport function param<T>(value: T, opts: { codecId: string }): ParamRef {\n return ParamRef.of(value, { codec: { codecId: opts.codecId } });\n}\n\n/**\n * Derive the {@link CodecRef} carried by an expression-like value.\n *\n * Resolution order:\n * 1. `wrapper.codec` — explicit column-bound {@link CodecRef} stamped at field-proxy time.\n * 2. `wrapper.returnType.codec` — scope-level codec when the scope was built from contract storage.\n * 3. `{ codecId: wrapper.returnType.codecId }` — minimal ref derived from the expression's declared codec id (covers synthetic expressions like `count()` whose returnType has a known codec id but no explicit column binding).\n *\n * Returns `undefined` for raw scalar values (non-expression-like).\n */\nexport function codecOf(value: unknown): CodecRef | undefined {\n if (!isExpressionLike(value)) return undefined;\n const wrapper = value as {\n codec?: CodecRef;\n returnType?: { codec?: CodecRef; codecId?: string };\n };\n if (wrapper.codec) return wrapper.codec;\n if (wrapper.returnType?.codec) return wrapper.returnType.codec;\n if (wrapper.returnType?.codecId) return { codecId: wrapper.returnType.codecId };\n return undefined;\n}\n\nfunction isExpressionLike(value: unknown): value is Expression<ScopeField> {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'buildAst' in value &&\n typeof (value as { buildAst: unknown }).buildAst === 'function'\n );\n}\n\nexport interface BuildOperationSpec<R extends ScopeField> {\n readonly method: string;\n /**\n * The operation's arguments. The first element is the self argument (the value the operation is being applied to); the rest are the remaining user-supplied arguments.\n */\n readonly args: readonly [AstExpression, ...AstExpression[]];\n readonly returns: R & ParamSpec;\n readonly lowering: SqlLoweringSpec;\n}\n\n/**\n * Construct an OperationExpr AST node and wrap it as a typed Expression. Operation implementations use this to turn their user-facing arguments into the AST node the compilation pipeline eventually lowers to SQL.\n */\nexport function buildOperation<R extends ScopeField>(spec: BuildOperationSpec<R>): Expression<R> {\n const [self, ...rest] = spec.args;\n const op = new OperationExpr({\n method: spec.method,\n self,\n args: rest.length > 0 ? rest : undefined,\n returns: spec.returns,\n lowering: spec.lowering,\n });\n return {\n returnType: spec.returns,\n buildAst: () => op,\n };\n}\n\n/**\n * Resolves a codec id for a bare JavaScript value interpolated into a raw-SQL\n * template — e.g. `` rawSql`SELECT ${42}` `` calls `inferCodec(42)` to pick\n * the codec id (`pg/int4`, `sqlite/integer@1`, etc.) that will encode the\n * value as a bound parameter.\n *\n * Targets implement this once per dialect: examine the JS value's runtime\n * shape (number, bigint, string, boolean, `Uint8Array`) and return a codec\n * id known to the target's codec registry. Throw when the value falls\n * outside the supported set — callers should wrap such values with\n * `param(value, { codecId })` to declare the codec explicitly.\n */\nexport interface RawCodecInferer {\n inferCodec(value: RawSqlLiteral): string;\n}\n\n/** The one-method builder returned by a `RawSqlTag` template call before `.returns()` is called. */\nexport interface RawSqlBuilder {\n returns<S extends string>(spec: S): Expression<{ codecId: S; nullable: false }>;\n returns<S extends string, N extends boolean = false>(spec: {\n readonly codecId: S;\n readonly nullable?: N;\n }): Expression<{ codecId: S; nullable: N }>;\n}\n\n/** Tagged-template function returned by {@link createRawSql}. */\nexport type RawSqlTag = (\n strings: TemplateStringsArray,\n ...values: RawSqlInterpolation[]\n) => RawSqlBuilder;\n\ntype RawSqlInterpolation = Expression<ScopeField> | ParamRef | RawSqlLiteral;\n\nfunction resolveInterpolation(\n adapter: RawCodecInferer,\n value: RawSqlInterpolation,\n): AstExpression | ParamRef {\n if (isExpressionLike(value)) {\n return value.buildAst();\n }\n if (value instanceof ParamRef) {\n return value;\n }\n if (\n typeof value === 'number' ||\n typeof value === 'bigint' ||\n typeof value === 'string' ||\n typeof value === 'boolean' ||\n value instanceof Uint8Array\n ) {\n return ParamRef.of(value, { codec: { codecId: adapter.inferCodec(value) } });\n }\n\n value satisfies never;\n throw runtimeError(\n 'RUNTIME.RAW_SQL_UNSUPPORTED_INTERPOLATION',\n 'unsupported JS value type for raw-SQL interpolation: wrap this value in `param(...)` with an explicit codec',\n );\n}\n\n/**\n * Create a tagged-template builder for raw SQL expressions. The returned tag accepts SQL string fragments interleaved with typed {@link Expression}, {@link ParamRef}, or bare {@link RawSqlLiteral} interpolations. Call `.returns(spec)` on the result to obtain a typed {@link Expression} whose AST is a {@link RawExpr}.\n *\n * Bare {@link RawSqlLiteral} interpolations are wrapped as `ParamRef` nodes with the codec resolved via `adapter.inferCodec(value)`. Use {@link param} when the codec cannot be inferred from the value alone (e.g. `Date`).\n */\nexport function createRawSql(adapter: RawCodecInferer): RawSqlTag {\n return (strings, ...values) => {\n const parts: (string | AstExpression | ParamRef)[] = [];\n parts.push(strings[0] ?? '');\n values.forEach((value, i) => {\n parts.push(resolveInterpolation(adapter, value));\n parts.push(strings[i + 1] ?? '');\n });\n return new RawSqlBuilderImpl(parts);\n };\n}\n\nclass RawSqlBuilderImpl implements RawSqlBuilder {\n constructor(private readonly parts: readonly (string | AstExpression | ParamRef)[]) {}\n\n returns<S extends string>(spec: S): Expression<{ codecId: S; nullable: false }>;\n returns<S extends string, N extends boolean = false>(spec: {\n readonly codecId: S;\n readonly nullable?: N;\n }): Expression<{ codecId: S; nullable: N }>;\n returns(\n spec: string | { readonly codecId: string; readonly nullable?: boolean },\n ): Expression<{ codecId: string; nullable: boolean }> {\n const codecId = typeof spec === 'string' ? spec : spec.codecId;\n const nullable = typeof spec === 'string' ? false : (spec.nullable ?? false);\n const paramSpec: ParamSpec = { codecId, nullable };\n const node = new RawExpr({ parts: this.parts, returns: paramSpec });\n return {\n returnType: { codecId, nullable },\n buildAst: () => node,\n };\n }\n}\n"],"mappings":";;;;;;;;;;AA8GA,SAAgB,OAAO,OAAgB,OAAiC;CACtE,IAAI,iBAAiB,KAAK,GACxB,OAAO,MAAM,SAAS;CAExB,IAAI,UAAU,KAAA,GACZ,MAAM,aACJ,oCACA,qCAAqC,UAAU,OAAO,SAAS,OAAO,MAAM,0GAE9E;CAEF,OAAO,SAAS,GAAG,OAAO,EAAE,MAAM,CAAC;AACrC;;;;AAKA,SAAgB,MAAS,OAAU,MAAqC;CACtE,OAAO,SAAS,GAAG,OAAO,EAAE,OAAO,EAAE,SAAS,KAAK,QAAQ,EAAE,CAAC;AAChE;;;;;;;;;;;AAYA,SAAgB,QAAQ,OAAsC;CAC5D,IAAI,CAAC,iBAAiB,KAAK,GAAG,OAAO,KAAA;CACrC,MAAM,UAAU;CAIhB,IAAI,QAAQ,OAAO,OAAO,QAAQ;CAClC,IAAI,QAAQ,YAAY,OAAO,OAAO,QAAQ,WAAW;CACzD,IAAI,QAAQ,YAAY,SAAS,OAAO,EAAE,SAAS,QAAQ,WAAW,QAAQ;AAEhF;AAEA,SAAS,iBAAiB,OAAiD;CACzE,OACE,OAAO,UAAU,YACjB,UAAU,QACV,cAAc,SACd,OAAQ,MAAgC,aAAa;AAEzD;;;;AAeA,SAAgB,eAAqC,MAA4C;CAC/F,MAAM,CAAC,MAAM,GAAG,QAAQ,KAAK;CAC7B,MAAM,KAAK,IAAI,cAAc;EAC3B,QAAQ,KAAK;EACb;EACA,MAAM,KAAK,SAAS,IAAI,OAAO,KAAA;EAC/B,SAAS,KAAK;EACd,UAAU,KAAK;CACjB,CAAC;CACD,OAAO;EACL,YAAY,KAAK;EACjB,gBAAgB;CAClB;AACF;AAmCA,SAAS,qBACP,SACA,OAC0B;CAC1B,IAAI,iBAAiB,KAAK,GACxB,OAAO,MAAM,SAAS;CAExB,IAAI,iBAAiB,UACnB,OAAO;CAET,IACE,OAAO,UAAU,YACjB,OAAO,UAAU,YACjB,OAAO,UAAU,YACjB,OAAO,UAAU,aACjB,iBAAiB,YAEjB,OAAO,SAAS,GAAG,OAAO,EAAE,OAAO,EAAE,SAAS,QAAQ,WAAW,KAAK,EAAE,EAAE,CAAC;CAI7E,MAAM,aACJ,6CACA,6GACF;AACF;;;;;;AAOA,SAAgB,aAAa,SAAqC;CAChE,QAAQ,SAAS,GAAG,WAAW;EAC7B,MAAM,QAA+C,CAAC;EACtD,MAAM,KAAK,QAAQ,MAAM,EAAE;EAC3B,OAAO,SAAS,OAAO,MAAM;GAC3B,MAAM,KAAK,qBAAqB,SAAS,KAAK,CAAC;GAC/C,MAAM,KAAK,QAAQ,IAAI,MAAM,EAAE;EACjC,CAAC;EACD,OAAO,IAAI,kBAAkB,KAAK;CACpC;AACF;AAEA,IAAM,oBAAN,MAAiD;CAClB;CAA7B,YAAY,OAAwE;EAAvD,KAAA,QAAA;CAAwD;CAOrF,QACE,MACoD;EACpD,MAAM,UAAU,OAAO,SAAS,WAAW,OAAO,KAAK;EACvD,MAAM,WAAW,OAAO,SAAS,WAAW,QAAS,KAAK,YAAY;EACtE,MAAM,YAAuB;GAAE;GAAS;EAAS;EACjD,MAAM,OAAO,IAAI,QAAQ;GAAE,OAAO,KAAK;GAAO,SAAS;EAAU,CAAC;EAClE,OAAO;GACL,YAAY;IAAE;IAAS;GAAS;GAChC,gBAAgB;EAClB;CACF;AACF"}

@@ -9,6 +9,6 @@ import { a as CodecMeta, c as ContractCodecRegistry, d as DescriptorCodecTraits, f as ExtractCodecTypes, h as SqlColumnRef, i as CodecDescriptor, l as DescriptorCodecId, m as SqlCodecInstanceContext, n as Codec, o as CodecRef, p as SqlCodecCallContext, r as CodecCallContext, s as CodecTrait, t as AnyCodecDescriptor, u as DescriptorCodecInput } from "./codec-types-DFLA6Hmj.mjs";

import { n as planUnsupported, t as planInvalid } from "./errors-COyZClzw.mjs";
import { BuildOperationSpec, CodecExpression, CodecTypesBase, CodecValue, Expression, RawCodecInferer, RawSqlBuilder, RawSqlTag, ScopeField, TraitExpression, buildOperation, codecOf, createRawSql, param, toExpr } from "./exports/expression.mjs";
import { BuildOperationSpec, CodecExpression, CodecTypesBase, CodecValue, Expression, RawCodecInferer, RawSqlBuilder, RawSqlTag, ScalarListExpression, ScopeField, TraitExpression, buildOperation, codecOf, createRawSql, param, toExpr } from "./exports/expression.mjs";
import { a as SqlParamRefMutatorInternal, i as SqlParamRefMutator, n as ParamRefEntryUnion, o as createSqlParamRefMutator, r as ParamRefHandle, t as ParamRefEntry } from "./middleware-Dyyo4IP1.mjs";
import { n as planFromAst, t as SqlQueryPlan } from "./plan-DUjdGLY3.mjs";
import { n as SqlOrmPlan, t as RuntimeScope } from "./types-CUHnDsdV.mjs";
export { Adapter, AdapterProfile, AdapterTarget, AggregateCountFn, AggregateExpr, AggregateFn, AggregateOpFn, AndExpr, AnyCodecDescriptor, AnyDdlColumnDefault, AnyExpression, AnyFromSource, AnyInsertOnConflictAction, AnyInsertValue, AnyOperationArg, AnyParamRef, AnyQueryAst, AppliedMutationDefault, AstRewriter, BinaryExpr, BinaryOp, BuildOperationSpec, BuildOptions, BuildParamsMap, Codec, type CodecCallContext, type CodecDescriptor, CodecDescriptorRegistry, CodecExpression, CodecMeta, type CodecRef, type CodecTrait, CodecTypes, CodecTypesBase, CodecValue, ColumnRef, ColumnResolutionContract, ColumnsOf, ComputeColumnJsType, ContractCodecRegistry, DdlColumn, DdlColumnDefault, DdlColumnDefaultVisitor, DdlColumnRenderContext, DdlNode, DdlTableConstraint, DefaultValueExpr, DeleteAst, DerivedTableSource, DescriptorCodecId, DescriptorCodecInput, DescriptorCodecTraits, Direction, DoNothingConflictAction, DoUpdateSetConflictAction, EqColJoinOn, ExecutionContext, ExistsExpr, Expr, ExprVisitor, Expression, ExpressionFolder, ExpressionRewriter, ExpressionSource, ExtractCodecTypes, ForeignKeyConstraint, FunctionColumnDefault, FunctionSource, IdentifierRef, InsertAst, InsertOnConflict, InsertValue, JoinAst, JoinOnExpr, JsonArrayAggExpr, JsonObjectEntry, JsonObjectExpr, LimitOffsetValue, ListExpression, LiteralColumnDefault, LiteralExpr, LoweredParam, LoweredStatement, Lowerer, LowererContext, META, MarkerReadResult, Meta, ModelDef, ModelMetadata, MutationDefaultsOp, MutationDefaultsOptions, NotExpr, NullCheckExpr, OperationExpr, OperationTypeSignature, OperationTypes, OperationsForTypeId, OrExpr, OrderByItem, ParamRef, type ParamRefEntry, type ParamRefEntryUnion, type ParamRefHandle, PreparedExecuteRequest, PreparedParamRef, PrimaryKeyConstraint, ProjectionExpr, ProjectionItem, RawCodecInferer, RawExpr, RawFactory, RawFunctionOptions, RawSqlBuilder, RawSqlExpr, RawSqlLiteral, RawSqlTag, RawTemplateFactory, RawTemplateOptions, RuntimeError, type RuntimeScope, SQL_CHAR_CODEC_ID, SQL_FLOAT_CODEC_ID, SQL_INT_CODEC_ID, SQL_TEXT_CODEC_ID, SQL_TIMESTAMP_CODEC_ID, SQL_VARCHAR_CODEC_ID, ScopeField, SelectAst, SelectAstOptions, SqlBuilderOptions, SqlCharCodec, SqlCharDescriptor, SqlCodecCallContext, SqlCodecInstanceContext, SqlColumnRef, SqlConnection, SqlDriver, SqlDriverState, SqlExecuteRequest, type SqlExecutionPlan, SqlExplainResult, SqlFloatCodec, SqlFloatDescriptor, SqlIntCodec, SqlIntDescriptor, type SqlOrmPlan, type SqlParamRefMutator, type SqlParamRefMutatorInternal, SqlPlan, SqlQueryPlan, SqlQueryResult, SqlQueryable, SqlTextCodec, SqlTextDescriptor, SqlTimestampCodec, SqlTimestampDescriptor, SqlTransaction, SqlVarcharCodec, SqlVarcharDescriptor, SubqueryExpr, TableDef, TableKey, TableMetadata, TableRef, TableSource, TablesOf, ToWhereExpr, TraitExpression, TypeHelperRegistry, UniqueConstraint, UpdateAst, WhereArg, WindowFn, WindowFuncExpr, buildOperation, codecOf, collectOrderedParamRefs, compact, createRawSql, createSqlParamRefMutator, isDdlNode, isQueryAst, isWhereExpr, param, planFromAst, planInvalid, planUnsupported, queryAstKinds, sqlCharColumn, sqlCharDecode, sqlCharDescriptor, sqlCharEncode, sqlCharRenderOutputType, sqlFloatColumn, sqlFloatDecode, sqlFloatDescriptor, sqlFloatEncode, sqlIntColumn, sqlIntDecode, sqlIntDescriptor, sqlIntEncode, sqlTextColumn, sqlTextDecode, sqlTextDescriptor, sqlTextEncode, sqlTimestampColumn, sqlTimestampDecode, sqlTimestampDecodeJson, sqlTimestampDescriptor, sqlTimestampEncode, sqlTimestampEncodeJson, sqlTimestampRenderOutputType, sqlVarcharColumn, sqlVarcharDecode, sqlVarcharDescriptor, sqlVarcharEncode, sqlVarcharRenderOutputType, toExpr, whereExprKinds };
export { Adapter, AdapterProfile, AdapterTarget, AggregateCountFn, AggregateExpr, AggregateFn, AggregateOpFn, AndExpr, AnyCodecDescriptor, AnyDdlColumnDefault, AnyExpression, AnyFromSource, AnyInsertOnConflictAction, AnyInsertValue, AnyOperationArg, AnyParamRef, AnyQueryAst, AppliedMutationDefault, AstRewriter, BinaryExpr, BinaryOp, BuildOperationSpec, BuildOptions, BuildParamsMap, Codec, type CodecCallContext, type CodecDescriptor, CodecDescriptorRegistry, CodecExpression, CodecMeta, type CodecRef, type CodecTrait, CodecTypes, CodecTypesBase, CodecValue, ColumnRef, ColumnResolutionContract, ColumnsOf, ComputeColumnJsType, ContractCodecRegistry, DdlColumn, DdlColumnDefault, DdlColumnDefaultVisitor, DdlColumnRenderContext, DdlNode, DdlTableConstraint, DefaultValueExpr, DeleteAst, DerivedTableSource, DescriptorCodecId, DescriptorCodecInput, DescriptorCodecTraits, Direction, DoNothingConflictAction, DoUpdateSetConflictAction, EqColJoinOn, ExecutionContext, ExistsExpr, Expr, ExprVisitor, Expression, ExpressionFolder, ExpressionRewriter, ExpressionSource, ExtractCodecTypes, ForeignKeyConstraint, FunctionColumnDefault, FunctionSource, IdentifierRef, InsertAst, InsertOnConflict, InsertValue, JoinAst, JoinOnExpr, JsonArrayAggExpr, JsonObjectEntry, JsonObjectExpr, LimitOffsetValue, ListExpression, LiteralColumnDefault, LiteralExpr, LoweredParam, LoweredStatement, Lowerer, LowererContext, META, MarkerReadResult, Meta, ModelDef, ModelMetadata, MutationDefaultsOp, MutationDefaultsOptions, NotExpr, NullCheckExpr, OperationExpr, OperationTypeSignature, OperationTypes, OperationsForTypeId, OrExpr, OrderByItem, ParamRef, type ParamRefEntry, type ParamRefEntryUnion, type ParamRefHandle, PreparedExecuteRequest, PreparedParamRef, PrimaryKeyConstraint, ProjectionExpr, ProjectionItem, RawCodecInferer, RawExpr, RawFactory, RawFunctionOptions, RawSqlBuilder, RawSqlExpr, RawSqlLiteral, RawSqlTag, RawTemplateFactory, RawTemplateOptions, RuntimeError, type RuntimeScope, SQL_CHAR_CODEC_ID, SQL_FLOAT_CODEC_ID, SQL_INT_CODEC_ID, SQL_TEXT_CODEC_ID, SQL_TIMESTAMP_CODEC_ID, SQL_VARCHAR_CODEC_ID, ScalarListExpression, ScopeField, SelectAst, SelectAstOptions, SqlBuilderOptions, SqlCharCodec, SqlCharDescriptor, SqlCodecCallContext, SqlCodecInstanceContext, SqlColumnRef, SqlConnection, SqlDriver, SqlDriverState, SqlExecuteRequest, type SqlExecutionPlan, SqlExplainResult, SqlFloatCodec, SqlFloatDescriptor, SqlIntCodec, SqlIntDescriptor, type SqlOrmPlan, type SqlParamRefMutator, type SqlParamRefMutatorInternal, SqlPlan, SqlQueryPlan, SqlQueryResult, SqlQueryable, SqlTextCodec, SqlTextDescriptor, SqlTimestampCodec, SqlTimestampDescriptor, SqlTransaction, SqlVarcharCodec, SqlVarcharDescriptor, SubqueryExpr, TableDef, TableKey, TableMetadata, TableRef, TableSource, TablesOf, ToWhereExpr, TraitExpression, TypeHelperRegistry, UniqueConstraint, UpdateAst, WhereArg, WindowFn, WindowFuncExpr, buildOperation, codecOf, collectOrderedParamRefs, compact, createRawSql, createSqlParamRefMutator, isDdlNode, isQueryAst, isWhereExpr, param, planFromAst, planInvalid, planUnsupported, queryAstKinds, sqlCharColumn, sqlCharDecode, sqlCharDescriptor, sqlCharEncode, sqlCharRenderOutputType, sqlFloatColumn, sqlFloatDecode, sqlFloatDescriptor, sqlFloatEncode, sqlIntColumn, sqlIntDecode, sqlIntDescriptor, sqlIntEncode, sqlTextColumn, sqlTextDecode, sqlTextDescriptor, sqlTextEncode, sqlTimestampColumn, sqlTimestampDecode, sqlTimestampDecodeJson, sqlTimestampDescriptor, sqlTimestampEncode, sqlTimestampEncodeJson, sqlTimestampRenderOutputType, sqlVarcharColumn, sqlVarcharDecode, sqlVarcharDescriptor, sqlVarcharEncode, sqlVarcharRenderOutputType, toExpr, whereExprKinds };
import { a as FunctionColumnDefault, c as UniqueConstraint, i as ForeignKeyConstraint, l as isDdlNode, n as DdlColumnDefault, o as LiteralColumnDefault, r as DdlNode, s as PrimaryKeyConstraint, t as DdlColumn } from "./ddl-types-DAox2c8w.mjs";
import { A as RawSqlExpr, C as OperationExpr, D as PreparedParamRef, E as ParamRef, F as WindowFuncExpr, I as isQueryAst, L as isWhereExpr, M as SubqueryExpr, N as TableSource, O as ProjectionItem, P as UpdateAst, R as queryAstKinds, S as NullCheckExpr, T as OrderByItem, _ as JsonArrayAggExpr, a as DefaultValueExpr, b as LiteralExpr, c as DoNothingConflictAction, d as ExistsExpr, f as FunctionSource, g as JoinAst, h as InsertOnConflict, i as ColumnRef, j as SelectAst, k as RawExpr, l as DoUpdateSetConflictAction, m as InsertAst, n as AndExpr, o as DeleteAst, p as IdentifierRef, r as BinaryExpr, s as DerivedTableSource, t as AggregateExpr, u as EqColJoinOn, v as JsonObjectExpr, w as OrExpr, x as NotExpr, y as ListExpression, z as whereExprKinds } from "./types-lJUc6cY-.mjs";
import { A as RawSqlExpr, C as OperationExpr, D as PreparedParamRef, E as ParamRef, F as WindowFuncExpr, I as isQueryAst, L as isWhereExpr, M as SubqueryExpr, N as TableSource, O as ProjectionItem, P as UpdateAst, R as queryAstKinds, S as NullCheckExpr, T as OrderByItem, _ as JsonArrayAggExpr, a as DefaultValueExpr, b as LiteralExpr, c as DoNothingConflictAction, d as ExistsExpr, f as FunctionSource, g as JoinAst, h as InsertOnConflict, i as ColumnRef, j as SelectAst, k as RawExpr, l as DoUpdateSetConflictAction, m as InsertAst, n as AndExpr, o as DeleteAst, p as IdentifierRef, r as BinaryExpr, s as DerivedTableSource, t as AggregateExpr, u as EqColJoinOn, v as JsonObjectExpr, w as OrExpr, x as NotExpr, y as ListExpression, z as whereExprKinds } from "./types-CaGVAsoT.mjs";
import { n as compact, t as collectOrderedParamRefs } from "./util-DQQgv2j1.mjs";

@@ -4,0 +4,0 @@ import { SQL_CHAR_CODEC_ID, SQL_FLOAT_CODEC_ID, SQL_INT_CODEC_ID, SQL_TEXT_CODEC_ID, SQL_TIMESTAMP_CODEC_ID, SQL_VARCHAR_CODEC_ID, SqlCharCodec, SqlCharDescriptor, SqlFloatCodec, SqlFloatDescriptor, SqlIntCodec, SqlIntDescriptor, SqlTextCodec, SqlTextDescriptor, SqlTimestampCodec, SqlTimestampDescriptor, SqlVarcharCodec, SqlVarcharDescriptor, sqlCharColumn, sqlCharDecode, sqlCharDescriptor, sqlCharEncode, sqlCharRenderOutputType, sqlFloatColumn, sqlFloatDecode, sqlFloatDescriptor, sqlFloatEncode, sqlIntColumn, sqlIntDecode, sqlIntDescriptor, sqlIntEncode, sqlTextColumn, sqlTextDecode, sqlTextDescriptor, sqlTextEncode, sqlTimestampColumn, sqlTimestampDecode, sqlTimestampDecodeJson, sqlTimestampDescriptor, sqlTimestampEncode, sqlTimestampEncodeJson, sqlTimestampRenderOutputType, sqlVarcharColumn, sqlVarcharDecode, sqlVarcharDescriptor, sqlVarcharEncode, sqlVarcharRenderOutputType } from "./exports/ast.mjs";

{
"name": "@prisma-next/sql-relational-core",
"version": "0.14.0-dev.18",
"version": "0.14.0-dev.19",
"license": "Apache-2.0",

@@ -9,8 +9,8 @@ "type": "module",

"dependencies": {
"@prisma-next/contract": "0.14.0-dev.18",
"@prisma-next/framework-components": "0.14.0-dev.18",
"@prisma-next/operations": "0.14.0-dev.18",
"@prisma-next/sql-contract": "0.14.0-dev.18",
"@prisma-next/sql-operations": "0.14.0-dev.18",
"@prisma-next/utils": "0.14.0-dev.18",
"@prisma-next/contract": "0.14.0-dev.19",
"@prisma-next/framework-components": "0.14.0-dev.19",
"@prisma-next/operations": "0.14.0-dev.19",
"@prisma-next/sql-contract": "0.14.0-dev.19",
"@prisma-next/sql-operations": "0.14.0-dev.19",
"@prisma-next/utils": "0.14.0-dev.19",
"@standard-schema/spec": "^1.1.0",

@@ -21,6 +21,6 @@ "arktype": "^2.2.0",

"devDependencies": {
"@prisma-next/sql-contract-ts": "0.14.0-dev.18",
"@prisma-next/test-utils": "0.14.0-dev.18",
"@prisma-next/tsconfig": "0.14.0-dev.18",
"@prisma-next/tsdown": "0.14.0-dev.18",
"@prisma-next/sql-contract-ts": "0.14.0-dev.19",
"@prisma-next/test-utils": "0.14.0-dev.19",
"@prisma-next/tsconfig": "0.14.0-dev.19",
"@prisma-next/tsdown": "0.14.0-dev.19",
"tsdown": "0.22.1",

@@ -27,0 +27,0 @@ "typescript": "5.9.3",

@@ -110,5 +110,5 @@ import type { ParamSpec } from '@prisma-next/operations';

: (structuredClone(codec.typeParams) as CodecRef['typeParams']);
return Object.freeze(
typeParams === undefined ? { codecId: codec.codecId } : { codecId: codec.codecId, typeParams },
);
const base =
typeParams === undefined ? { codecId: codec.codecId } : { codecId: codec.codecId, typeParams };
return Object.freeze(codec.many ? { ...base, many: true } : base);
}

@@ -115,0 +115,0 @@

@@ -5,2 +5,3 @@ import type { JsonValue } from '@prisma-next/contract/types';

import { isStorageTypeInstance, type SqlStorage } from '@prisma-next/sql-contract/types';
import { blindCast } from '@prisma-next/utils/casts';

@@ -46,5 +47,13 @@ /**

if (columnDef.typeParams !== undefined && Object.keys(columnDef.typeParams).length > 0) {
return { codecId: columnDef.codecId, typeParams: columnDef.typeParams as JsonValue };
const typeParams = blindCast<
JsonValue,
'column typeParams is a validated contract record; its values are JSON-serialisable'
>(columnDef.typeParams);
return columnDef.many
? { codecId: columnDef.codecId, typeParams, many: true }
: { codecId: columnDef.codecId, typeParams };
}
return { codecId: columnDef.codecId };
return columnDef.many
? { codecId: columnDef.codecId, many: true }
: { codecId: columnDef.codecId };
}

@@ -13,2 +13,10 @@ import { runtimeError } from '@prisma-next/framework-components/runtime';

/**
* Marks a list-typed (scalar-array) field. When `true`, the field is an
* array of `codecId`-typed elements; list operations target it and the
* element type is `codecId`. Absent/`false` for scalar fields. Carried so
* `X` and `X[]` stay distinct at the type level (a list expression is not
* assignable to a scalar `CodecExpression` slot).
*/
many?: boolean;
/**
* Optional {@link CodecRef} derived from contract storage at scope construction time. Builder paths that mint column-bound `ParamRef` / `ProjectionItem` nodes stamp this slot onto the AST so encode/decode dispatch resolves through `contractCodecs.forCodecRef`. Leave `undefined` when the scope was built without contract storage (rare — tests, ad-hoc scopes).

@@ -59,2 +67,8 @@ */

* - `null` when `Nullable` is true
*
* `many?: never` makes this a *scalar* slot: a list expression (whose
* `returnType` carries `many: true`) is rejected here, while scalar
* expressions — which carry no `many` key at all — pass unchanged. The
* discriminant lives on this operand slot, so scalar expression and scope
* types never have to spell out `many: false`.
*/

@@ -65,5 +79,19 @@ export type CodecExpression<

CT extends Record<string, { readonly input: unknown }>,
> = Expression<{ codecId: CodecId; nullable: Nullable }> | CodecValue<CodecId, Nullable, CT>;
> =
| Expression<{ codecId: CodecId; nullable: Nullable; many?: never }>
| CodecValue<CodecId, Nullable, CT>;
/**
* A list-typed expression: an {@link Expression} whose element codec is
* `CodecId` and whose `returnType` carries `many: true`. The element identity
* is the codec id, so list operations stay generic over the element type while
* tying any element argument back to this list's `CodecId`.
*/
export type ScalarListExpression<CodecId extends string, Nullable extends boolean> = Expression<{
codecId: CodecId;
nullable: Nullable;
many: true;
}>;
/**
* An expression or literal value targeting any codec whose trait set contains all the required traits.

@@ -70,0 +98,0 @@ *

import { ifDefined } from "@prisma-next/utils/defined";
//#region src/ast/types.ts
function frozenArrayCopy(values) {
return Object.freeze([...values]);
}
function frozenOptionalRecordCopy(value) {
return value === void 0 ? void 0 : Object.freeze({ ...value });
}
function frozenRecordCopy(record) {
return Object.freeze({ ...record });
}
function frozenCodecRef(codec) {
const typeParams = codec.typeParams === void 0 ? void 0 : structuredClone(codec.typeParams);
return Object.freeze(typeParams === void 0 ? { codecId: codec.codecId } : {
codecId: codec.codecId,
typeParams
});
}
function freezeRows(rows) {
return Object.freeze(rows.map((row) => Object.freeze({ ...row })));
}
function combineAll(folder, thunks) {
let result = folder.empty;
for (const thunk of thunks) {
if (folder.isAbsorbing?.(result)) return result;
result = folder.combine(result, thunk());
}
return result;
}
function rewriteComparable(value, rewriter) {
switch (value.kind) {
case "param-ref": return rewriter.paramRef ? rewriter.paramRef(value) : value;
case "prepared-param-ref": return rewriter.preparedParamRef ? rewriter.preparedParamRef(value) : value;
case "literal": return rewriter.literal ? rewriter.literal(value) : value;
case "list":
if (rewriter.list) return rewriter.list(value);
return value.rewrite(rewriter);
default: return value.rewrite(rewriter);
}
}
function foldComparable(value, folder) {
switch (value.kind) {
case "param-ref": return folder.paramRef ? folder.paramRef(value) : folder.empty;
case "prepared-param-ref": return folder.preparedParamRef ? folder.preparedParamRef(value) : folder.empty;
case "literal": return folder.literal ? folder.literal(value) : folder.empty;
case "list": return value.fold(folder);
default: return value.fold(folder);
}
}
function collectColumnRefsWith(node) {
return node.fold({
empty: [],
combine: (a, b) => [...a, ...b],
columnRef: (columnRef) => [columnRef],
select: (ast) => ast.collectColumnRefs()
});
}
function collectParamRefsWith(node) {
return node.fold({
empty: [],
combine: (a, b) => [...a, ...b],
paramRef: (paramRef) => [paramRef],
preparedParamRef: (paramRef) => [paramRef],
select: (ast) => ast.collectParamRefs()
});
}
function rewriteTableSource(table, rewriter) {
return rewriter.tableSource ? rewriter.tableSource(table) : table;
}
function rewriteProjectionItem(item, rewriter) {
const rewrittenExpr = item.expr.kind === "literal" ? rewriter.literal ? rewriter.literal(item.expr) : item.expr : item.expr.rewrite(rewriter);
return new ProjectionItem(item.alias, rewrittenExpr, item.codec);
}
function rewriteInsertValue(value, rewriter) {
switch (value.kind) {
case "param-ref": return rewriter.paramRef ? rewriteParamRefForInsert(value, rewriter) : value;
case "prepared-param-ref": return rewriter.preparedParamRef ? rewriter.preparedParamRef(value) : value;
case "column-ref": return rewriter.columnRef ? rewriteColumnRefForInsert(value, rewriter) : value;
case "default-value": return value;
case "raw-expr": return value;
}
}
function rewriteParamRefForInsert(value, rewriter) {
const rewritten = rewriter.paramRef ? rewriter.paramRef(value) : value;
return rewritten.kind === "param-ref" ? rewritten : value;
}
function rewriteColumnRefForInsert(value, rewriter) {
const rewritten = rewriter.columnRef ? rewriter.columnRef(value) : value;
return rewritten.kind === "column-ref" ? rewritten : value;
}
function rewriteInsertRow(row, rewriter) {
const result = {};
for (const [key, value] of Object.entries(row)) result[key] = rewriteInsertValue(value, rewriter);
return result;
}
function rewriteUpdateSet(set, rewriter) {
const result = {};
for (const [key, value] of Object.entries(set)) result[key] = value.rewrite(rewriter);
return result;
}
function rewriteLimitOffset(value, rewriter) {
if (value === void 0 || typeof value === "number") return value;
return value.rewrite(rewriter);
}
function rewriteOnConflict(onConflict, rewriter) {
const columns = onConflict.columns.map((columnRef) => {
const rewritten = rewriter.columnRef ? rewriter.columnRef(columnRef) : columnRef;
return rewritten.kind === "column-ref" ? rewritten : columnRef;
});
if (onConflict.action.kind === "do-nothing") return new InsertOnConflict(columns, new DoNothingConflictAction());
return new InsertOnConflict(columns, new DoUpdateSetConflictAction(rewriteUpdateSet(onConflict.action.set, rewriter)));
}
var AstNode = class {
freeze() {
Object.freeze(this);
}
};
var QueryAst = class extends AstNode {};
var FromSource = class extends AstNode {};
var Expression = class extends AstNode {
collectColumnRefs() {
return collectColumnRefsWith(this);
}
collectParamRefs() {
return collectParamRefsWith(this);
}
baseColumnRef() {
throw new Error(`${this.constructor.name} does not expose a base column reference`);
}
toExpr() {
return this;
}
not() {
return new NotExpr(this);
}
};
var TableSource = class TableSource extends FromSource {
kind = "table-source";
name;
alias;
/**
* Resolved storage namespace coordinate for this table, stamped when the
* table proxy constructs the AST. Renderers qualify via the namespace
* concretion's `qualifyTable()` using this id — never by re-resolving the
* bare table name at render time.
*/
namespaceId;
constructor(name, alias, namespaceId) {
super();
this.name = name;
this.alias = alias;
this.namespaceId = namespaceId;
}
static named(name, alias, namespaceId) {
const source = new TableSource(name, alias, namespaceId);
source.freeze();
return source;
}
rewrite(rewriter) {
return rewriter.tableSource ? rewriter.tableSource(this) : this;
}
toFromSource() {
return this;
}
};
var DerivedTableSource = class DerivedTableSource extends FromSource {
kind = "derived-table-source";
alias;
query;
constructor(alias, query) {
super();
this.alias = alias;
this.query = query;
this.freeze();
}
static as(alias, query) {
return new DerivedTableSource(alias, query);
}
rewrite(rewriter) {
return new DerivedTableSource(this.alias, this.query.rewrite(rewriter));
}
toFromSource() {
return this;
}
};
var FunctionSource = class FunctionSource extends FromSource {
kind = "function-source";
fn;
args;
alias;
constructor(fn, args, alias) {
super();
this.fn = fn;
this.args = frozenArrayCopy(args);
this.alias = alias;
this.freeze();
}
static of(fn, args, alias) {
return new FunctionSource(fn, args, alias);
}
rewrite(rewriter) {
const rewrittenArgs = this.args.map((arg) => rewriteComparable(arg, rewriter));
if (rewrittenArgs.every((arg, i) => arg === this.args[i])) return this;
return new FunctionSource(this.fn, rewrittenArgs, this.alias);
}
toFromSource() {
return this;
}
};
var ColumnRef = class ColumnRef extends Expression {
kind = "column-ref";
table;
column;
constructor(table, column) {
super();
this.table = table;
this.column = column;
this.freeze();
}
static of(table, column) {
return new ColumnRef(table, column);
}
accept(visitor) {
return visitor.columnRef(this);
}
rewrite(rewriter) {
return rewriter.columnRef ? rewriter.columnRef(this) : this;
}
fold(folder) {
return folder.columnRef ? folder.columnRef(this) : folder.empty;
}
baseColumnRef() {
return this;
}
};
var IdentifierRef = class IdentifierRef extends Expression {
kind = "identifier-ref";
name;
constructor(name) {
super();
this.name = name;
this.freeze();
}
static of(name) {
return new IdentifierRef(name);
}
accept(visitor) {
return visitor.identifierRef(this);
}
rewrite(rewriter) {
return rewriter.identifierRef ? rewriter.identifierRef(this) : this;
}
fold(folder) {
return folder.identifierRef ? folder.identifierRef(this) : folder.empty;
}
};
var ParamRef = class ParamRef extends Expression {
kind = "param-ref";
value;
name;
/**
* Codec identity carried by every column-bound `ParamRef`. The encode-side dispatch path materialises the per-instance codec through `contractCodecs.forCodecRef(codec)` — content-keyed memoisation on `(codecId, canonicalize(typeParams))` keeps repeated lookups for the same logical column on one shared {@link Codec}.
*
* `codec` may be `undefined` for `ParamRef`s constructed without a column-bound site (literals, transient builder state); the runtime treats those as untyped passthroughs.
*/
codec;
constructor(value, options) {
super();
this.value = value;
this.name = options?.name;
this.codec = options?.codec ? frozenCodecRef(options.codec) : void 0;
this.freeze();
}
static of(value, options) {
return new ParamRef(value, options);
}
accept(visitor) {
return visitor.param(this);
}
rewrite(rewriter) {
return rewriter.paramRef ? rewriter.paramRef(this) : this;
}
fold(folder) {
return folder.paramRef ? folder.paramRef(this) : folder.empty;
}
};
/**
* Bind-site placeholder: occupies the same positions as `ParamRef` in the
* AST, but carries no value — the value is supplied per-execute by the
* `PreparedStatement.execute(params)` caller and matched to this node by
* `name`.
*/
var PreparedParamRef = class PreparedParamRef extends Expression {
kind = "prepared-param-ref";
name;
codec;
constructor(name, codec) {
super();
this.name = name;
this.codec = frozenCodecRef(codec);
this.freeze();
}
static of(name, codec) {
return new PreparedParamRef(name, codec);
}
accept(visitor) {
return visitor.preparedParam(this);
}
rewrite(rewriter) {
return rewriter.preparedParamRef ? rewriter.preparedParamRef(this) : this;
}
fold(folder) {
return folder.preparedParamRef ? folder.preparedParamRef(this) : folder.empty;
}
};
var DefaultValueExpr = class extends AstNode {
kind = "default-value";
constructor() {
super();
this.freeze();
}
};
var LiteralExpr = class LiteralExpr extends Expression {
kind = "literal";
value;
constructor(value) {
super();
this.value = value;
this.freeze();
}
static of(value) {
return new LiteralExpr(value);
}
accept(visitor) {
return visitor.literal(this);
}
rewrite(rewriter) {
return rewriter.literal ? rewriter.literal(this) : this;
}
fold(folder) {
return folder.literal ? folder.literal(this) : folder.empty;
}
};
var SubqueryExpr = class SubqueryExpr extends Expression {
kind = "subquery";
query;
constructor(query) {
super();
this.query = query;
this.freeze();
}
static of(query) {
return new SubqueryExpr(query);
}
accept(visitor) {
return visitor.subquery(this);
}
rewrite(rewriter) {
return new SubqueryExpr(this.query.rewrite(rewriter));
}
fold(folder) {
return folder.select ? folder.select(this.query) : folder.empty;
}
};
var OperationExpr = class OperationExpr extends Expression {
kind = "operation";
method;
self;
args;
returns;
lowering;
constructor(options) {
super();
this.method = options.method;
this.self = options.self;
this.args = frozenArrayCopy(options.args ?? []);
this.returns = options.returns;
this.lowering = options.lowering;
this.freeze();
}
accept(visitor) {
return visitor.operation(this);
}
rewrite(rewriter) {
return new OperationExpr({
method: this.method,
self: this.self.rewrite(rewriter),
args: this.args.map((arg) => rewriteComparable(arg, rewriter)),
returns: this.returns,
lowering: this.lowering
});
}
fold(folder) {
return combineAll(folder, [() => this.self.fold(folder), ...this.args.map((arg) => () => foldComparable(arg, folder))]);
}
baseColumnRef() {
return this.self.baseColumnRef();
}
};
var RawExpr = class extends Expression {
kind = "raw-expr";
parts;
returns;
constructor(options) {
super();
this.parts = frozenArrayCopy(options.parts);
this.returns = options.returns;
this.freeze();
}
accept(visitor) {
return visitor.rawExpr(this);
}
rewrite(rewriter) {
return rewriter.rawExpr ? rewriter.rawExpr(this) : this;
}
fold(folder) {
if (folder.rawExpr) return folder.rawExpr(this);
return combineAll(folder, this.parts.filter((p) => typeof p !== "string").map((p) => () => p.fold(folder)));
}
};
var AggregateExpr = class AggregateExpr extends Expression {
kind = "aggregate";
fn;
expr;
constructor(fn, expr) {
super();
if (fn !== "count" && expr === void 0) throw new Error(`Aggregate function "${fn}" requires an expression`);
this.fn = fn;
this.expr = expr;
this.freeze();
}
static count(expr) {
return new AggregateExpr("count", expr);
}
static sum(expr) {
return new AggregateExpr("sum", expr);
}
static avg(expr) {
return new AggregateExpr("avg", expr);
}
static min(expr) {
return new AggregateExpr("min", expr);
}
static max(expr) {
return new AggregateExpr("max", expr);
}
accept(visitor) {
return visitor.aggregate(this);
}
rewrite(rewriter) {
return this.expr === void 0 ? this : new AggregateExpr(this.fn, this.expr.rewrite(rewriter));
}
fold(folder) {
return this.expr ? this.expr.fold(folder) : folder.empty;
}
};
/**
* Window function call: `fn(args) OVER (PARTITION BY ... ORDER BY ...)`.
*
* Both `partitionBy` and `orderBy` are optional; an empty `OVER ()`
* clause is legal SQL but rarely useful. For `ROW_NUMBER`, `RANK`, and
* `DENSE_RANK` the standard mandates an `ORDER BY` for deterministic
* results — callers are expected to provide one, but the AST does not
* enforce it.
*
* The `args` slot exists for future window function additions that take
* arguments (e.g. `COUNT(*) OVER`, `SUM(x) OVER`); `ROW_NUMBER` and the
* other ranking functions take no arguments.
*/
var WindowFuncExpr = class WindowFuncExpr extends Expression {
kind = "window-func";
fn;
args;
partitionBy;
orderBy;
constructor(options) {
super();
this.fn = options.fn;
this.args = options.args && options.args.length > 0 ? frozenArrayCopy(options.args) : [];
this.partitionBy = options.partitionBy && options.partitionBy.length > 0 ? frozenArrayCopy(options.partitionBy) : void 0;
this.orderBy = options.orderBy && options.orderBy.length > 0 ? frozenArrayCopy(options.orderBy) : void 0;
this.freeze();
}
static rowNumber(options) {
return new WindowFuncExpr({
fn: "row_number",
...options
});
}
accept(visitor) {
return visitor.windowFunc(this);
}
rewrite(rewriter) {
return new WindowFuncExpr({
fn: this.fn,
args: this.args.map((arg) => arg.rewrite(rewriter)),
...ifDefined("partitionBy", this.partitionBy?.map((expr) => expr.rewrite(rewriter))),
...ifDefined("orderBy", this.orderBy?.map((orderItem) => orderItem.rewrite(rewriter)))
});
}
fold(folder) {
return combineAll(folder, [
...this.args.map((arg) => () => arg.fold(folder)),
...(this.partitionBy ?? []).map((expr) => () => expr.fold(folder)),
...(this.orderBy ?? []).map((orderItem) => () => orderItem.expr.fold(folder))
]);
}
};
var JsonObjectExpr = class JsonObjectExpr extends Expression {
kind = "json-object";
entries;
constructor(entries) {
super();
this.entries = frozenArrayCopy(entries.map((entry) => Object.freeze({ ...entry })));
this.freeze();
}
static entry(key, value) {
return {
key,
value
};
}
static fromEntries(entries) {
return new JsonObjectExpr(entries);
}
accept(visitor) {
return visitor.jsonObject(this);
}
rewrite(rewriter) {
return new JsonObjectExpr(this.entries.map((entry) => ({
key: entry.key,
value: entry.value.kind === "literal" ? rewriter.literal ? rewriter.literal(entry.value) : entry.value : entry.value.rewrite(rewriter)
})));
}
fold(folder) {
return combineAll(folder, this.entries.map((entry) => () => entry.value.kind === "literal" ? folder.literal ? folder.literal(entry.value) : folder.empty : entry.value.fold(folder)));
}
};
var OrderByItem = class OrderByItem extends AstNode {
kind = "order-by-item";
expr;
dir;
constructor(expr, dir) {
super();
this.expr = expr;
this.dir = dir;
this.freeze();
}
static asc(expr) {
return new OrderByItem(expr, "asc");
}
static desc(expr) {
return new OrderByItem(expr, "desc");
}
rewrite(rewriter) {
return new OrderByItem(this.expr.rewrite(rewriter), this.dir);
}
/**
* A new frozen item with the sort direction flipped and `expr` unchanged.
* Integrations that own pagination (e.g. backward cursor pagination) use
* this to reverse a user's sort order without reaching into the AST.
*/
reverse() {
return new OrderByItem(this.expr, this.dir === "asc" ? "desc" : "asc");
}
};
var JsonArrayAggExpr = class JsonArrayAggExpr extends Expression {
kind = "json-array-agg";
expr;
onEmpty;
orderBy;
constructor(expr, onEmpty = "null", orderBy) {
super();
this.expr = expr;
this.onEmpty = onEmpty;
this.orderBy = orderBy && orderBy.length > 0 ? frozenArrayCopy(orderBy) : void 0;
this.freeze();
}
static of(expr, onEmpty = "null", orderBy) {
return new JsonArrayAggExpr(expr, onEmpty, orderBy);
}
accept(visitor) {
return visitor.jsonArrayAgg(this);
}
rewrite(rewriter) {
return new JsonArrayAggExpr(this.expr.rewrite(rewriter), this.onEmpty, this.orderBy?.map((orderItem) => orderItem.rewrite(rewriter)));
}
fold(folder) {
return combineAll(folder, [() => this.expr.fold(folder), ...(this.orderBy ?? []).map((orderItem) => () => orderItem.expr.fold(folder))]);
}
};
var ListExpression = class ListExpression extends Expression {
kind = "list";
values;
constructor(values) {
super();
this.values = frozenArrayCopy(values);
this.freeze();
}
static of(values) {
return new ListExpression(values);
}
static fromValues(values) {
return new ListExpression(values.map((value) => new LiteralExpr(value)));
}
accept(visitor) {
return visitor.list(this);
}
rewrite(rewriter) {
if (rewriter.list) return rewriter.list(this);
return new ListExpression(this.values.map((value) => value.rewrite(rewriter)));
}
fold(folder) {
if (folder.list) return folder.list(this);
return combineAll(folder, this.values.map((value) => () => value.fold(folder)));
}
};
var BinaryExpr = class BinaryExpr extends Expression {
kind = "binary";
op;
left;
right;
constructor(op, left, right) {
super();
this.op = op;
this.left = left;
this.right = right;
this.freeze();
}
static eq(left, right) {
return new BinaryExpr("eq", left, right);
}
static neq(left, right) {
return new BinaryExpr("neq", left, right);
}
static gt(left, right) {
return new BinaryExpr("gt", left, right);
}
static lt(left, right) {
return new BinaryExpr("lt", left, right);
}
static gte(left, right) {
return new BinaryExpr("gte", left, right);
}
static lte(left, right) {
return new BinaryExpr("lte", left, right);
}
static like(left, right) {
return new BinaryExpr("like", left, right);
}
static in(left, right) {
return new BinaryExpr("in", left, right);
}
static notIn(left, right) {
return new BinaryExpr("notIn", left, right);
}
accept(visitor) {
return visitor.binary(this);
}
rewrite(rewriter) {
return new BinaryExpr(this.op, rewriteComparable(this.left, rewriter), rewriteComparable(this.right, rewriter));
}
fold(folder) {
return combineAll(folder, [() => foldComparable(this.left, folder), () => foldComparable(this.right, folder)]);
}
};
var AndExpr = class AndExpr extends Expression {
kind = "and";
exprs;
constructor(exprs) {
super();
this.exprs = frozenArrayCopy(exprs);
this.freeze();
}
static of(exprs) {
return new AndExpr(exprs);
}
static true() {
return new AndExpr([]);
}
accept(visitor) {
return visitor.and(this);
}
rewrite(rewriter) {
return new AndExpr(this.exprs.map((expr) => expr.rewrite(rewriter)));
}
fold(folder) {
return combineAll(folder, this.exprs.map((expr) => () => expr.fold(folder)));
}
};
var OrExpr = class OrExpr extends Expression {
kind = "or";
exprs;
constructor(exprs) {
super();
this.exprs = frozenArrayCopy(exprs);
this.freeze();
}
static of(exprs) {
return new OrExpr(exprs);
}
static false() {
return new OrExpr([]);
}
accept(visitor) {
return visitor.or(this);
}
rewrite(rewriter) {
return new OrExpr(this.exprs.map((expr) => expr.rewrite(rewriter)));
}
fold(folder) {
return combineAll(folder, this.exprs.map((expr) => () => expr.fold(folder)));
}
};
var ExistsExpr = class ExistsExpr extends Expression {
kind = "exists";
notExists;
subquery;
constructor(subquery, notExists = false) {
super();
this.notExists = notExists;
this.subquery = subquery;
this.freeze();
}
static exists(subquery) {
return new ExistsExpr(subquery, false);
}
static notExists(subquery) {
return new ExistsExpr(subquery, true);
}
accept(visitor) {
return visitor.exists(this);
}
rewrite(rewriter) {
return new ExistsExpr(this.subquery.rewrite(rewriter), this.notExists);
}
fold(folder) {
return folder.select ? folder.select(this.subquery) : folder.empty;
}
};
var NullCheckExpr = class NullCheckExpr extends Expression {
kind = "null-check";
expr;
isNull;
constructor(expr, isNull) {
super();
this.expr = expr;
this.isNull = isNull;
this.freeze();
}
static isNull(expr) {
return new NullCheckExpr(expr, true);
}
static isNotNull(expr) {
return new NullCheckExpr(expr, false);
}
accept(visitor) {
return visitor.nullCheck(this);
}
rewrite(rewriter) {
return new NullCheckExpr(this.expr.rewrite(rewriter), this.isNull);
}
fold(folder) {
return this.expr.fold(folder);
}
};
var NotExpr = class NotExpr extends Expression {
kind = "not";
expr;
constructor(expr) {
super();
this.expr = expr;
this.freeze();
}
toWhereExpr() {
return this;
}
accept(visitor) {
return visitor.not(this);
}
rewrite(rewriter) {
return new NotExpr(this.expr.rewrite(rewriter));
}
fold(folder) {
return this.expr.fold(folder);
}
};
var EqColJoinOn = class EqColJoinOn extends AstNode {
kind = "eq-col-join-on";
left;
right;
constructor(left, right) {
super();
this.left = left;
this.right = right;
this.freeze();
}
static of(left, right) {
return new EqColJoinOn(left, right);
}
rewrite(rewriter) {
return rewriter.eqColJoinOn ? rewriter.eqColJoinOn(this) : this;
}
};
var JoinAst = class JoinAst extends AstNode {
kind = "join";
joinType;
source;
lateral;
on;
constructor(joinType, source, on, lateral = false) {
super();
this.joinType = joinType;
this.source = source;
this.lateral = lateral;
this.on = on;
this.freeze();
}
static inner(source, on, lateral = false) {
return new JoinAst("inner", source, on, lateral);
}
static left(source, on, lateral = false) {
return new JoinAst("left", source, on, lateral);
}
static right(source, on, lateral = false) {
return new JoinAst("right", source, on, lateral);
}
static full(source, on, lateral = false) {
return new JoinAst("full", source, on, lateral);
}
rewrite(rewriter) {
return new JoinAst(this.joinType, this.source.rewrite(rewriter), this.on.kind === "eq-col-join-on" ? this.on.rewrite(rewriter) : this.on.rewrite(rewriter), this.lateral);
}
};
var ProjectionItem = class ProjectionItem extends AstNode {
kind = "projection-item";
alias;
expr;
/**
* Codec identity for the projected cell. Decode-side dispatch resolves the per-instance codec through `contractCodecs.forCodecRef(codec)` — content-keyed memoisation collapses repeated lookups for the same logical column onto one shared {@link Codec}.
*
* Stays `undefined` for non-column-bound projections (computed expressions, subqueries, raw aliases) whose decoded type the runtime cannot infer from a single contract column.
*/
codec;
constructor(alias, expr, codec) {
super();
this.alias = alias;
this.expr = expr;
this.codec = codec ? frozenCodecRef(codec) : void 0;
this.freeze();
}
static of(alias, expr, codec) {
return new ProjectionItem(alias, expr, codec);
}
withCodec(codec) {
return new ProjectionItem(this.alias, this.expr, codec);
}
};
var SelectAst = class SelectAst extends QueryAst {
kind = "select";
from;
joins;
projection;
where;
orderBy;
distinct;
distinctOn;
groupBy;
having;
limit;
offset;
selectAllIntent;
constructor(options) {
super();
this.from = options.from;
this.joins = options.joins && options.joins.length > 0 ? frozenArrayCopy(options.joins) : void 0;
this.projection = frozenArrayCopy(options.projection);
this.where = options.where;
this.orderBy = options.orderBy && options.orderBy.length > 0 ? frozenArrayCopy(options.orderBy) : void 0;
this.distinct = options.distinct;
this.distinctOn = options.distinctOn && options.distinctOn.length > 0 ? frozenArrayCopy(options.distinctOn) : void 0;
this.groupBy = options.groupBy && options.groupBy.length > 0 ? frozenArrayCopy(options.groupBy) : void 0;
this.having = options.having;
this.limit = options.limit;
this.offset = options.offset;
this.selectAllIntent = frozenOptionalRecordCopy(options.selectAllIntent);
this.freeze();
}
static from(from) {
return new SelectAst({
from,
joins: void 0,
projection: [],
where: void 0,
orderBy: void 0,
distinct: void 0,
distinctOn: void 0,
groupBy: void 0,
having: void 0,
limit: void 0,
offset: void 0,
selectAllIntent: void 0
});
}
static noFrom() {
return new SelectAst({
joins: void 0,
projection: [],
where: void 0,
orderBy: void 0,
distinct: void 0,
distinctOn: void 0,
groupBy: void 0,
having: void 0,
limit: void 0,
offset: void 0,
selectAllIntent: void 0
});
}
toOptions() {
return {
...this.from !== void 0 ? { from: this.from } : {},
joins: this.joins,
projection: this.projection,
where: this.where,
orderBy: this.orderBy,
distinct: this.distinct,
distinctOn: this.distinctOn,
groupBy: this.groupBy,
having: this.having,
limit: this.limit,
offset: this.offset,
selectAllIntent: this.selectAllIntent
};
}
withFrom(from) {
return new SelectAst({
...this.toOptions(),
from
});
}
withJoins(joins) {
return new SelectAst({
...this.toOptions(),
joins: joins.length > 0 ? joins : void 0
});
}
withProjection(projection) {
return new SelectAst({
...this.toOptions(),
projection
});
}
addProjection(alias, expr) {
return new SelectAst({
...this.toOptions(),
projection: [...this.projection, new ProjectionItem(alias, expr)]
});
}
withWhere(where) {
return new SelectAst({
...this.toOptions(),
where
});
}
withOrderBy(orderBy) {
return new SelectAst({
...this.toOptions(),
orderBy: orderBy.length > 0 ? orderBy : void 0
});
}
withDistinct(enabled = true) {
return new SelectAst({
...this.toOptions(),
distinct: enabled ? true : void 0
});
}
withDistinctOn(distinctOn) {
return new SelectAst({
...this.toOptions(),
distinctOn: distinctOn.length > 0 ? distinctOn : void 0
});
}
withGroupBy(groupBy) {
return new SelectAst({
...this.toOptions(),
groupBy: groupBy.length > 0 ? groupBy : void 0
});
}
withHaving(having) {
return new SelectAst({
...this.toOptions(),
having
});
}
withLimit(limit) {
return new SelectAst({
...this.toOptions(),
limit
});
}
withOffset(offset) {
return new SelectAst({
...this.toOptions(),
offset
});
}
withSelectAllIntent(selectAllIntent) {
return new SelectAst({
...this.toOptions(),
selectAllIntent
});
}
rewrite(rewriter) {
const rewrittenFrom = this.from?.rewrite(rewriter);
const rewritten = new SelectAst({
...rewrittenFrom !== void 0 ? { from: rewrittenFrom } : {},
joins: this.joins?.map((join) => join.rewrite(rewriter)),
projection: this.projection.map((projection) => new ProjectionItem(projection.alias, projection.expr.kind === "literal" ? rewriter.literal ? rewriter.literal(projection.expr) : projection.expr : projection.expr.rewrite(rewriter), projection.codec)),
where: this.where?.rewrite(rewriter),
orderBy: this.orderBy?.map((orderItem) => orderItem.rewrite(rewriter)),
distinct: this.distinct,
distinctOn: this.distinctOn?.map((expr) => expr.rewrite(rewriter)),
groupBy: this.groupBy?.map((expr) => expr.rewrite(rewriter)),
having: this.having?.rewrite(rewriter),
limit: rewriteLimitOffset(this.limit, rewriter),
offset: rewriteLimitOffset(this.offset, rewriter),
selectAllIntent: this.selectAllIntent
});
return rewriter.select ? rewriter.select(rewritten) : rewritten;
}
collectColumnRefs() {
const refs = [];
const pushRefs = (columns) => {
refs.push(...columns);
};
if (this.from?.kind === "derived-table-source") pushRefs(this.from.query.collectColumnRefs());
else if (this.from?.kind === "function-source") for (const arg of this.from.args) pushRefs(arg.collectColumnRefs());
for (const projection of this.projection) if (!(projection.expr.kind === "literal")) pushRefs(projection.expr.collectColumnRefs());
if (this.where) pushRefs(this.where.collectColumnRefs());
if (this.having) pushRefs(this.having.collectColumnRefs());
for (const orderItem of this.orderBy ?? []) pushRefs(orderItem.expr.collectColumnRefs());
for (const expr of this.distinctOn ?? []) pushRefs(expr.collectColumnRefs());
for (const expr of this.groupBy ?? []) pushRefs(expr.collectColumnRefs());
for (const join of this.joins ?? []) {
if (join.source.kind === "derived-table-source") pushRefs(join.source.query.collectColumnRefs());
else if (join.source.kind === "function-source") for (const arg of join.source.args) pushRefs(arg.collectColumnRefs());
if (join.on.kind === "eq-col-join-on") refs.push(join.on.left, join.on.right);
else pushRefs(join.on.collectColumnRefs());
}
if (typeof this.limit === "object") pushRefs(this.limit.collectColumnRefs());
if (typeof this.offset === "object") pushRefs(this.offset.collectColumnRefs());
return refs;
}
collectParamRefs() {
const refs = [];
const pushRefs = (params) => {
refs.push(...params);
};
if (this.from?.kind === "derived-table-source") pushRefs(this.from.query.collectParamRefs());
else if (this.from?.kind === "function-source") for (const arg of this.from.args) pushRefs(arg.collectParamRefs());
for (const projection of this.projection) if (!(projection.expr.kind === "literal")) pushRefs(projection.expr.collectParamRefs());
if (this.where) pushRefs(this.where.collectParamRefs());
if (this.having) pushRefs(this.having.collectParamRefs());
for (const orderItem of this.orderBy ?? []) pushRefs(orderItem.expr.collectParamRefs());
for (const expr of this.distinctOn ?? []) pushRefs(expr.collectParamRefs());
for (const expr of this.groupBy ?? []) pushRefs(expr.collectParamRefs());
for (const join of this.joins ?? []) {
if (join.source.kind === "derived-table-source") pushRefs(join.source.query.collectParamRefs());
else if (join.source.kind === "function-source") for (const arg of join.source.args) pushRefs(arg.collectParamRefs());
if (!(join.on.kind === "eq-col-join-on")) pushRefs(join.on.collectParamRefs());
}
if (typeof this.limit === "object") pushRefs(this.limit.collectParamRefs());
if (typeof this.offset === "object") pushRefs(this.offset.collectParamRefs());
return refs;
}
toQueryAst() {
return this;
}
};
var InsertOnConflictAction = class extends AstNode {};
var DoNothingConflictAction = class extends InsertOnConflictAction {
kind = "do-nothing";
constructor() {
super();
this.freeze();
}
toInsertOnConflictAction() {
return this;
}
};
var DoUpdateSetConflictAction = class extends InsertOnConflictAction {
kind = "do-update-set";
set;
constructor(set) {
super();
this.set = frozenRecordCopy(set);
this.freeze();
}
toInsertOnConflictAction() {
return this;
}
};
var InsertOnConflict = class InsertOnConflict extends AstNode {
kind = "insert-on-conflict";
columns;
action;
constructor(columns, action) {
super();
this.columns = frozenArrayCopy(columns);
this.action = action;
this.freeze();
}
static on(columns) {
return new InsertOnConflict(columns, new DoNothingConflictAction());
}
doNothing() {
return new InsertOnConflict(this.columns, new DoNothingConflictAction());
}
doUpdateSet(set) {
return new InsertOnConflict(this.columns, new DoUpdateSetConflictAction(set));
}
};
var InsertAst = class InsertAst extends QueryAst {
kind = "insert";
table;
rows;
onConflict;
returning;
constructor(table, rows = [{}], onConflict, returning) {
super();
this.table = table;
this.rows = freezeRows(rows);
this.onConflict = onConflict;
this.returning = returning && returning.length > 0 ? frozenArrayCopy(returning) : void 0;
this.freeze();
}
static into(table) {
return new InsertAst(table);
}
withRows(rows) {
return new InsertAst(this.table, rows.map((row) => ({ ...row })), this.onConflict, this.returning);
}
withReturning(returning) {
return new InsertAst(this.table, this.rows.map((row) => ({ ...row })), this.onConflict, returning);
}
withOnConflict(onConflict) {
return new InsertAst(this.table, this.rows.map((row) => ({ ...row })), onConflict, this.returning);
}
rewrite(rewriter) {
return new InsertAst(rewriteTableSource(this.table, rewriter), this.rows.map((row) => rewriteInsertRow(row, rewriter)), this.onConflict ? rewriteOnConflict(this.onConflict, rewriter) : void 0, this.returning?.map((item) => rewriteProjectionItem(item, rewriter)));
}
collectParamRefs() {
const refs = [];
for (const row of this.rows) for (const value of Object.values(row)) if (value.kind === "param-ref" || value.kind === "prepared-param-ref") refs.push(value);
else if (value.kind === "raw-expr") refs.push(...value.collectParamRefs());
if (this.onConflict?.action.kind === "do-update-set") {
for (const value of Object.values(this.onConflict.action.set)) if (value.kind === "param-ref" || value.kind === "prepared-param-ref") refs.push(value);
}
for (const item of this.returning ?? []) if (item.expr.kind !== "literal") refs.push(...item.expr.collectParamRefs());
return refs;
}
toQueryAst() {
return this;
}
};
var UpdateAst = class UpdateAst extends QueryAst {
kind = "update";
table;
set;
where;
returning;
constructor(table, set = {}, where, returning) {
super();
this.table = table;
this.set = frozenRecordCopy(set);
this.where = where;
this.returning = returning && returning.length > 0 ? frozenArrayCopy(returning) : void 0;
this.freeze();
}
static table(table) {
return new UpdateAst(table);
}
withSet(set) {
return new UpdateAst(this.table, set, this.where, this.returning);
}
withWhere(where) {
return new UpdateAst(this.table, this.set, where, this.returning);
}
withReturning(returning) {
return new UpdateAst(this.table, this.set, this.where, returning);
}
rewrite(rewriter) {
return new UpdateAst(rewriteTableSource(this.table, rewriter), rewriteUpdateSet(this.set, rewriter), this.where?.rewrite(rewriter), this.returning?.map((item) => rewriteProjectionItem(item, rewriter)));
}
collectParamRefs() {
const refs = [];
for (const value of Object.values(this.set)) refs.push(...value.collectParamRefs());
if (this.where) refs.push(...this.where.collectParamRefs());
for (const item of this.returning ?? []) if (item.expr.kind !== "literal") refs.push(...item.expr.collectParamRefs());
return refs;
}
toQueryAst() {
return this;
}
};
var DeleteAst = class DeleteAst extends QueryAst {
kind = "delete";
table;
where;
returning;
constructor(table, where, returning) {
super();
this.table = table;
this.where = where;
this.returning = returning && returning.length > 0 ? frozenArrayCopy(returning) : void 0;
this.freeze();
}
static from(table) {
return new DeleteAst(table);
}
withWhere(where) {
return new DeleteAst(this.table, where, this.returning);
}
withReturning(returning) {
return new DeleteAst(this.table, this.where, returning);
}
rewrite(rewriter) {
return new DeleteAst(rewriteTableSource(this.table, rewriter), this.where?.rewrite(rewriter), this.returning?.map((item) => rewriteProjectionItem(item, rewriter)));
}
collectParamRefs() {
const refs = [];
if (this.where) refs.push(...this.where.collectParamRefs());
for (const item of this.returning ?? []) if (item.expr.kind !== "literal") refs.push(...item.expr.collectParamRefs());
return refs;
}
toQueryAst() {
return this;
}
};
/**
* Raw-SQL query AST node carrying interpolated parameter / expression nodes
* embedded inside literal SQL fragments.
*
* `fragments` and `args` are interleaved during lowering:
* `fragments[0] + lower(args[0]) + fragments[1] + ... + fragments[n]`.
* Construction enforces `fragments.length === args.length + 1`.
*
* Extends {@link QueryAst} (whole-query AST, not a sub-expression).
* Construction does not validate that each arg is a `ParamRef` /
* `AnyExpression`: the type system already rejects bare values because
* `args` is typed `readonly AnyExpression[]`. The user-facing `raw\`...\``
* factory (separate `sql-raw-factory` component) layers stricter
* type-level rejection on top of this AST node.
*/
var RawSqlExpr = class RawSqlExpr extends QueryAst {
kind = "raw-sql";
fragments;
args;
constructor(fragments, args) {
super();
if (fragments.length !== args.length + 1) throw new Error(`RawSqlExpr: fragments.length must equal args.length + 1 (got fragments=${fragments.length}, args=${args.length})`);
this.fragments = Object.freeze([...fragments]);
this.args = Object.freeze([...args]);
this.freeze();
}
static of(fragments, args) {
return new RawSqlExpr(fragments, args);
}
collectParamRefs() {
const refs = [];
for (const arg of this.args) if (arg.kind === "param-ref") refs.push(arg);
else refs.push(...arg.collectParamRefs());
return refs;
}
toQueryAst() {
return this;
}
};
const queryAstKinds = new Set([
"select",
"insert",
"update",
"delete",
"raw-sql"
]);
const whereExprKinds = new Set([
"binary",
"and",
"or",
"exists",
"null-check",
"not"
]);
function isQueryAst(value) {
return typeof value === "object" && value !== null && "kind" in value && queryAstKinds.has(value.kind);
}
function isWhereExpr(value) {
return typeof value === "object" && value !== null && "kind" in value && whereExprKinds.has(value.kind);
}
//#endregion
export { RawSqlExpr as A, OperationExpr as C, PreparedParamRef as D, ParamRef as E, WindowFuncExpr as F, isQueryAst as I, isWhereExpr as L, SubqueryExpr as M, TableSource as N, ProjectionItem as O, UpdateAst as P, queryAstKinds as R, NullCheckExpr as S, OrderByItem as T, JsonArrayAggExpr as _, DefaultValueExpr as a, LiteralExpr as b, DoNothingConflictAction as c, ExistsExpr as d, FunctionSource as f, JoinAst as g, InsertOnConflict as h, ColumnRef as i, SelectAst as j, RawExpr as k, DoUpdateSetConflictAction as l, InsertAst as m, AndExpr as n, DeleteAst as o, IdentifierRef as p, BinaryExpr as r, DerivedTableSource as s, AggregateExpr as t, EqColJoinOn as u, JsonObjectExpr as v, OrExpr as w, NotExpr as x, ListExpression as y, whereExprKinds as z };
//# sourceMappingURL=types-lJUc6cY-.mjs.map

Sorry, the diff of this file is too big to display