🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@a2lix/schemql

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@a2lix/schemql - npm Package Compare versions

Comparing version
0.5.2
to
0.5.3
+68
dist/schemql-oq-xONEF.d.cts
import { StandardSchemaV1 } from "@standard-schema/spec";
//#region src/schemql.d.ts
interface SchemQlAdapter<T = unknown> {
queryFirst: QueryFn<T | undefined>;
queryFirstOrThrow: QueryFn<T>;
queryAll: QueryFn<T[]>;
queryIterate: IterativeQueryFn<T>;
}
type QueryFn<TQueryResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined> = (sql: string) => (params?: TParams) => TQueryResult | Promise<TQueryResult>;
type IterativeQueryFn<TQueryResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined> = (sql: string) => (params?: TParams) => GeneratorFn<TQueryResult> | AsyncGeneratorFn<TQueryResult>;
type ArrayElement<T> = T extends (infer U)[] ? U : T;
type GeneratorFn<T> = () => Generator<T, void, unknown>;
type AsyncGeneratorFn<T> = () => AsyncGenerator<T, void, unknown>;
type TableNames<DB> = keyof DB & string;
type ColumnNames<DB, T extends TableNames<DB>> = keyof DB[T] & string;
type TableColumnSelection<DB> = { [T in TableNames<DB>]?: ColumnNames<DB, T>[] };
type ValidTableColumnCombinations<DB> = { [T in TableNames<DB>]: `${T}.${ColumnNames<DB, T>}` | `${T}.${ColumnNames<DB, T>}-` }[TableNames<DB>];
type JsonPathForObjectArrow<T, P extends string = ''> = T extends Record<string, any> ? { [K in keyof T & string]: `${P}->${K}` | `${P}->${K}-` | `${P}->>${K}` | `${P}->>${K}-` | (NonNullable<T[K]> extends Record<string, any> ? `${P}->${K}${JsonPathForObjectArrow<NonNullable<T[K]>, ''>}` : never) }[keyof T & string] : '';
type JsonPathForObjectDot<T, P extends string = ''> = T extends Record<string, any> ? { [K in keyof T & string]: `${P}.${K}` | (NonNullable<T[K]> extends Record<string, any> ? `${P}.${K}${JsonPathForObjectDot<NonNullable<T[K]>, ''>}` : never) }[keyof T & string] : '';
type JsonPathCombinations<DB, T extends TableNames<DB>> = { [K in ColumnNames<DB, T>]: DB[T][K] extends object ? JsonPathForObjectArrow<ArrayElement<DB[T][K]>, `${T}.${K} `> | JsonPathForObjectDot<ArrayElement<DB[T][K]>, `${T}.${K} $`> : never }[ColumnNames<DB, T>];
type ValidJsonPathCombinations<DB> = { [T in TableNames<DB>]: JsonPathCombinations<DB, T> }[TableNames<DB>];
type SqlTemplateValue<TResultSchema, TParams, DB> = TableColumnSelection<DB> | `@${TableNames<DB>}` | `@${TableNames<DB>}.*` | `@${ValidTableColumnCombinations<DB>}` | `@${ValidJsonPathCombinations<DB>}` | `$${keyof ArrayElement<Exclude<TResultSchema, undefined>> & string}` | `:${keyof TParams & string}` | `§${string}`;
type SqlTemplateValues<TResultSchema, TParams, DB> = SqlTemplateValue<TResultSchema, TParams, DB>[];
type SqlOrBuilderFn<TResultSchema extends StandardSchemaV1 | undefined, TParams extends Record<string, any>, DB> = string | ((s: SchemQlSqlHelper<TResultSchema, TParams, DB>) => string);
type SchemQlSqlHelper<TResultSchema extends StandardSchemaV1 | undefined, TParams extends Record<string, any>, DB> = {
sql: <const T extends SqlTemplateValues<TResultSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TResultSchema> : unknown, TParams, DB>>(strings: TemplateStringsArray, ...values: T) => string;
sqlCond: (condition: boolean, ifTrue: string | number, ifFalse?: string | number) => `§${string}`;
sqlRaw: (raw: string | number) => `§${string}`;
};
type SchemQlOptions = {
readonly adapter: SchemQlAdapter; /** @deprecated Use `stringifyObjectParams` instead */
readonly shouldStringifyObjectParams?: boolean;
readonly stringifyObjectParams?: boolean;
readonly quoteSqlIdentifiers?: boolean;
};
type IsIterativeExecution<TParams> = TParams extends any[] | GeneratorFn<any> | AsyncGeneratorFn<any> ? true : false;
type ParamsType<T> = T extends AsyncGeneratorFn<infer P> | GeneratorFn<infer P> | Array<infer P> ? P : T;
type SimpleQueryExecutorResult<TQueryResult, TResultSchema extends StandardSchemaV1 | undefined> = TResultSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TResultSchema> : TQueryResult;
type QueryExecutor<DB> = <TQueryResult = unknown, TParams extends QueryExecutorParams = QueryExecutorParams, TParamsSchema extends StandardSchemaV1 | undefined = undefined, TResultSchema extends StandardSchemaV1 | undefined = undefined>(options: {
params?: QueryExecutorOptionsParams<TParams, TParamsSchema>;
paramsSchema?: TParamsSchema;
resultSchema?: TResultSchema;
}) => (sqlOrBuilderFn: SqlOrBuilderFn<TResultSchema, ParamsType<TParams>, DB>) => Promise<QueryExecutorResult<TQueryResult, TParams, TResultSchema>>;
type QueryExecutorParams = Record<string, any> | Record<string, any>[] | GeneratorFn<Record<string, any>> | AsyncGeneratorFn<Record<string, any>>;
type QueryExecutorOptionsParams<TParams, TParamsSchema extends StandardSchemaV1 | undefined> = TParams extends AsyncGeneratorFn<infer P> ? AsyncGeneratorFn<P> : TParams extends GeneratorFn<infer P> ? GeneratorFn<P> : TParams extends Array<infer P> ? P[] : TParamsSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TParamsSchema> : TParams;
type QueryExecutorResult<TQueryResult, TParams, TResultSchema extends StandardSchemaV1 | undefined> = IsIterativeExecution<TParams> extends true ? AsyncGenerator<SimpleQueryExecutorResult<TQueryResult, TResultSchema>, void, unknown> : SimpleQueryExecutorResult<TQueryResult, TResultSchema>;
type IterativeQueryExecutor<DB> = <TQueryResult = unknown, TParams extends Record<string, any> = Record<string, any>, TParamsSchema extends StandardSchemaV1 | undefined = undefined, TResultSchema extends StandardSchemaV1 | undefined = undefined>(options: {
params?: TParamsSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TParamsSchema> : TParams;
paramsSchema?: TParamsSchema;
resultSchema?: TResultSchema;
}) => (sqlOrBuilderFn: SqlOrBuilderFn<TResultSchema, TParams, DB>) => Promise<AsyncGenerator<SimpleQueryExecutorResult<TQueryResult, TResultSchema>, void, unknown>>;
declare class SchemQl<DB> {
private readonly options;
first: QueryExecutor<DB>;
firstOrThrow: QueryExecutor<DB>;
all: QueryExecutor<DB>;
iterate: IterativeQueryExecutor<DB>;
constructor(options: SchemQlOptions);
private createQueryExecutor;
private createIterativeExecutor;
private validateAndStringifyParams;
private createSqlHelper;
private processLiteralExpressions;
private processLiteralExpression;
}
//#endregion
export { SchemQlAdapter as n, SchemQl as t };
import { StandardSchemaV1 } from "@standard-schema/spec";
//#region src/schemql.d.ts
interface SchemQlAdapter<T = unknown> {
queryFirst: QueryFn<T | undefined>;
queryFirstOrThrow: QueryFn<T>;
queryAll: QueryFn<T[]>;
queryIterate: IterativeQueryFn<T>;
}
type QueryFn<TQueryResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined> = (sql: string) => (params?: TParams) => TQueryResult | Promise<TQueryResult>;
type IterativeQueryFn<TQueryResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined> = (sql: string) => (params?: TParams) => GeneratorFn<TQueryResult> | AsyncGeneratorFn<TQueryResult>;
type ArrayElement<T> = T extends (infer U)[] ? U : T;
type GeneratorFn<T> = () => Generator<T, void, unknown>;
type AsyncGeneratorFn<T> = () => AsyncGenerator<T, void, unknown>;
type TableNames<DB> = keyof DB & string;
type ColumnNames<DB, T extends TableNames<DB>> = keyof DB[T] & string;
type TableColumnSelection<DB> = { [T in TableNames<DB>]?: ColumnNames<DB, T>[] };
type ValidTableColumnCombinations<DB> = { [T in TableNames<DB>]: `${T}.${ColumnNames<DB, T>}` | `${T}.${ColumnNames<DB, T>}-` }[TableNames<DB>];
type JsonPathForObjectArrow<T, P extends string = ''> = T extends Record<string, any> ? { [K in keyof T & string]: `${P}->${K}` | `${P}->${K}-` | `${P}->>${K}` | `${P}->>${K}-` | (NonNullable<T[K]> extends Record<string, any> ? `${P}->${K}${JsonPathForObjectArrow<NonNullable<T[K]>, ''>}` : never) }[keyof T & string] : '';
type JsonPathForObjectDot<T, P extends string = ''> = T extends Record<string, any> ? { [K in keyof T & string]: `${P}.${K}` | (NonNullable<T[K]> extends Record<string, any> ? `${P}.${K}${JsonPathForObjectDot<NonNullable<T[K]>, ''>}` : never) }[keyof T & string] : '';
type JsonPathCombinations<DB, T extends TableNames<DB>> = { [K in ColumnNames<DB, T>]: DB[T][K] extends object ? JsonPathForObjectArrow<ArrayElement<DB[T][K]>, `${T}.${K} `> | JsonPathForObjectDot<ArrayElement<DB[T][K]>, `${T}.${K} $`> : never }[ColumnNames<DB, T>];
type ValidJsonPathCombinations<DB> = { [T in TableNames<DB>]: JsonPathCombinations<DB, T> }[TableNames<DB>];
type SqlTemplateValue<TResultSchema, TParams, DB> = TableColumnSelection<DB> | `@${TableNames<DB>}` | `@${TableNames<DB>}.*` | `@${ValidTableColumnCombinations<DB>}` | `@${ValidJsonPathCombinations<DB>}` | `$${keyof ArrayElement<Exclude<TResultSchema, undefined>> & string}` | `:${keyof TParams & string}` | `§${string}`;
type SqlTemplateValues<TResultSchema, TParams, DB> = SqlTemplateValue<TResultSchema, TParams, DB>[];
type SqlOrBuilderFn<TResultSchema extends StandardSchemaV1 | undefined, TParams extends Record<string, any>, DB> = string | ((s: SchemQlSqlHelper<TResultSchema, TParams, DB>) => string);
type SchemQlSqlHelper<TResultSchema extends StandardSchemaV1 | undefined, TParams extends Record<string, any>, DB> = {
sql: <const T extends SqlTemplateValues<TResultSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TResultSchema> : unknown, TParams, DB>>(strings: TemplateStringsArray, ...values: T) => string;
sqlCond: (condition: boolean, ifTrue: string | number, ifFalse?: string | number) => `§${string}`;
sqlRaw: (raw: string | number) => `§${string}`;
};
type SchemQlOptions = {
readonly adapter: SchemQlAdapter; /** @deprecated Use `stringifyObjectParams` instead */
readonly shouldStringifyObjectParams?: boolean;
readonly stringifyObjectParams?: boolean;
readonly quoteSqlIdentifiers?: boolean;
};
type IsIterativeExecution<TParams> = TParams extends any[] | GeneratorFn<any> | AsyncGeneratorFn<any> ? true : false;
type ParamsType<T> = T extends AsyncGeneratorFn<infer P> | GeneratorFn<infer P> | Array<infer P> ? P : T;
type SimpleQueryExecutorResult<TQueryResult, TResultSchema extends StandardSchemaV1 | undefined> = TResultSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TResultSchema> : TQueryResult;
type QueryExecutor<DB> = <TQueryResult = unknown, TParams extends QueryExecutorParams = QueryExecutorParams, TParamsSchema extends StandardSchemaV1 | undefined = undefined, TResultSchema extends StandardSchemaV1 | undefined = undefined>(options: {
params?: QueryExecutorOptionsParams<TParams, TParamsSchema>;
paramsSchema?: TParamsSchema;
resultSchema?: TResultSchema;
}) => (sqlOrBuilderFn: SqlOrBuilderFn<TResultSchema, ParamsType<TParams>, DB>) => Promise<QueryExecutorResult<TQueryResult, TParams, TResultSchema>>;
type QueryExecutorParams = Record<string, any> | Record<string, any>[] | GeneratorFn<Record<string, any>> | AsyncGeneratorFn<Record<string, any>>;
type QueryExecutorOptionsParams<TParams, TParamsSchema extends StandardSchemaV1 | undefined> = TParams extends AsyncGeneratorFn<infer P> ? AsyncGeneratorFn<P> : TParams extends GeneratorFn<infer P> ? GeneratorFn<P> : TParams extends Array<infer P> ? P[] : TParamsSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TParamsSchema> : TParams;
type QueryExecutorResult<TQueryResult, TParams, TResultSchema extends StandardSchemaV1 | undefined> = IsIterativeExecution<TParams> extends true ? AsyncGenerator<SimpleQueryExecutorResult<TQueryResult, TResultSchema>, void, unknown> : SimpleQueryExecutorResult<TQueryResult, TResultSchema>;
type IterativeQueryExecutor<DB> = <TQueryResult = unknown, TParams extends Record<string, any> = Record<string, any>, TParamsSchema extends StandardSchemaV1 | undefined = undefined, TResultSchema extends StandardSchemaV1 | undefined = undefined>(options: {
params?: TParamsSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TParamsSchema> : TParams;
paramsSchema?: TParamsSchema;
resultSchema?: TResultSchema;
}) => (sqlOrBuilderFn: SqlOrBuilderFn<TResultSchema, TParams, DB>) => Promise<AsyncGenerator<SimpleQueryExecutorResult<TQueryResult, TResultSchema>, void, unknown>>;
declare class SchemQl<DB> {
private readonly options;
first: QueryExecutor<DB>;
firstOrThrow: QueryExecutor<DB>;
all: QueryExecutor<DB>;
iterate: IterativeQueryExecutor<DB>;
constructor(options: SchemQlOptions);
private createQueryExecutor;
private createIterativeExecutor;
private validateAndStringifyParams;
private createSqlHelper;
private processLiteralExpressions;
private processLiteralExpression;
}
//#endregion
export { SchemQlAdapter as n, SchemQl as t };
+1
-1

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

"use strict";var I=Object.defineProperty;var n=(s,N)=>I(s,"name",{value:N,configurable:!0});var t=(s=>(s.InvalidParams="INVALID_PARAMS",s.InvalidResults="INVALID_RESULTS",s.UniqueConstraint="UNIQUE_CONSTRAINT",s.ForeignkeyConstraint="FOREIGNKEY_CONSTRAINT",s.NotnullConstraint="NOTNULL_CONSTRAINT",s.CheckConstraint="CHECK_CONSTRAINT",s.PrimarykeyConstraint="PRIMARYKEY_CONSTRAINT",s.NoResult="NO_RESULT",s.Generic="GENERIC",s))(t||{});class T extends Error{static{n(this,"BaseAdapterError")}constructor(N,i,R){super(N),this.code=i,this.originalError=R,this.name="AdapterError"}isNoResultError=n(()=>this.code==="NO_RESULT","isNoResultError")}exports.AdapterErrorCode=t,exports.BaseAdapterError=T;
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=function(e){return e.InvalidParams=`INVALID_PARAMS`,e.InvalidResults=`INVALID_RESULTS`,e.UniqueConstraint=`UNIQUE_CONSTRAINT`,e.ForeignkeyConstraint=`FOREIGNKEY_CONSTRAINT`,e.NotnullConstraint=`NOTNULL_CONSTRAINT`,e.CheckConstraint=`CHECK_CONSTRAINT`,e.PrimarykeyConstraint=`PRIMARYKEY_CONSTRAINT`,e.NoResult=`NO_RESULT`,e.Generic=`GENERIC`,e}({});var t=class extends Error{constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.isNoResultError=()=>this.code===`NO_RESULT`,this.name=`AdapterError`}};exports.AdapterErrorCode=e,exports.BaseAdapterError=t;

@@ -0,19 +1,20 @@

//#region src/adapters/baseAdapterError.d.ts
declare enum AdapterErrorCode {
InvalidParams = "INVALID_PARAMS",
InvalidResults = "INVALID_RESULTS",
UniqueConstraint = "UNIQUE_CONSTRAINT",
ForeignkeyConstraint = "FOREIGNKEY_CONSTRAINT",
NotnullConstraint = "NOTNULL_CONSTRAINT",
CheckConstraint = "CHECK_CONSTRAINT",
PrimarykeyConstraint = "PRIMARYKEY_CONSTRAINT",
NoResult = "NO_RESULT",
Generic = "GENERIC"
InvalidParams = "INVALID_PARAMS",
InvalidResults = "INVALID_RESULTS",
UniqueConstraint = "UNIQUE_CONSTRAINT",
ForeignkeyConstraint = "FOREIGNKEY_CONSTRAINT",
NotnullConstraint = "NOTNULL_CONSTRAINT",
CheckConstraint = "CHECK_CONSTRAINT",
PrimarykeyConstraint = "PRIMARYKEY_CONSTRAINT",
NoResult = "NO_RESULT",
Generic = "GENERIC"
}
declare class BaseAdapterError extends Error {
code: AdapterErrorCode;
originalError?: Error | undefined;
constructor(message: string, code: AdapterErrorCode, originalError?: Error | undefined);
isNoResultError: () => boolean;
code: AdapterErrorCode;
originalError?: Error | undefined;
constructor(message: string, code: AdapterErrorCode, originalError?: Error | undefined);
isNoResultError: () => boolean;
}
export { AdapterErrorCode, BaseAdapterError };
//#endregion
export { AdapterErrorCode, BaseAdapterError };

@@ -0,19 +1,20 @@

//#region src/adapters/baseAdapterError.d.ts
declare enum AdapterErrorCode {
InvalidParams = "INVALID_PARAMS",
InvalidResults = "INVALID_RESULTS",
UniqueConstraint = "UNIQUE_CONSTRAINT",
ForeignkeyConstraint = "FOREIGNKEY_CONSTRAINT",
NotnullConstraint = "NOTNULL_CONSTRAINT",
CheckConstraint = "CHECK_CONSTRAINT",
PrimarykeyConstraint = "PRIMARYKEY_CONSTRAINT",
NoResult = "NO_RESULT",
Generic = "GENERIC"
InvalidParams = "INVALID_PARAMS",
InvalidResults = "INVALID_RESULTS",
UniqueConstraint = "UNIQUE_CONSTRAINT",
ForeignkeyConstraint = "FOREIGNKEY_CONSTRAINT",
NotnullConstraint = "NOTNULL_CONSTRAINT",
CheckConstraint = "CHECK_CONSTRAINT",
PrimarykeyConstraint = "PRIMARYKEY_CONSTRAINT",
NoResult = "NO_RESULT",
Generic = "GENERIC"
}
declare class BaseAdapterError extends Error {
code: AdapterErrorCode;
originalError?: Error | undefined;
constructor(message: string, code: AdapterErrorCode, originalError?: Error | undefined);
isNoResultError: () => boolean;
code: AdapterErrorCode;
originalError?: Error | undefined;
constructor(message: string, code: AdapterErrorCode, originalError?: Error | undefined);
isNoResultError: () => boolean;
}
export { AdapterErrorCode, BaseAdapterError };
//#endregion
export { AdapterErrorCode, BaseAdapterError };

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

var I=Object.defineProperty;var s=(N,n)=>I(N,"name",{value:n,configurable:!0});var i=(N=>(N.InvalidParams="INVALID_PARAMS",N.InvalidResults="INVALID_RESULTS",N.UniqueConstraint="UNIQUE_CONSTRAINT",N.ForeignkeyConstraint="FOREIGNKEY_CONSTRAINT",N.NotnullConstraint="NOTNULL_CONSTRAINT",N.CheckConstraint="CHECK_CONSTRAINT",N.PrimarykeyConstraint="PRIMARYKEY_CONSTRAINT",N.NoResult="NO_RESULT",N.Generic="GENERIC",N))(i||{});class T extends Error{static{s(this,"BaseAdapterError")}constructor(n,t,R){super(n),this.code=t,this.originalError=R,this.name="AdapterError"}isNoResultError=s(()=>this.code==="NO_RESULT","isNoResultError")}export{i as AdapterErrorCode,T as BaseAdapterError};
let e=function(e){return e.InvalidParams=`INVALID_PARAMS`,e.InvalidResults=`INVALID_RESULTS`,e.UniqueConstraint=`UNIQUE_CONSTRAINT`,e.ForeignkeyConstraint=`FOREIGNKEY_CONSTRAINT`,e.NotnullConstraint=`NOTNULL_CONSTRAINT`,e.CheckConstraint=`CHECK_CONSTRAINT`,e.PrimarykeyConstraint=`PRIMARYKEY_CONSTRAINT`,e.NoResult=`NO_RESULT`,e.Generic=`GENERIC`,e}({});var t=class extends Error{constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.isNoResultError=()=>this.code===`NO_RESULT`,this.name=`AdapterError`}};export{e as AdapterErrorCode,t as BaseAdapterError};

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

"use strict";var d=Object.defineProperty;var n=(i,e)=>d(i,"name",{value:e,configurable:!0});var a=require("./baseAdapterError.cjs");class c{static{n(this,"BetterSqlite3Adapter")}constructor(e){this.db=e}queryAll=n(e=>{let r;try{r=this.db.prepare(e)}catch(t){throw s.createFromBetterSqlite3(t)}return t=>{try{return t?r.all(t):r.all()}catch(o){if(o instanceof TypeError&&o.message==="This statement does not return data. Use run() instead")return this.handleTypeErrorRun(r,t),[];throw s.createFromBetterSqlite3(o)}}},"queryAll");queryFirst=n(e=>{let r;try{r=this.db.prepare(e)}catch(t){throw s.createFromBetterSqlite3(t)}return t=>{try{return t?r.get(t):r.get()}catch(o){if(o instanceof TypeError&&o.message==="This statement does not return data. Use run() instead"){this.handleTypeErrorRun(r,t);return}throw s.createFromBetterSqlite3(o)}}},"queryFirst");queryFirstOrThrow=n(e=>{const r=this.queryFirst(e);return t=>{const o=r(t);if(o===void 0)throw new s("No result",a.AdapterErrorCode.NoResult);return o}},"queryFirstOrThrow");queryIterate=n(e=>{const r=this.db.prepare(e);return t=>t?r.iterate(t):r.iterate()},"queryIterate");handleTypeErrorRun=n((e,r)=>{try{r?e.run(r):e.run()}catch(t){throw s.createFromBetterSqlite3(t)}},"handleTypeErrorRun")}class s extends a.BaseAdapterError{static{n(this,"SchemQlAdapterError")}static createFromBetterSqlite3=n(e=>{const r=new Map([["SQLITE_CONSTRAINT_UNIQUE",a.AdapterErrorCode.UniqueConstraint],["SQLITE_CONSTRAINT_FOREIGNKEY",a.AdapterErrorCode.ForeignkeyConstraint],["SQLITE_CONSTRAINT_NOTNULL",a.AdapterErrorCode.NotnullConstraint],["SQLITE_CONSTRAINT_CHECK",a.AdapterErrorCode.CheckConstraint],["SQLITE_CONSTRAINT_PRIMARYKEY",a.AdapterErrorCode.PrimarykeyConstraint]]);return new s(e.message,r.get(e.code)??a.AdapterErrorCode.Generic,e)},"createFromBetterSqlite3")}exports.SchemQlAdapterErrorCode=a.AdapterErrorCode,exports.BetterSqlite3Adapter=c,exports.SchemQlAdapterError=s;
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./baseAdapterError.cjs");var t=class{constructor(e){this.db=e,this.queryAll=e=>{let t;try{t=this.db.prepare(e)}catch(e){throw n.createFromBetterSqlite3(e)}return e=>{try{return e?t.all(e):t.all()}catch(r){if(r instanceof TypeError&&r.message===`This statement does not return data. Use run() instead`)return this.handleTypeErrorRun(t,e),[];throw n.createFromBetterSqlite3(r)}}},this.queryFirst=e=>{let t;try{t=this.db.prepare(e)}catch(e){throw n.createFromBetterSqlite3(e)}return e=>{try{return e?t.get(e):t.get()}catch(r){if(r instanceof TypeError&&r.message===`This statement does not return data. Use run() instead`){this.handleTypeErrorRun(t,e);return}throw n.createFromBetterSqlite3(r)}}},this.queryFirstOrThrow=e=>{let t=this.queryFirst(e);return e=>{let r=t(e);if(r===void 0)throw new n(`No result`,`NO_RESULT`);return r}},this.queryIterate=e=>{let t=this.db.prepare(e);return e=>e?t.iterate(e):t.iterate()},this.handleTypeErrorRun=(e,t)=>{try{t?e.run(t):e.run()}catch(e){throw n.createFromBetterSqlite3(e)}}}},n=class t extends e.BaseAdapterError{static{this.createFromBetterSqlite3=e=>{let n=new Map([[`SQLITE_CONSTRAINT_UNIQUE`,`UNIQUE_CONSTRAINT`],[`SQLITE_CONSTRAINT_FOREIGNKEY`,`FOREIGNKEY_CONSTRAINT`],[`SQLITE_CONSTRAINT_NOTNULL`,`NOTNULL_CONSTRAINT`],[`SQLITE_CONSTRAINT_CHECK`,`CHECK_CONSTRAINT`],[`SQLITE_CONSTRAINT_PRIMARYKEY`,`PRIMARYKEY_CONSTRAINT`]]);return new t(e.message,n.get(e.code)??`GENERIC`,e)}}};exports.BetterSqlite3Adapter=t,exports.SchemQlAdapterError=n,exports.SchemQlAdapterErrorCode=e.AdapterErrorCode;

@@ -1,22 +0,19 @@

import { BaseAdapterError } from './baseAdapterError.cjs';
export { AdapterErrorCode as SchemQlAdapterErrorCode } from './baseAdapterError.cjs';
import { S as SchemQlAdapter } from '../schemql-DY-sGX-S.cjs';
import '@standard-schema/spec';
import { AdapterErrorCode, BaseAdapterError } from "./baseAdapterError.cjs";
import { n as SchemQlAdapter } from "../schemql-oq-xONEF.cjs";
import * as SQLite from "better-sqlite3";
module.exports = require('./database');
module.exports.SqliteError = require('./sqlite-error');
//#region src/adapters/betterSqlite3Adapter.d.ts
declare class BetterSqlite3Adapter<T = unknown> implements SchemQlAdapter<T> {
private db;
constructor(db: undefined);
queryAll: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult[];
queryFirst: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult | undefined;
queryFirstOrThrow: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => NonNullable<TResult>;
queryIterate: <_TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => any;
private handleTypeErrorRun;
private db;
constructor(db: SQLite.Database);
queryAll: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult[];
queryFirst: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult | undefined;
queryFirstOrThrow: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => NonNullable<TResult>;
queryIterate: <_TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => any;
private handleTypeErrorRun;
}
declare class SchemQlAdapterError extends BaseAdapterError {
static createFromBetterSqlite3: (error: undefined | TypeError) => SchemQlAdapterError;
static createFromBetterSqlite3: (error: SQLite.SqliteError | TypeError) => SchemQlAdapterError;
}
export { BetterSqlite3Adapter, SchemQlAdapterError };
//#endregion
export { BetterSqlite3Adapter, SchemQlAdapterError, AdapterErrorCode as SchemQlAdapterErrorCode };

@@ -1,22 +0,19 @@

import { BaseAdapterError } from './baseAdapterError.mjs';
export { AdapterErrorCode as SchemQlAdapterErrorCode } from './baseAdapterError.mjs';
import { S as SchemQlAdapter } from '../schemql-DY-sGX-S.mjs';
import '@standard-schema/spec';
import { AdapterErrorCode, BaseAdapterError } from "./baseAdapterError.mjs";
import { n as SchemQlAdapter } from "../schemql-oq-xONEF.mjs";
import * as SQLite from "better-sqlite3";
module.exports = require('./database');
module.exports.SqliteError = require('./sqlite-error');
//#region src/adapters/betterSqlite3Adapter.d.ts
declare class BetterSqlite3Adapter<T = unknown> implements SchemQlAdapter<T> {
private db;
constructor(db: undefined);
queryAll: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult[];
queryFirst: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult | undefined;
queryFirstOrThrow: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => NonNullable<TResult>;
queryIterate: <_TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => any;
private handleTypeErrorRun;
private db;
constructor(db: SQLite.Database);
queryAll: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult[];
queryFirst: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult | undefined;
queryFirstOrThrow: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => NonNullable<TResult>;
queryIterate: <_TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => any;
private handleTypeErrorRun;
}
declare class SchemQlAdapterError extends BaseAdapterError {
static createFromBetterSqlite3: (error: undefined | TypeError) => SchemQlAdapterError;
static createFromBetterSqlite3: (error: SQLite.SqliteError | TypeError) => SchemQlAdapterError;
}
export { BetterSqlite3Adapter, SchemQlAdapterError };
//#endregion
export { BetterSqlite3Adapter, SchemQlAdapterError, AdapterErrorCode as SchemQlAdapterErrorCode };

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

var c=Object.defineProperty;var o=(a,t)=>c(a,"name",{value:t,configurable:!0});import{AdapterErrorCode as i,BaseAdapterError as u}from"./baseAdapterError.mjs";class h{static{o(this,"BetterSqlite3Adapter")}constructor(t){this.db=t}queryAll=o(t=>{let e;try{e=this.db.prepare(t)}catch(r){throw s.createFromBetterSqlite3(r)}return r=>{try{return r?e.all(r):e.all()}catch(n){if(n instanceof TypeError&&n.message==="This statement does not return data. Use run() instead")return this.handleTypeErrorRun(e,r),[];throw s.createFromBetterSqlite3(n)}}},"queryAll");queryFirst=o(t=>{let e;try{e=this.db.prepare(t)}catch(r){throw s.createFromBetterSqlite3(r)}return r=>{try{return r?e.get(r):e.get()}catch(n){if(n instanceof TypeError&&n.message==="This statement does not return data. Use run() instead"){this.handleTypeErrorRun(e,r);return}throw s.createFromBetterSqlite3(n)}}},"queryFirst");queryFirstOrThrow=o(t=>{const e=this.queryFirst(t);return r=>{const n=e(r);if(n===void 0)throw new s("No result",i.NoResult);return n}},"queryFirstOrThrow");queryIterate=o(t=>{const e=this.db.prepare(t);return r=>r?e.iterate(r):e.iterate()},"queryIterate");handleTypeErrorRun=o((t,e)=>{try{e?t.run(e):t.run()}catch(r){throw s.createFromBetterSqlite3(r)}},"handleTypeErrorRun")}class s extends u{static{o(this,"SchemQlAdapterError")}static createFromBetterSqlite3=o(t=>{const e=new Map([["SQLITE_CONSTRAINT_UNIQUE",i.UniqueConstraint],["SQLITE_CONSTRAINT_FOREIGNKEY",i.ForeignkeyConstraint],["SQLITE_CONSTRAINT_NOTNULL",i.NotnullConstraint],["SQLITE_CONSTRAINT_CHECK",i.CheckConstraint],["SQLITE_CONSTRAINT_PRIMARYKEY",i.PrimarykeyConstraint]]);return new s(t.message,e.get(t.code)??i.Generic,t)},"createFromBetterSqlite3")}export{h as BetterSqlite3Adapter,s as SchemQlAdapterError,i as SchemQlAdapterErrorCode};
import{AdapterErrorCode as e,BaseAdapterError as t}from"./baseAdapterError.mjs";var n=class{constructor(e){this.db=e,this.queryAll=e=>{let t;try{t=this.db.prepare(e)}catch(e){throw r.createFromBetterSqlite3(e)}return e=>{try{return e?t.all(e):t.all()}catch(n){if(n instanceof TypeError&&n.message===`This statement does not return data. Use run() instead`)return this.handleTypeErrorRun(t,e),[];throw r.createFromBetterSqlite3(n)}}},this.queryFirst=e=>{let t;try{t=this.db.prepare(e)}catch(e){throw r.createFromBetterSqlite3(e)}return e=>{try{return e?t.get(e):t.get()}catch(n){if(n instanceof TypeError&&n.message===`This statement does not return data. Use run() instead`){this.handleTypeErrorRun(t,e);return}throw r.createFromBetterSqlite3(n)}}},this.queryFirstOrThrow=e=>{let t=this.queryFirst(e);return e=>{let n=t(e);if(n===void 0)throw new r(`No result`,`NO_RESULT`);return n}},this.queryIterate=e=>{let t=this.db.prepare(e);return e=>e?t.iterate(e):t.iterate()},this.handleTypeErrorRun=(e,t)=>{try{t?e.run(t):e.run()}catch(e){throw r.createFromBetterSqlite3(e)}}}},r=class e extends t{static{this.createFromBetterSqlite3=t=>{let n=new Map([[`SQLITE_CONSTRAINT_UNIQUE`,`UNIQUE_CONSTRAINT`],[`SQLITE_CONSTRAINT_FOREIGNKEY`,`FOREIGNKEY_CONSTRAINT`],[`SQLITE_CONSTRAINT_NOTNULL`,`NOTNULL_CONSTRAINT`],[`SQLITE_CONSTRAINT_CHECK`,`CHECK_CONSTRAINT`],[`SQLITE_CONSTRAINT_PRIMARYKEY`,`PRIMARYKEY_CONSTRAINT`]]);return new e(t.message,n.get(t.code)??`GENERIC`,t)}}};export{n as BetterSqlite3Adapter,r as SchemQlAdapterError,e as SchemQlAdapterErrorCode};

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

"use strict";var p=Object.defineProperty;var e=(u,r)=>p(u,"name",{value:r,configurable:!0});var i=require("./baseAdapterError.cjs");class h{static{e(this,"D1Adapter")}constructor(r,t={verbosity:0}){this.db=r,this.options=t}queryAll=e(r=>{const{sql:t,paramsOrder:o}=this.transformToAnonymousParams(r),n=this.db.prepare(t);return async a=>{try{const s=a?o.map(l=>a[l]):[],{results:c}=await n.bind(...s).all();return this.options.verbosity&&this.logSql(t,s,this.options.verbosity),c}catch(s){throw d.createFromD1(s)}}},"queryAll");queryFirst=e(r=>{const{sql:t,paramsOrder:o}=this.transformToAnonymousParams(r),n=this.db.prepare(t);return async a=>{try{const s=a?o.map(l=>a[l]):[],c=await n.bind(...s).first()??void 0;return this.options.verbosity&&this.logSql(t,s,this.options.verbosity),c}catch(s){throw d.createFromD1(s)}}},"queryFirst");queryFirstOrThrow=e(r=>{const t=this.queryFirst(r);return async o=>{const n=await t(o);if(n===void 0)throw new d("No result",i.AdapterErrorCode.NoResult);return n}},"queryFirstOrThrow");queryIterate=e(r=>t=>{throw new Error("Not implemented")},"queryIterate");transformToAnonymousParams=e(r=>{const t=[];return{sql:r.replace(/:([a-zA-Z0-9_]+)/g,(n,a)=>(t.push(a),"?")),paramsOrder:t}},"transformToAnonymousParams");logSql=e((r,t,o)=>{const n=t.map(c=>typeof c=="string"?`'${c}'`:c===null?"NULL":c);let a=0;const s=r.replace(/\?/g,()=>n[a++]??"?");console.log(`${o>1?`
-- PREPARED --
${r}`:""}
++ EXECUTED ++
${s}
`)},"logSql")}class d extends i.BaseAdapterError{static{e(this,"SchemQlAdapterError")}static createFromD1=e(r=>{const t=e(o=>{if(o.startsWith("D1_ERROR:")){if(o.startsWith("D1_ERROR: UNIQUE constraint failed"))return i.AdapterErrorCode.UniqueConstraint;if(o.startsWith("D1_ERROR: FOREIGN KEY constraint failed"))return i.AdapterErrorCode.ForeignkeyConstraint;if(o.startsWith("D1_ERROR: NOT NULL constraint failed"))return i.AdapterErrorCode.NotnullConstraint;if(o.startsWith("D1_ERROR: CHECK constraint failed"))return i.AdapterErrorCode.CheckConstraint;if(o.startsWith("D1_ERROR: PRIMARY KEY constraint failed"))return i.AdapterErrorCode.PrimarykeyConstraint}return i.AdapterErrorCode.Generic},"computeCode");return new d(r.message,t(r.message),r)},"createFromD1")}exports.SchemQlAdapterErrorCode=i.AdapterErrorCode,exports.D1Adapter=h,exports.SchemQlAdapterError=d;
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./baseAdapterError.cjs");var t=class{constructor(e,t={verbosity:0}){this.db=e,this.options=t,this.queryAll=e=>{let{sql:t,paramsOrder:r}=this.transformToAnonymousParams(e),i=this.db.prepare(t);return async e=>{try{let n=e?r.map(t=>e[t]):[],{results:a}=await i.bind(...n).all();return this.options.verbosity&&this.logSql(t,n,this.options.verbosity),a}catch(e){throw n.createFromD1(e)}}},this.queryFirst=e=>{let{sql:t,paramsOrder:r}=this.transformToAnonymousParams(e),i=this.db.prepare(t);return async e=>{try{let n=e?r.map(t=>e[t]):[],a=await i.bind(...n).first()??void 0;return this.options.verbosity&&this.logSql(t,n,this.options.verbosity),a}catch(e){throw n.createFromD1(e)}}},this.queryFirstOrThrow=e=>{let t=this.queryFirst(e);return async e=>{let r=await t(e);if(r===void 0)throw new n(`No result`,`NO_RESULT`);return r}},this.queryIterate=e=>e=>{throw Error(`Not implemented`)},this.transformToAnonymousParams=e=>{let t=[];return{sql:e.replace(/:([a-zA-Z0-9_]+)/g,(e,n)=>(t.push(n),`?`)),paramsOrder:t}},this.logSql=(e,t,n)=>{let r=t.map(e=>typeof e==`string`?`'${e}'`:e===null?`NULL`:e),i=0,a=e.replace(/\?/g,()=>r[i++]??`?`);console.log(`${n>1?`\n-- PREPARED --\n${e}`:``}\n++ EXECUTED ++\n${a}\n`)}}},n=class t extends e.BaseAdapterError{static{this.createFromD1=e=>new t(e.message,(e=>{if(e.startsWith(`D1_ERROR:`)){if(e.startsWith(`D1_ERROR: UNIQUE constraint failed`))return`UNIQUE_CONSTRAINT`;if(e.startsWith(`D1_ERROR: FOREIGN KEY constraint failed`))return`FOREIGNKEY_CONSTRAINT`;if(e.startsWith(`D1_ERROR: NOT NULL constraint failed`))return`NOTNULL_CONSTRAINT`;if(e.startsWith(`D1_ERROR: CHECK constraint failed`))return`CHECK_CONSTRAINT`;if(e.startsWith(`D1_ERROR: PRIMARY KEY constraint failed`))return`PRIMARYKEY_CONSTRAINT`}return`GENERIC`})(e.message),e)}};exports.D1Adapter=t,exports.SchemQlAdapterError=n,exports.SchemQlAdapterErrorCode=e.AdapterErrorCode;

@@ -1,113 +0,23 @@

import { BaseAdapterError } from './baseAdapterError.cjs';
export { AdapterErrorCode as SchemQlAdapterErrorCode } from './baseAdapterError.cjs';
import { S as SchemQlAdapter } from '../schemql-DY-sGX-S.cjs';
import '@standard-schema/spec';
import { AdapterErrorCode, BaseAdapterError } from "./baseAdapterError.cjs";
import { n as SchemQlAdapter } from "../schemql-oq-xONEF.cjs";
import { D1Database } from "@cloudflare/workers-types";
interface D1Meta {
duration: number;
size_after: number;
rows_read: number;
rows_written: number;
last_row_id: number;
changed_db: boolean;
changes: number;
/**
* The region of the database instance that executed the query.
*/
served_by_region?: string;
/**
* True if-and-only-if the database instance that executed the query was the primary.
*/
served_by_primary?: boolean;
timings?: {
/**
* The duration of the SQL query execution by the database instance. It doesn't include any network time.
*/
sql_duration_ms: number;
};
/**
* Number of total attempts to execute the query, due to automatic retries.
* Note: All other fields in the response like `timings` only apply to the last attempt.
*/
total_attempts?: number;
}
interface D1Response {
success: true;
meta: D1Meta & Record<string, unknown>;
error?: never;
}
type D1Result<T = unknown> = D1Response & {
results: T[];
};
interface D1ExecResult {
count: number;
duration: number;
}
type D1SessionConstraint =
// Indicates that the first query should go to the primary, and the rest queries
// using the same D1DatabaseSession will go to any replica that is consistent with
// the bookmark maintained by the session (returned by the first query).
| "first-primary"
// Indicates that the first query can go anywhere (primary or replica), and the rest queries
// using the same D1DatabaseSession will go to any replica that is consistent with
// the bookmark maintained by the session (returned by the first query).
| "first-unconstrained";
type D1SessionBookmark = string;
declare abstract class D1Database {
prepare(query: string): D1PreparedStatement;
batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;
exec(query: string): Promise<D1ExecResult>;
/**
* Creates a new D1 Session anchored at the given constraint or the bookmark.
* All queries executed using the created session will have sequential consistency,
* meaning that all writes done through the session will be visible in subsequent reads.
*
* @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session.
*/
withSession(
constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint,
): D1DatabaseSession;
/**
* @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases.
*/
dump(): Promise<ArrayBuffer>;
}
declare abstract class D1DatabaseSession {
prepare(query: string): D1PreparedStatement;
batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;
/**
* @returns The latest session bookmark across all executed queries on the session.
* If no query has been executed yet, `null` is returned.
*/
getBookmark(): D1SessionBookmark | null;
}
declare abstract class D1PreparedStatement {
bind(...values: unknown[]): D1PreparedStatement;
first<T = unknown>(colName: string): Promise<T | null>;
first<T = Record<string, unknown>>(): Promise<T | null>;
run<T = Record<string, unknown>>(): Promise<D1Result<T>>;
all<T = Record<string, unknown>>(): Promise<D1Result<T>>;
raw<T = unknown[]>(options: {
columnNames: true;
}): Promise<[string[], ...T[]]>;
raw<T = unknown[]>(options?: { columnNames?: false }): Promise<T[]>;
}
//#region src/adapters/d1Adapter.d.ts
declare class D1Adapter<T = unknown> implements SchemQlAdapter<T> {
private db;
private options;
constructor(db: D1Database, options?: {
verbosity: number;
});
queryAll: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => Promise<TResult[]>;
queryFirst: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => Promise<NonNullable<Awaited<TResult>> | undefined>;
queryFirstOrThrow: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => Promise<NonNullable<Awaited<TResult>>>;
queryIterate: <_TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(_sql: string) => (_params?: TParams) => never;
private transformToAnonymousParams;
private logSql;
private db;
private options;
constructor(db: D1Database, options?: {
verbosity: number;
});
queryAll: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => Promise<TResult[]>;
queryFirst: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => Promise<NonNullable<Awaited<TResult>> | undefined>;
queryFirstOrThrow: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => Promise<NonNullable<Awaited<TResult>>>;
queryIterate: <_TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(_sql: string) => (_params?: TParams) => never;
private transformToAnonymousParams;
private logSql;
}
declare class SchemQlAdapterError extends BaseAdapterError {
static createFromD1: (error: Error) => SchemQlAdapterError;
static createFromD1: (error: Error) => SchemQlAdapterError;
}
export { D1Adapter, SchemQlAdapterError };
//#endregion
export { D1Adapter, SchemQlAdapterError, AdapterErrorCode as SchemQlAdapterErrorCode };

@@ -1,113 +0,23 @@

import { BaseAdapterError } from './baseAdapterError.mjs';
export { AdapterErrorCode as SchemQlAdapterErrorCode } from './baseAdapterError.mjs';
import { S as SchemQlAdapter } from '../schemql-DY-sGX-S.mjs';
import '@standard-schema/spec';
import { AdapterErrorCode, BaseAdapterError } from "./baseAdapterError.mjs";
import { n as SchemQlAdapter } from "../schemql-oq-xONEF.mjs";
import { D1Database } from "@cloudflare/workers-types";
interface D1Meta {
duration: number;
size_after: number;
rows_read: number;
rows_written: number;
last_row_id: number;
changed_db: boolean;
changes: number;
/**
* The region of the database instance that executed the query.
*/
served_by_region?: string;
/**
* True if-and-only-if the database instance that executed the query was the primary.
*/
served_by_primary?: boolean;
timings?: {
/**
* The duration of the SQL query execution by the database instance. It doesn't include any network time.
*/
sql_duration_ms: number;
};
/**
* Number of total attempts to execute the query, due to automatic retries.
* Note: All other fields in the response like `timings` only apply to the last attempt.
*/
total_attempts?: number;
}
interface D1Response {
success: true;
meta: D1Meta & Record<string, unknown>;
error?: never;
}
type D1Result<T = unknown> = D1Response & {
results: T[];
};
interface D1ExecResult {
count: number;
duration: number;
}
type D1SessionConstraint =
// Indicates that the first query should go to the primary, and the rest queries
// using the same D1DatabaseSession will go to any replica that is consistent with
// the bookmark maintained by the session (returned by the first query).
| "first-primary"
// Indicates that the first query can go anywhere (primary or replica), and the rest queries
// using the same D1DatabaseSession will go to any replica that is consistent with
// the bookmark maintained by the session (returned by the first query).
| "first-unconstrained";
type D1SessionBookmark = string;
declare abstract class D1Database {
prepare(query: string): D1PreparedStatement;
batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;
exec(query: string): Promise<D1ExecResult>;
/**
* Creates a new D1 Session anchored at the given constraint or the bookmark.
* All queries executed using the created session will have sequential consistency,
* meaning that all writes done through the session will be visible in subsequent reads.
*
* @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session.
*/
withSession(
constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint,
): D1DatabaseSession;
/**
* @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases.
*/
dump(): Promise<ArrayBuffer>;
}
declare abstract class D1DatabaseSession {
prepare(query: string): D1PreparedStatement;
batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;
/**
* @returns The latest session bookmark across all executed queries on the session.
* If no query has been executed yet, `null` is returned.
*/
getBookmark(): D1SessionBookmark | null;
}
declare abstract class D1PreparedStatement {
bind(...values: unknown[]): D1PreparedStatement;
first<T = unknown>(colName: string): Promise<T | null>;
first<T = Record<string, unknown>>(): Promise<T | null>;
run<T = Record<string, unknown>>(): Promise<D1Result<T>>;
all<T = Record<string, unknown>>(): Promise<D1Result<T>>;
raw<T = unknown[]>(options: {
columnNames: true;
}): Promise<[string[], ...T[]]>;
raw<T = unknown[]>(options?: { columnNames?: false }): Promise<T[]>;
}
//#region src/adapters/d1Adapter.d.ts
declare class D1Adapter<T = unknown> implements SchemQlAdapter<T> {
private db;
private options;
constructor(db: D1Database, options?: {
verbosity: number;
});
queryAll: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => Promise<TResult[]>;
queryFirst: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => Promise<NonNullable<Awaited<TResult>> | undefined>;
queryFirstOrThrow: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => Promise<NonNullable<Awaited<TResult>>>;
queryIterate: <_TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(_sql: string) => (_params?: TParams) => never;
private transformToAnonymousParams;
private logSql;
private db;
private options;
constructor(db: D1Database, options?: {
verbosity: number;
});
queryAll: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => Promise<TResult[]>;
queryFirst: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => Promise<NonNullable<Awaited<TResult>> | undefined>;
queryFirstOrThrow: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => Promise<NonNullable<Awaited<TResult>>>;
queryIterate: <_TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(_sql: string) => (_params?: TParams) => never;
private transformToAnonymousParams;
private logSql;
}
declare class SchemQlAdapterError extends BaseAdapterError {
static createFromD1: (error: Error) => SchemQlAdapterError;
static createFromD1: (error: Error) => SchemQlAdapterError;
}
export { D1Adapter, SchemQlAdapterError };
//#endregion
export { D1Adapter, SchemQlAdapterError, AdapterErrorCode as SchemQlAdapterErrorCode };

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

var m=Object.defineProperty;var o=(h,t)=>m(h,"name",{value:t,configurable:!0});import{AdapterErrorCode as c,BaseAdapterError as p}from"./baseAdapterError.mjs";class d{static{o(this,"D1Adapter")}constructor(t,r={verbosity:0}){this.db=t,this.options=r}queryAll=o(t=>{const{sql:r,paramsOrder:s}=this.transformToAnonymousParams(t),e=this.db.prepare(r);return async a=>{try{const n=a?s.map(u=>a[u]):[],{results:i}=await e.bind(...n).all();return this.options.verbosity&&this.logSql(r,n,this.options.verbosity),i}catch(n){throw l.createFromD1(n)}}},"queryAll");queryFirst=o(t=>{const{sql:r,paramsOrder:s}=this.transformToAnonymousParams(t),e=this.db.prepare(r);return async a=>{try{const n=a?s.map(u=>a[u]):[],i=await e.bind(...n).first()??void 0;return this.options.verbosity&&this.logSql(r,n,this.options.verbosity),i}catch(n){throw l.createFromD1(n)}}},"queryFirst");queryFirstOrThrow=o(t=>{const r=this.queryFirst(t);return async s=>{const e=await r(s);if(e===void 0)throw new l("No result",c.NoResult);return e}},"queryFirstOrThrow");queryIterate=o(t=>r=>{throw new Error("Not implemented")},"queryIterate");transformToAnonymousParams=o(t=>{const r=[];return{sql:t.replace(/:([a-zA-Z0-9_]+)/g,(e,a)=>(r.push(a),"?")),paramsOrder:r}},"transformToAnonymousParams");logSql=o((t,r,s)=>{const e=r.map(i=>typeof i=="string"?`'${i}'`:i===null?"NULL":i);let a=0;const n=t.replace(/\?/g,()=>e[a++]??"?");console.log(`${s>1?`
-- PREPARED --
${t}`:""}
++ EXECUTED ++
${n}
`)},"logSql")}class l extends p{static{o(this,"SchemQlAdapterError")}static createFromD1=o(t=>{const r=o(s=>{if(s.startsWith("D1_ERROR:")){if(s.startsWith("D1_ERROR: UNIQUE constraint failed"))return c.UniqueConstraint;if(s.startsWith("D1_ERROR: FOREIGN KEY constraint failed"))return c.ForeignkeyConstraint;if(s.startsWith("D1_ERROR: NOT NULL constraint failed"))return c.NotnullConstraint;if(s.startsWith("D1_ERROR: CHECK constraint failed"))return c.CheckConstraint;if(s.startsWith("D1_ERROR: PRIMARY KEY constraint failed"))return c.PrimarykeyConstraint}return c.Generic},"computeCode");return new l(t.message,r(t.message),t)},"createFromD1")}export{d as D1Adapter,l as SchemQlAdapterError,c as SchemQlAdapterErrorCode};
import{AdapterErrorCode as e,BaseAdapterError as t}from"./baseAdapterError.mjs";var n=class{constructor(e,t={verbosity:0}){this.db=e,this.options=t,this.queryAll=e=>{let{sql:t,paramsOrder:n}=this.transformToAnonymousParams(e),i=this.db.prepare(t);return async e=>{try{let r=e?n.map(t=>e[t]):[],{results:a}=await i.bind(...r).all();return this.options.verbosity&&this.logSql(t,r,this.options.verbosity),a}catch(e){throw r.createFromD1(e)}}},this.queryFirst=e=>{let{sql:t,paramsOrder:n}=this.transformToAnonymousParams(e),i=this.db.prepare(t);return async e=>{try{let r=e?n.map(t=>e[t]):[],a=await i.bind(...r).first()??void 0;return this.options.verbosity&&this.logSql(t,r,this.options.verbosity),a}catch(e){throw r.createFromD1(e)}}},this.queryFirstOrThrow=e=>{let t=this.queryFirst(e);return async e=>{let n=await t(e);if(n===void 0)throw new r(`No result`,`NO_RESULT`);return n}},this.queryIterate=e=>e=>{throw Error(`Not implemented`)},this.transformToAnonymousParams=e=>{let t=[];return{sql:e.replace(/:([a-zA-Z0-9_]+)/g,(e,n)=>(t.push(n),`?`)),paramsOrder:t}},this.logSql=(e,t,n)=>{let r=t.map(e=>typeof e==`string`?`'${e}'`:e===null?`NULL`:e),i=0,a=e.replace(/\?/g,()=>r[i++]??`?`);console.log(`${n>1?`\n-- PREPARED --\n${e}`:``}\n++ EXECUTED ++\n${a}\n`)}}},r=class e extends t{static{this.createFromD1=t=>new e(t.message,(e=>{if(e.startsWith(`D1_ERROR:`)){if(e.startsWith(`D1_ERROR: UNIQUE constraint failed`))return`UNIQUE_CONSTRAINT`;if(e.startsWith(`D1_ERROR: FOREIGN KEY constraint failed`))return`FOREIGNKEY_CONSTRAINT`;if(e.startsWith(`D1_ERROR: NOT NULL constraint failed`))return`NOTNULL_CONSTRAINT`;if(e.startsWith(`D1_ERROR: CHECK constraint failed`))return`CHECK_CONSTRAINT`;if(e.startsWith(`D1_ERROR: PRIMARY KEY constraint failed`))return`PRIMARYKEY_CONSTRAINT`}return`GENERIC`})(t.message),t)}};export{n as D1Adapter,r as SchemQlAdapterError,e as SchemQlAdapterErrorCode};

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

"use strict";var s=Object.defineProperty;var a=(d,t)=>s(d,"name",{value:t,configurable:!0});var i=require("./baseAdapterError.cjs");class c{static{a(this,"NodeSqliteAdapter")}constructor(t){this.db=t}queryAll=a(t=>{let e;try{e=this.db.prepare(t)}catch(r){throw n.createFromNodeSqlite(r)}return r=>{try{return r?e.all(r):e.all()}catch(o){throw n.createFromNodeSqlite(o)}}},"queryAll");queryFirst=a(t=>{let e;try{e=this.db.prepare(t)}catch(r){throw n.createFromNodeSqlite(r)}return r=>{try{return r?e.get(r):e.get()}catch(o){throw n.createFromNodeSqlite(o)}}},"queryFirst");queryFirstOrThrow=a(t=>{const e=this.queryFirst(t);return r=>{const o=e(r);if(o===void 0)throw new n("No result",i.AdapterErrorCode.NoResult);return o}},"queryFirstOrThrow");queryIterate=a(t=>{const e=this.db.prepare(t);return r=>r?e.iterate(r):e.iterate()},"queryIterate")}class n extends i.BaseAdapterError{static{a(this,"SchemQlAdapterError")}static createFromNodeSqlite=a(t=>{const e=a(({code:r,message:o})=>{if(r==="ERR_SQLITE_ERROR"){if(o.startsWith("UNIQUE constraint failed"))return i.AdapterErrorCode.UniqueConstraint;if(o.startsWith("FOREIGN KEY constraint failed"))return i.AdapterErrorCode.ForeignkeyConstraint;if(o.startsWith("NOT NULL constraint failed"))return i.AdapterErrorCode.NotnullConstraint;if(o.startsWith("CHECK constraint failed"))return i.AdapterErrorCode.CheckConstraint}return i.AdapterErrorCode.Generic},"computeCode");return new n(t.message,e(t),t)},"createFromNodeSqlite")}exports.SchemQlAdapterErrorCode=i.AdapterErrorCode,exports.NodeSqliteAdapter=c,exports.SchemQlAdapterError=n;
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./baseAdapterError.cjs");var t=class{constructor(e){this.db=e,this.queryAll=e=>{let t;try{t=this.db.prepare(e)}catch(e){throw n.createFromNodeSqlite(e)}return e=>{try{return e?t.all(e):t.all()}catch(e){throw n.createFromNodeSqlite(e)}}},this.queryFirst=e=>{let t;try{t=this.db.prepare(e)}catch(e){throw n.createFromNodeSqlite(e)}return e=>{try{return e?t.get(e):t.get()}catch(e){throw n.createFromNodeSqlite(e)}}},this.queryFirstOrThrow=e=>{let t=this.queryFirst(e);return e=>{let r=t(e);if(r===void 0)throw new n(`No result`,`NO_RESULT`);return r}},this.queryIterate=e=>{let t=this.db.prepare(e);return e=>e?t.iterate(e):t.iterate()}}},n=class t extends e.BaseAdapterError{static{this.createFromNodeSqlite=e=>new t(e.message,(({code:e,message:t})=>{if(e===`ERR_SQLITE_ERROR`){if(t.startsWith(`UNIQUE constraint failed`))return`UNIQUE_CONSTRAINT`;if(t.startsWith(`FOREIGN KEY constraint failed`))return`FOREIGNKEY_CONSTRAINT`;if(t.startsWith(`NOT NULL constraint failed`))return`NOTNULL_CONSTRAINT`;if(t.startsWith(`CHECK constraint failed`))return`CHECK_CONSTRAINT`}return`GENERIC`})(e),e)}};exports.NodeSqliteAdapter=t,exports.SchemQlAdapterError=n,exports.SchemQlAdapterErrorCode=e.AdapterErrorCode;

@@ -1,19 +0,18 @@

import SQLite from 'node:sqlite';
import { BaseAdapterError } from './baseAdapterError.cjs';
export { AdapterErrorCode as SchemQlAdapterErrorCode } from './baseAdapterError.cjs';
import { S as SchemQlAdapter } from '../schemql-DY-sGX-S.cjs';
import '@standard-schema/spec';
import { AdapterErrorCode, BaseAdapterError } from "./baseAdapterError.cjs";
import { n as SchemQlAdapter } from "../schemql-oq-xONEF.cjs";
import SQLite from "node:sqlite";
//#region src/adapters/nodeSqliteAdapter.d.ts
declare class NodeSqliteAdapter<T = unknown> implements SchemQlAdapter<T> {
private db;
constructor(db: SQLite.DatabaseSync);
queryAll: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult[];
queryFirst: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult | undefined;
queryFirstOrThrow: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => NonNullable<TResult>;
queryIterate: <_TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => any;
private db;
constructor(db: SQLite.DatabaseSync);
queryAll: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult[];
queryFirst: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult | undefined;
queryFirstOrThrow: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => NonNullable<TResult>;
queryIterate: <_TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => any;
}
declare class SchemQlAdapterError extends BaseAdapterError {
static createFromNodeSqlite: (error: any) => SchemQlAdapterError;
static createFromNodeSqlite: (error: any) => SchemQlAdapterError;
}
export { NodeSqliteAdapter, SchemQlAdapterError };
//#endregion
export { NodeSqliteAdapter, SchemQlAdapterError, AdapterErrorCode as SchemQlAdapterErrorCode };

@@ -1,19 +0,18 @@

import SQLite from 'node:sqlite';
import { BaseAdapterError } from './baseAdapterError.mjs';
export { AdapterErrorCode as SchemQlAdapterErrorCode } from './baseAdapterError.mjs';
import { S as SchemQlAdapter } from '../schemql-DY-sGX-S.mjs';
import '@standard-schema/spec';
import { AdapterErrorCode, BaseAdapterError } from "./baseAdapterError.mjs";
import { n as SchemQlAdapter } from "../schemql-oq-xONEF.mjs";
import SQLite from "node:sqlite";
//#region src/adapters/nodeSqliteAdapter.d.ts
declare class NodeSqliteAdapter<T = unknown> implements SchemQlAdapter<T> {
private db;
constructor(db: SQLite.DatabaseSync);
queryAll: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult[];
queryFirst: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult | undefined;
queryFirstOrThrow: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => NonNullable<TResult>;
queryIterate: <_TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => any;
private db;
constructor(db: SQLite.DatabaseSync);
queryAll: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult[];
queryFirst: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult | undefined;
queryFirstOrThrow: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => NonNullable<TResult>;
queryIterate: <_TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => any;
}
declare class SchemQlAdapterError extends BaseAdapterError {
static createFromNodeSqlite: (error: any) => SchemQlAdapterError;
static createFromNodeSqlite: (error: any) => SchemQlAdapterError;
}
export { NodeSqliteAdapter, SchemQlAdapterError };
//#endregion
export { NodeSqliteAdapter, SchemQlAdapterError, AdapterErrorCode as SchemQlAdapterErrorCode };

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

var c=Object.defineProperty;var o=(a,r)=>c(a,"name",{value:r,configurable:!0});import{AdapterErrorCode as s,BaseAdapterError as l}from"./baseAdapterError.mjs";class u{static{o(this,"NodeSqliteAdapter")}constructor(r){this.db=r}queryAll=o(r=>{let e;try{e=this.db.prepare(r)}catch(t){throw n.createFromNodeSqlite(t)}return t=>{try{return t?e.all(t):e.all()}catch(i){throw n.createFromNodeSqlite(i)}}},"queryAll");queryFirst=o(r=>{let e;try{e=this.db.prepare(r)}catch(t){throw n.createFromNodeSqlite(t)}return t=>{try{return t?e.get(t):e.get()}catch(i){throw n.createFromNodeSqlite(i)}}},"queryFirst");queryFirstOrThrow=o(r=>{const e=this.queryFirst(r);return t=>{const i=e(t);if(i===void 0)throw new n("No result",s.NoResult);return i}},"queryFirstOrThrow");queryIterate=o(r=>{const e=this.db.prepare(r);return t=>t?e.iterate(t):e.iterate()},"queryIterate")}class n extends l{static{o(this,"SchemQlAdapterError")}static createFromNodeSqlite=o(r=>{const e=o(({code:t,message:i})=>{if(t==="ERR_SQLITE_ERROR"){if(i.startsWith("UNIQUE constraint failed"))return s.UniqueConstraint;if(i.startsWith("FOREIGN KEY constraint failed"))return s.ForeignkeyConstraint;if(i.startsWith("NOT NULL constraint failed"))return s.NotnullConstraint;if(i.startsWith("CHECK constraint failed"))return s.CheckConstraint}return s.Generic},"computeCode");return new n(r.message,e(r),r)},"createFromNodeSqlite")}export{u as NodeSqliteAdapter,n as SchemQlAdapterError,s as SchemQlAdapterErrorCode};
import{AdapterErrorCode as e,BaseAdapterError as t}from"./baseAdapterError.mjs";var n=class{constructor(e){this.db=e,this.queryAll=e=>{let t;try{t=this.db.prepare(e)}catch(e){throw r.createFromNodeSqlite(e)}return e=>{try{return e?t.all(e):t.all()}catch(e){throw r.createFromNodeSqlite(e)}}},this.queryFirst=e=>{let t;try{t=this.db.prepare(e)}catch(e){throw r.createFromNodeSqlite(e)}return e=>{try{return e?t.get(e):t.get()}catch(e){throw r.createFromNodeSqlite(e)}}},this.queryFirstOrThrow=e=>{let t=this.queryFirst(e);return e=>{let n=t(e);if(n===void 0)throw new r(`No result`,`NO_RESULT`);return n}},this.queryIterate=e=>{let t=this.db.prepare(e);return e=>e?t.iterate(e):t.iterate()}}},r=class e extends t{static{this.createFromNodeSqlite=t=>new e(t.message,(({code:e,message:t})=>{if(e===`ERR_SQLITE_ERROR`){if(t.startsWith(`UNIQUE constraint failed`))return`UNIQUE_CONSTRAINT`;if(t.startsWith(`FOREIGN KEY constraint failed`))return`FOREIGNKEY_CONSTRAINT`;if(t.startsWith(`NOT NULL constraint failed`))return`NOTNULL_CONSTRAINT`;if(t.startsWith(`CHECK constraint failed`))return`CHECK_CONSTRAINT`}return`GENERIC`})(t),t)}};export{n as NodeSqliteAdapter,r as SchemQlAdapterError,e as SchemQlAdapterErrorCode};

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

"use strict";var m=Object.defineProperty;var a=(i,r)=>m(i,"name",{value:r,configurable:!0});class p{static{a(this,"SchemQl")}constructor(r){this.options=r,this.first=this.createQueryExecutor(this.options.adapter.queryFirst),this.firstOrThrow=this.createQueryExecutor(this.options.adapter.queryFirstOrThrow),this.all=this.createQueryExecutor(this.options.adapter.queryAll),this.iterate=this.createIterativeExecutor(this.options.adapter.queryIterate)}first;firstOrThrow;all;iterate;createQueryExecutor=a(r=>t=>async e=>{const s=typeof e=="function"?e(this.createSqlHelper()):e;if(typeof t.params=="function"){const h=r(s),d=a(async o=>{const u=await this.validateAndStringifyParams({...t,params:o}),l=await h(u);return t.resultSchema?await f(t.resultSchema,l):l},"executeAndValidateResult");return(async function*(){for await(const o of t.params())yield await d(o)})()}if(Array.isArray(t.params)){const h=r(s),d=await this.validateAndStringifyParams({...t,params:t.params}),o=a(async u=>{const l=await h(u);return t.resultSchema?await f(t.resultSchema,l):l},"executeAndValidateResult");return(async function*(){for(const u of d)yield await o(u)})()}const c=await this.validateAndStringifyParams({...t,params:t.params}),n=await r(s)(c);return t.resultSchema?await f(t.resultSchema,n):n},"createQueryExecutor");createIterativeExecutor=a(r=>t=>async e=>{const s=typeof e=="function"?e(this.createSqlHelper()):e,c=await this.validateAndStringifyParams({...t,params:t.params});return(async function*(){for await(const n of r(s)(c)())yield t.resultSchema?await f(t.resultSchema,n):n})()},"createIterativeExecutor");validateAndStringifyParams=a(async r=>{if(typeof r.params>"u")return;const t=r.paramsSchema?await f(r.paramsSchema,r.params):r.params;return this.options.shouldStringifyObjectParams||this.options.stringifyObjectParams?Array.isArray(t)?t.map(e=>y(e)):y(t):t},"validateAndStringifyParams");createSqlHelper=a(()=>({sql:a((r,...t)=>this.processLiteralExpressions(r,t),"sql"),sqlCond:a((r,t,e="")=>`\xA7${r?t:e}`,"sqlCond"),sqlRaw:a(r=>`\xA7${r}`,"sqlRaw")}),"createSqlHelper");processLiteralExpressions=a((r,t)=>r.reduce((e,s,c)=>{const n=t[c];return`${e}${s}${n!==void 0?this.processLiteralExpression(n):""}`},""),"processLiteralExpressions");processLiteralExpression=a(r=>{if(typeof r=="object"){const t=Object.entries(r);if(t.length===1){const[e,s]=t[0];return this.options.quoteSqlIdentifiers?`"${e}" ("${Array.isArray(s)?s.join('", "'):String(s)}")`:`${e} (${Array.isArray(s)?s.join(", "):String(s)})`}}if(typeof r=="string")switch(!0){case r.startsWith("@"):{const t=r.indexOf(" $.");if(t!==-1)return`'${r.slice(t+1)}'`;let e=r;const s=e.indexOf(" ->");if(s!==-1){const c=S(e.slice(s+1));e=`${e.slice(0,s)}${c}`}return e.endsWith("-")?e.split(".")[1]?.slice(0,-1)??"":e.slice(1)}case r.startsWith("$"):case r.startsWith("\xA7"):return r.slice(1);default:return r}return String(r)},"processLiteralExpression")}const y=a(i=>Object.entries(i).reduce((r,[t,e])=>(r[t]=e!==null&&typeof e=="object"?JSON.stringify(e):e,r),{}),"stringifyObjectParams"),S=a(i=>i.split(/(?=->)/).reduce((r,t)=>{const e=t.startsWith("->>")?"->>":"->",s=t.replace(e,"");return`${r}${e}'${s}'`},""),"quotifyJsonPath"),f=a(async(i,r)=>{let t=i["~standard"].validate(r);if(t instanceof Promise&&(t=await t),t.issues)throw new Error(`Validation failed: ${JSON.stringify(t.issues,null,2)}`);return t.value},"standardValidate"),w=a((i,r)=>{if(typeof i=="string")try{return JSON.parse(i)}catch(t){r.addIssue({code:"custom",message:t.message})}return i},"parseJsonPreprocessor");exports.SchemQl=p,exports.parseJsonPreprocessor=w;
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=class{constructor(e){this.options=e,this.createQueryExecutor=e=>t=>async n=>{let i=typeof n==`function`?n(this.createSqlHelper()):n;if(typeof t.params==`function`){let n=e(i),a=async e=>{let i=await n(await this.validateAndStringifyParams({...t,params:e}));return t.resultSchema?await r(t.resultSchema,i):i};return(async function*(){for await(let e of t.params())yield await a(e)})()}if(Array.isArray(t.params)){let n=e(i),a=await this.validateAndStringifyParams({...t,params:t.params}),o=async e=>{let i=await n(e);return t.resultSchema?await r(t.resultSchema,i):i};return(async function*(){for(let e of a)yield await o(e)})()}let a=await this.validateAndStringifyParams({...t,params:t.params}),o=await e(i)(a);return t.resultSchema?await r(t.resultSchema,o):o},this.createIterativeExecutor=e=>t=>async n=>{let i=typeof n==`function`?n(this.createSqlHelper()):n,a=await this.validateAndStringifyParams({...t,params:t.params});return(async function*(){for await(let n of e(i)(a)())yield t.resultSchema?await r(t.resultSchema,n):n})()},this.validateAndStringifyParams=async e=>{if(e.params===void 0)return;let n=e.paramsSchema?await r(e.paramsSchema,e.params):e.params;return this.options.shouldStringifyObjectParams||this.options.stringifyObjectParams?Array.isArray(n)?n.map(e=>t(e)):t(n):n},this.createSqlHelper=()=>({sql:(e,...t)=>this.processLiteralExpressions(e,t),sqlCond:(e,t,n=``)=>`§${e?t:n}`,sqlRaw:e=>`§${e}`}),this.processLiteralExpressions=(e,t)=>e.reduce((e,n,r)=>{let i=t[r];return`${e}${n}${i===void 0?``:this.processLiteralExpression(i)}`},``),this.processLiteralExpression=e=>{if(typeof e==`object`){let t=Object.entries(e);if(t.length===1){let[e,n]=t[0];return this.options.quoteSqlIdentifiers?`"${e}" ("${Array.isArray(n)?n.join(`", "`):String(n)}")`:`${e} (${Array.isArray(n)?n.join(`, `):String(n)})`}}if(typeof e==`string`)switch(!0){case e.startsWith(`@`):{let t=e.indexOf(` $.`);if(t!==-1)return`'${e.slice(t+1)}'`;let r=e,i=r.indexOf(` ->`);if(i!==-1){let e=n(r.slice(i+1));r=`${r.slice(0,i)}${e}`}return r.endsWith(`-`)?r.split(`.`)[1]?.slice(0,-1)??``:r.slice(1)}case e.startsWith(`$`):case e.startsWith(`§`):return e.slice(1);default:return e}return String(e)},this.first=this.createQueryExecutor(this.options.adapter.queryFirst),this.firstOrThrow=this.createQueryExecutor(this.options.adapter.queryFirstOrThrow),this.all=this.createQueryExecutor(this.options.adapter.queryAll),this.iterate=this.createIterativeExecutor(this.options.adapter.queryIterate)}};const t=e=>Object.entries(e).reduce((e,[t,n])=>(e[t]=typeof n==`object`&&n?JSON.stringify(n):n,e),{}),n=e=>e.split(/(?=->)/).reduce((e,t)=>{let n=t.startsWith(`->>`)?`->>`:`->`;return`${e}${n}'${t.replace(n,``)}'`},``),r=async(e,t)=>{let n=e[`~standard`].validate(t);if(n instanceof Promise&&(n=await n),n.issues)throw Error(`Validation failed: ${JSON.stringify(n.issues,null,2)}`);return n.value},i=(e,t)=>{if(typeof e==`string`)try{return JSON.parse(e)}catch(e){t.addIssue({code:`custom`,message:e.message})}return e};exports.SchemQl=e,exports.parseJsonPreprocessor=i;

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

var m=Object.defineProperty;var s=(i,r)=>m(i,"name",{value:r,configurable:!0});class p{static{s(this,"SchemQl")}constructor(r){this.options=r,this.first=this.createQueryExecutor(this.options.adapter.queryFirst),this.firstOrThrow=this.createQueryExecutor(this.options.adapter.queryFirstOrThrow),this.all=this.createQueryExecutor(this.options.adapter.queryAll),this.iterate=this.createIterativeExecutor(this.options.adapter.queryIterate)}first;firstOrThrow;all;iterate;createQueryExecutor=s(r=>t=>async e=>{const a=typeof e=="function"?e(this.createSqlHelper()):e;if(typeof t.params=="function"){const d=r(a),h=s(async o=>{const u=await this.validateAndStringifyParams({...t,params:o}),f=await d(u);return t.resultSchema?await l(t.resultSchema,f):f},"executeAndValidateResult");return(async function*(){for await(const o of t.params())yield await h(o)})()}if(Array.isArray(t.params)){const d=r(a),h=await this.validateAndStringifyParams({...t,params:t.params}),o=s(async u=>{const f=await d(u);return t.resultSchema?await l(t.resultSchema,f):f},"executeAndValidateResult");return(async function*(){for(const u of h)yield await o(u)})()}const c=await this.validateAndStringifyParams({...t,params:t.params}),n=await r(a)(c);return t.resultSchema?await l(t.resultSchema,n):n},"createQueryExecutor");createIterativeExecutor=s(r=>t=>async e=>{const a=typeof e=="function"?e(this.createSqlHelper()):e,c=await this.validateAndStringifyParams({...t,params:t.params});return(async function*(){for await(const n of r(a)(c)())yield t.resultSchema?await l(t.resultSchema,n):n})()},"createIterativeExecutor");validateAndStringifyParams=s(async r=>{if(typeof r.params>"u")return;const t=r.paramsSchema?await l(r.paramsSchema,r.params):r.params;return this.options.shouldStringifyObjectParams||this.options.stringifyObjectParams?Array.isArray(t)?t.map(e=>y(e)):y(t):t},"validateAndStringifyParams");createSqlHelper=s(()=>({sql:s((r,...t)=>this.processLiteralExpressions(r,t),"sql"),sqlCond:s((r,t,e="")=>`\xA7${r?t:e}`,"sqlCond"),sqlRaw:s(r=>`\xA7${r}`,"sqlRaw")}),"createSqlHelper");processLiteralExpressions=s((r,t)=>r.reduce((e,a,c)=>{const n=t[c];return`${e}${a}${n!==void 0?this.processLiteralExpression(n):""}`},""),"processLiteralExpressions");processLiteralExpression=s(r=>{if(typeof r=="object"){const t=Object.entries(r);if(t.length===1){const[e,a]=t[0];return this.options.quoteSqlIdentifiers?`"${e}" ("${Array.isArray(a)?a.join('", "'):String(a)}")`:`${e} (${Array.isArray(a)?a.join(", "):String(a)})`}}if(typeof r=="string")switch(!0){case r.startsWith("@"):{const t=r.indexOf(" $.");if(t!==-1)return`'${r.slice(t+1)}'`;let e=r;const a=e.indexOf(" ->");if(a!==-1){const c=w(e.slice(a+1));e=`${e.slice(0,a)}${c}`}return e.endsWith("-")?e.split(".")[1]?.slice(0,-1)??"":e.slice(1)}case r.startsWith("$"):case r.startsWith("\xA7"):return r.slice(1);default:return r}return String(r)},"processLiteralExpression")}const y=s(i=>Object.entries(i).reduce((r,[t,e])=>(r[t]=e!==null&&typeof e=="object"?JSON.stringify(e):e,r),{}),"stringifyObjectParams"),w=s(i=>i.split(/(?=->)/).reduce((r,t)=>{const e=t.startsWith("->>")?"->>":"->",a=t.replace(e,"");return`${r}${e}'${a}'`},""),"quotifyJsonPath"),l=s(async(i,r)=>{let t=i["~standard"].validate(r);if(t instanceof Promise&&(t=await t),t.issues)throw new Error(`Validation failed: ${JSON.stringify(t.issues,null,2)}`);return t.value},"standardValidate"),S=s((i,r)=>{if(typeof i=="string")try{return JSON.parse(i)}catch(t){r.addIssue({code:"custom",message:t.message})}return i},"parseJsonPreprocessor");export{p as SchemQl,S as parseJsonPreprocessor};
var e=class{constructor(e){this.options=e,this.createQueryExecutor=e=>t=>async n=>{let i=typeof n==`function`?n(this.createSqlHelper()):n;if(typeof t.params==`function`){let n=e(i),a=async e=>{let i=await n(await this.validateAndStringifyParams({...t,params:e}));return t.resultSchema?await r(t.resultSchema,i):i};return(async function*(){for await(let e of t.params())yield await a(e)})()}if(Array.isArray(t.params)){let n=e(i),a=await this.validateAndStringifyParams({...t,params:t.params}),o=async e=>{let i=await n(e);return t.resultSchema?await r(t.resultSchema,i):i};return(async function*(){for(let e of a)yield await o(e)})()}let a=await this.validateAndStringifyParams({...t,params:t.params}),o=await e(i)(a);return t.resultSchema?await r(t.resultSchema,o):o},this.createIterativeExecutor=e=>t=>async n=>{let i=typeof n==`function`?n(this.createSqlHelper()):n,a=await this.validateAndStringifyParams({...t,params:t.params});return(async function*(){for await(let n of e(i)(a)())yield t.resultSchema?await r(t.resultSchema,n):n})()},this.validateAndStringifyParams=async e=>{if(e.params===void 0)return;let n=e.paramsSchema?await r(e.paramsSchema,e.params):e.params;return this.options.shouldStringifyObjectParams||this.options.stringifyObjectParams?Array.isArray(n)?n.map(e=>t(e)):t(n):n},this.createSqlHelper=()=>({sql:(e,...t)=>this.processLiteralExpressions(e,t),sqlCond:(e,t,n=``)=>`§${e?t:n}`,sqlRaw:e=>`§${e}`}),this.processLiteralExpressions=(e,t)=>e.reduce((e,n,r)=>{let i=t[r];return`${e}${n}${i===void 0?``:this.processLiteralExpression(i)}`},``),this.processLiteralExpression=e=>{if(typeof e==`object`){let t=Object.entries(e);if(t.length===1){let[e,n]=t[0];return this.options.quoteSqlIdentifiers?`"${e}" ("${Array.isArray(n)?n.join(`", "`):String(n)}")`:`${e} (${Array.isArray(n)?n.join(`, `):String(n)})`}}if(typeof e==`string`)switch(!0){case e.startsWith(`@`):{let t=e.indexOf(` $.`);if(t!==-1)return`'${e.slice(t+1)}'`;let r=e,i=r.indexOf(` ->`);if(i!==-1){let e=n(r.slice(i+1));r=`${r.slice(0,i)}${e}`}return r.endsWith(`-`)?r.split(`.`)[1]?.slice(0,-1)??``:r.slice(1)}case e.startsWith(`$`):case e.startsWith(`§`):return e.slice(1);default:return e}return String(e)},this.first=this.createQueryExecutor(this.options.adapter.queryFirst),this.firstOrThrow=this.createQueryExecutor(this.options.adapter.queryFirstOrThrow),this.all=this.createQueryExecutor(this.options.adapter.queryAll),this.iterate=this.createIterativeExecutor(this.options.adapter.queryIterate)}};const t=e=>Object.entries(e).reduce((e,[t,n])=>(e[t]=typeof n==`object`&&n?JSON.stringify(n):n,e),{}),n=e=>e.split(/(?=->)/).reduce((e,t)=>{let n=t.startsWith(`->>`)?`->>`:`->`;return`${e}${n}'${t.replace(n,``)}'`},``),r=async(e,t)=>{let n=e[`~standard`].validate(t);if(n instanceof Promise&&(n=await n),n.issues)throw Error(`Validation failed: ${JSON.stringify(n.issues,null,2)}`);return n.value},i=(e,t)=>{if(typeof e==`string`)try{return JSON.parse(e)}catch(e){t.addIssue({code:`custom`,message:e.message})}return e};export{e as SchemQl,i as parseJsonPreprocessor};
{
"name": "@a2lix/schemql",
"version": "0.5.2",
"version": "0.5.3",
"description": "A lightweight TypeScript library that enhances your SQL workflow by combining raw SQL with targeted type safety and schema validation",

@@ -39,2 +39,5 @@ "license": "MIT",

"types": "./dist/index.d.ts",
"imports": {
"#*": "./src/*.ts"
},
"exports": {

@@ -99,19 +102,19 @@ ".": {

"devDependencies": {
"@biomejs/biome": "^2.3.9",
"@cloudflare/workers-types": "^4.20251011.0",
"@types/node": "^24.10.4",
"arktype": "^2.1.29",
"better-sqlite3": "^12.5.0",
"pkgroll": "^2.21.4",
"ts-node": "^10.9.2",
"tsx": "^4.21.0",
"typescript": "^5.9.3",
"zod": "^4.2.1"
"@cloudflare/workers-types": "^4.20260610.1",
"@types/node": "^24.13.1",
"arktype": "^2.2.0",
"better-sqlite3": "^12.10.0",
"oxfmt": "^0.54.0",
"oxlint": "^1.69.0",
"tsdown": "^0.22.2",
"tsx": "^4.22.4",
"typescript": "^6.0.3",
"zod": "^4.4.3"
},
"scripts": {
"biome": "biome check --write ./src ./tests",
"biome:ci": "biome ci ./src ./tests",
"lint": "oxlint ./src ./tests",
"format": "oxfmt ./src ./tests",
"test": "tsx --test './tests/**/*.test.ts'",
"build": "pkgroll --clean-dist --minify --src src/"
"build": "tsdown"
}
}

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

import { StandardSchemaV1 } from '@standard-schema/spec';
interface SchemQlAdapter<T = unknown> {
queryFirst: QueryFn<T | undefined>;
queryFirstOrThrow: QueryFn<T>;
queryAll: QueryFn<T[]>;
queryIterate: IterativeQueryFn<T>;
}
type QueryFn<TQueryResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined> = (sql: string) => (params?: TParams) => TQueryResult | Promise<TQueryResult>;
type IterativeQueryFn<TQueryResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined> = (sql: string) => (params?: TParams) => GeneratorFn<TQueryResult> | AsyncGeneratorFn<TQueryResult>;
type ArrayElement<T> = T extends (infer U)[] ? U : T;
type GeneratorFn<T> = () => Generator<T, void, unknown>;
type AsyncGeneratorFn<T> = () => AsyncGenerator<T, void, unknown>;
type TableNames<DB> = Extract<keyof DB, string>;
type ColumnNames<DB, T extends TableNames<DB>> = Extract<keyof DB[T], string>;
type TableColumnSelection<DB> = {
[T in TableNames<DB>]?: ColumnNames<DB, T>[];
};
type ValidTableColumnCombinations<DB> = {
[T in TableNames<DB>]: `${T}.${ColumnNames<DB, T>}` | `${T}.${ColumnNames<DB, T>}-`;
}[TableNames<DB>];
type JsonPathForObjectArrow<T, P extends string = ''> = T extends Record<string, any> ? {
[K in keyof T & string]: `${P}->${K}` | `${P}->${K}-` | `${P}->>${K}` | `${P}->>${K}-` | (NonNullable<T[K]> extends Record<string, any> ? `${P}->${K}${JsonPathForObjectArrow<NonNullable<T[K]>, ''>}` : never);
}[keyof T & string] : '';
type JsonPathForObjectDot<T, P extends string = ''> = T extends Record<string, any> ? {
[K in keyof T & string]: `${P}.${K}` | (NonNullable<T[K]> extends Record<string, any> ? `${P}.${K}${JsonPathForObjectDot<NonNullable<T[K]>, ''>}` : never);
}[keyof T & string] : '';
type JsonPathCombinations<DB, T extends TableNames<DB>> = {
[K in ColumnNames<DB, T>]: DB[T][K] extends object ? JsonPathForObjectArrow<ArrayElement<DB[T][K]>, `${T}.${K} `> | JsonPathForObjectDot<ArrayElement<DB[T][K]>, `${T}.${K} $`> : never;
}[ColumnNames<DB, T>];
type ValidJsonPathCombinations<DB> = {
[T in TableNames<DB>]: JsonPathCombinations<DB, T>;
}[TableNames<DB>];
type SqlTemplateValue<TResultSchema, TParams, DB> = TableColumnSelection<DB> | `@${TableNames<DB>}` | `@${TableNames<DB>}.*` | `@${ValidTableColumnCombinations<DB>}` | `@${ValidJsonPathCombinations<DB>}` | `$${keyof ArrayElement<Exclude<TResultSchema, undefined>> & string}` | `:${keyof TParams & string}` | `§${string}`;
type SqlTemplateValues<TResultSchema, TParams, DB> = SqlTemplateValue<TResultSchema, TParams, DB>[];
type SqlOrBuilderFn<TResultSchema extends StandardSchemaV1 | undefined, TParams extends Record<string, any>, DB> = string | ((s: SchemQlSqlHelper<TResultSchema, TParams, DB>) => string);
type SchemQlSqlHelper<TResultSchema extends StandardSchemaV1 | undefined, TParams extends Record<string, any>, DB> = {
sql: <T extends SqlTemplateValues<TResultSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TResultSchema> : unknown, TParams, DB>>(strings: TemplateStringsArray, ...values: T) => string;
sqlCond: (condition: boolean, ifTrue: string | number, ifFalse?: string | number) => `§${string}`;
sqlRaw: (raw: string | number) => `§${string}`;
};
type SchemQlOptions = {
readonly adapter: SchemQlAdapter;
/** @deprecated Use `stringifyObjectParams` instead */
readonly shouldStringifyObjectParams?: boolean;
readonly stringifyObjectParams?: boolean;
readonly quoteSqlIdentifiers?: boolean;
};
type IsIterativeExecution<TParams> = TParams extends any[] | GeneratorFn<any> | AsyncGeneratorFn<any> ? true : false;
type ParamsType<T> = T extends AsyncGeneratorFn<infer P> | GeneratorFn<infer P> | Array<infer P> ? P : T;
type SimpleQueryExecutorResult<TQueryResult, TResultSchema extends StandardSchemaV1 | undefined> = TResultSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TResultSchema> : TQueryResult;
type QueryExecutor<DB> = <TQueryResult = unknown, TParams extends QueryExecutorParams = QueryExecutorParams, TParamsSchema extends StandardSchemaV1 | undefined = undefined, TResultSchema extends StandardSchemaV1 | undefined = undefined>(options: {
params?: QueryExecutorOptionsParams<TParams, TParamsSchema>;
paramsSchema?: TParamsSchema;
resultSchema?: TResultSchema;
}) => (sqlOrBuilderFn: SqlOrBuilderFn<TResultSchema, ParamsType<TParams>, DB>) => Promise<QueryExecutorResult<TQueryResult, TParams, TResultSchema>>;
type QueryExecutorParams = Record<string, any> | Record<string, any>[] | GeneratorFn<Record<string, any>> | AsyncGeneratorFn<Record<string, any>>;
type QueryExecutorOptionsParams<TParams, TParamsSchema extends StandardSchemaV1 | undefined> = TParams extends AsyncGeneratorFn<infer P> ? AsyncGeneratorFn<P> : TParams extends GeneratorFn<infer P> ? GeneratorFn<P> : TParams extends Array<infer P> ? P[] : TParamsSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TParamsSchema> : TParams;
type QueryExecutorResult<TQueryResult, TParams, TResultSchema extends StandardSchemaV1 | undefined> = IsIterativeExecution<TParams> extends true ? AsyncGenerator<SimpleQueryExecutorResult<TQueryResult, TResultSchema>, void, unknown> : SimpleQueryExecutorResult<TQueryResult, TResultSchema>;
type IterativeQueryExecutor<DB> = <TQueryResult = unknown, TParams extends Record<string, any> = Record<string, any>, TParamsSchema extends StandardSchemaV1 | undefined = undefined, TResultSchema extends StandardSchemaV1 | undefined = undefined>(options: {
params?: TParamsSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TParamsSchema> : TParams;
paramsSchema?: TParamsSchema;
resultSchema?: TResultSchema;
}) => (sqlOrBuilderFn: SqlOrBuilderFn<TResultSchema, TParams, DB>) => Promise<AsyncGenerator<SimpleQueryExecutorResult<TQueryResult, TResultSchema>, void, unknown>>;
declare class SchemQl<DB> {
private readonly options;
first: QueryExecutor<DB>;
firstOrThrow: QueryExecutor<DB>;
all: QueryExecutor<DB>;
iterate: IterativeQueryExecutor<DB>;
constructor(options: SchemQlOptions);
private createQueryExecutor;
private createIterativeExecutor;
private validateAndStringifyParams;
private createSqlHelper;
private processLiteralExpressions;
private processLiteralExpression;
}
export { SchemQl as a };
export type { SchemQlAdapter as S };
import { StandardSchemaV1 } from '@standard-schema/spec';
interface SchemQlAdapter<T = unknown> {
queryFirst: QueryFn<T | undefined>;
queryFirstOrThrow: QueryFn<T>;
queryAll: QueryFn<T[]>;
queryIterate: IterativeQueryFn<T>;
}
type QueryFn<TQueryResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined> = (sql: string) => (params?: TParams) => TQueryResult | Promise<TQueryResult>;
type IterativeQueryFn<TQueryResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined> = (sql: string) => (params?: TParams) => GeneratorFn<TQueryResult> | AsyncGeneratorFn<TQueryResult>;
type ArrayElement<T> = T extends (infer U)[] ? U : T;
type GeneratorFn<T> = () => Generator<T, void, unknown>;
type AsyncGeneratorFn<T> = () => AsyncGenerator<T, void, unknown>;
type TableNames<DB> = Extract<keyof DB, string>;
type ColumnNames<DB, T extends TableNames<DB>> = Extract<keyof DB[T], string>;
type TableColumnSelection<DB> = {
[T in TableNames<DB>]?: ColumnNames<DB, T>[];
};
type ValidTableColumnCombinations<DB> = {
[T in TableNames<DB>]: `${T}.${ColumnNames<DB, T>}` | `${T}.${ColumnNames<DB, T>}-`;
}[TableNames<DB>];
type JsonPathForObjectArrow<T, P extends string = ''> = T extends Record<string, any> ? {
[K in keyof T & string]: `${P}->${K}` | `${P}->${K}-` | `${P}->>${K}` | `${P}->>${K}-` | (NonNullable<T[K]> extends Record<string, any> ? `${P}->${K}${JsonPathForObjectArrow<NonNullable<T[K]>, ''>}` : never);
}[keyof T & string] : '';
type JsonPathForObjectDot<T, P extends string = ''> = T extends Record<string, any> ? {
[K in keyof T & string]: `${P}.${K}` | (NonNullable<T[K]> extends Record<string, any> ? `${P}.${K}${JsonPathForObjectDot<NonNullable<T[K]>, ''>}` : never);
}[keyof T & string] : '';
type JsonPathCombinations<DB, T extends TableNames<DB>> = {
[K in ColumnNames<DB, T>]: DB[T][K] extends object ? JsonPathForObjectArrow<ArrayElement<DB[T][K]>, `${T}.${K} `> | JsonPathForObjectDot<ArrayElement<DB[T][K]>, `${T}.${K} $`> : never;
}[ColumnNames<DB, T>];
type ValidJsonPathCombinations<DB> = {
[T in TableNames<DB>]: JsonPathCombinations<DB, T>;
}[TableNames<DB>];
type SqlTemplateValue<TResultSchema, TParams, DB> = TableColumnSelection<DB> | `@${TableNames<DB>}` | `@${TableNames<DB>}.*` | `@${ValidTableColumnCombinations<DB>}` | `@${ValidJsonPathCombinations<DB>}` | `$${keyof ArrayElement<Exclude<TResultSchema, undefined>> & string}` | `:${keyof TParams & string}` | `§${string}`;
type SqlTemplateValues<TResultSchema, TParams, DB> = SqlTemplateValue<TResultSchema, TParams, DB>[];
type SqlOrBuilderFn<TResultSchema extends StandardSchemaV1 | undefined, TParams extends Record<string, any>, DB> = string | ((s: SchemQlSqlHelper<TResultSchema, TParams, DB>) => string);
type SchemQlSqlHelper<TResultSchema extends StandardSchemaV1 | undefined, TParams extends Record<string, any>, DB> = {
sql: <T extends SqlTemplateValues<TResultSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TResultSchema> : unknown, TParams, DB>>(strings: TemplateStringsArray, ...values: T) => string;
sqlCond: (condition: boolean, ifTrue: string | number, ifFalse?: string | number) => `§${string}`;
sqlRaw: (raw: string | number) => `§${string}`;
};
type SchemQlOptions = {
readonly adapter: SchemQlAdapter;
/** @deprecated Use `stringifyObjectParams` instead */
readonly shouldStringifyObjectParams?: boolean;
readonly stringifyObjectParams?: boolean;
readonly quoteSqlIdentifiers?: boolean;
};
type IsIterativeExecution<TParams> = TParams extends any[] | GeneratorFn<any> | AsyncGeneratorFn<any> ? true : false;
type ParamsType<T> = T extends AsyncGeneratorFn<infer P> | GeneratorFn<infer P> | Array<infer P> ? P : T;
type SimpleQueryExecutorResult<TQueryResult, TResultSchema extends StandardSchemaV1 | undefined> = TResultSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TResultSchema> : TQueryResult;
type QueryExecutor<DB> = <TQueryResult = unknown, TParams extends QueryExecutorParams = QueryExecutorParams, TParamsSchema extends StandardSchemaV1 | undefined = undefined, TResultSchema extends StandardSchemaV1 | undefined = undefined>(options: {
params?: QueryExecutorOptionsParams<TParams, TParamsSchema>;
paramsSchema?: TParamsSchema;
resultSchema?: TResultSchema;
}) => (sqlOrBuilderFn: SqlOrBuilderFn<TResultSchema, ParamsType<TParams>, DB>) => Promise<QueryExecutorResult<TQueryResult, TParams, TResultSchema>>;
type QueryExecutorParams = Record<string, any> | Record<string, any>[] | GeneratorFn<Record<string, any>> | AsyncGeneratorFn<Record<string, any>>;
type QueryExecutorOptionsParams<TParams, TParamsSchema extends StandardSchemaV1 | undefined> = TParams extends AsyncGeneratorFn<infer P> ? AsyncGeneratorFn<P> : TParams extends GeneratorFn<infer P> ? GeneratorFn<P> : TParams extends Array<infer P> ? P[] : TParamsSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TParamsSchema> : TParams;
type QueryExecutorResult<TQueryResult, TParams, TResultSchema extends StandardSchemaV1 | undefined> = IsIterativeExecution<TParams> extends true ? AsyncGenerator<SimpleQueryExecutorResult<TQueryResult, TResultSchema>, void, unknown> : SimpleQueryExecutorResult<TQueryResult, TResultSchema>;
type IterativeQueryExecutor<DB> = <TQueryResult = unknown, TParams extends Record<string, any> = Record<string, any>, TParamsSchema extends StandardSchemaV1 | undefined = undefined, TResultSchema extends StandardSchemaV1 | undefined = undefined>(options: {
params?: TParamsSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TParamsSchema> : TParams;
paramsSchema?: TParamsSchema;
resultSchema?: TResultSchema;
}) => (sqlOrBuilderFn: SqlOrBuilderFn<TResultSchema, TParams, DB>) => Promise<AsyncGenerator<SimpleQueryExecutorResult<TQueryResult, TResultSchema>, void, unknown>>;
declare class SchemQl<DB> {
private readonly options;
first: QueryExecutor<DB>;
firstOrThrow: QueryExecutor<DB>;
all: QueryExecutor<DB>;
iterate: IterativeQueryExecutor<DB>;
constructor(options: SchemQlOptions);
private createQueryExecutor;
private createIterativeExecutor;
private validateAndStringifyParams;
private createSqlHelper;
private processLiteralExpressions;
private processLiteralExpression;
}
export { SchemQl as a };
export type { SchemQlAdapter as S };
import { StandardSchemaV1 } from '@standard-schema/spec';
interface SchemQlAdapter<T = unknown> {
queryFirst: QueryFn<T | undefined>;
queryFirstOrThrow: QueryFn<T>;
queryAll: QueryFn<T[]>;
queryIterate: IterativeQueryFn<T>;
}
type QueryFn<TQueryResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined> = (sql: string) => (params?: TParams) => TQueryResult | Promise<TQueryResult>;
type IterativeQueryFn<TQueryResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined> = (sql: string) => (params?: TParams) => GeneratorFn<TQueryResult> | AsyncGeneratorFn<TQueryResult>;
type ArrayElement<T> = T extends (infer U)[] ? U : T;
type GeneratorFn<T> = () => Generator<T, void, unknown>;
type AsyncGeneratorFn<T> = () => AsyncGenerator<T, void, unknown>;
type TableNames<DB> = Extract<keyof DB, string>;
type ColumnNames<DB, T extends TableNames<DB>> = Extract<keyof DB[T], string>;
type TableColumnSelection<DB> = {
[T in TableNames<DB>]?: ColumnNames<DB, T>[];
};
type ValidTableColumnCombinations<DB> = {
[T in TableNames<DB>]: `${T}.${ColumnNames<DB, T>}` | `${T}.${ColumnNames<DB, T>}-`;
}[TableNames<DB>];
type JsonPathForObjectArrow<T, P extends string = ''> = T extends Record<string, any> ? {
[K in keyof T & string]: `${P}->${K}` | `${P}->${K}-` | `${P}->>${K}` | `${P}->>${K}-` | (NonNullable<T[K]> extends Record<string, any> ? `${P}->${K}${JsonPathForObjectArrow<NonNullable<T[K]>, ''>}` : never);
}[keyof T & string] : '';
type JsonPathForObjectDot<T, P extends string = ''> = T extends Record<string, any> ? {
[K in keyof T & string]: `${P}.${K}` | (NonNullable<T[K]> extends Record<string, any> ? `${P}.${K}${JsonPathForObjectDot<NonNullable<T[K]>, ''>}` : never);
}[keyof T & string] : '';
type JsonPathCombinations<DB, T extends TableNames<DB>> = {
[K in ColumnNames<DB, T>]: DB[T][K] extends object ? JsonPathForObjectArrow<ArrayElement<DB[T][K]>, `${T}.${K} `> | JsonPathForObjectDot<ArrayElement<DB[T][K]>, `${T}.${K} $`> : never;
}[ColumnNames<DB, T>];
type ValidJsonPathCombinations<DB> = {
[T in TableNames<DB>]: JsonPathCombinations<DB, T>;
}[TableNames<DB>];
type SqlTemplateValue<TResultSchema, TParams, DB> = TableColumnSelection<DB> | `@${TableNames<DB>}` | `@${TableNames<DB>}.*` | `@${ValidTableColumnCombinations<DB>}` | `@${ValidJsonPathCombinations<DB>}` | `$${keyof ArrayElement<Exclude<TResultSchema, undefined>> & string}` | `:${keyof TParams & string}` | `§${string}`;
type SqlTemplateValues<TResultSchema, TParams, DB> = SqlTemplateValue<TResultSchema, TParams, DB>[];
type SqlOrBuilderFn<TResultSchema extends StandardSchemaV1 | undefined, TParams extends Record<string, any>, DB> = string | ((s: SchemQlSqlHelper<TResultSchema, TParams, DB>) => string);
type SchemQlSqlHelper<TResultSchema extends StandardSchemaV1 | undefined, TParams extends Record<string, any>, DB> = {
sql: <T extends SqlTemplateValues<TResultSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TResultSchema> : unknown, TParams, DB>>(strings: TemplateStringsArray, ...values: T) => string;
sqlCond: (condition: boolean, ifTrue: string | number, ifFalse?: string | number) => `§${string}`;
sqlRaw: (raw: string | number) => `§${string}`;
};
type SchemQlOptions = {
readonly adapter: SchemQlAdapter;
/** @deprecated Use `stringifyObjectParams` instead */
readonly shouldStringifyObjectParams?: boolean;
readonly stringifyObjectParams?: boolean;
readonly quoteSqlIdentifiers?: boolean;
};
type IsIterativeExecution<TParams> = TParams extends any[] | GeneratorFn<any> | AsyncGeneratorFn<any> ? true : false;
type ParamsType<T> = T extends AsyncGeneratorFn<infer P> | GeneratorFn<infer P> | Array<infer P> ? P : T;
type SimpleQueryExecutorResult<TQueryResult, TResultSchema extends StandardSchemaV1 | undefined> = TResultSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TResultSchema> : TQueryResult;
type QueryExecutor<DB> = <TQueryResult = unknown, TParams extends QueryExecutorParams = QueryExecutorParams, TParamsSchema extends StandardSchemaV1 | undefined = undefined, TResultSchema extends StandardSchemaV1 | undefined = undefined>(options: {
params?: QueryExecutorOptionsParams<TParams, TParamsSchema>;
paramsSchema?: TParamsSchema;
resultSchema?: TResultSchema;
}) => (sqlOrBuilderFn: SqlOrBuilderFn<TResultSchema, ParamsType<TParams>, DB>) => Promise<QueryExecutorResult<TQueryResult, TParams, TResultSchema>>;
type QueryExecutorParams = Record<string, any> | Record<string, any>[] | GeneratorFn<Record<string, any>> | AsyncGeneratorFn<Record<string, any>>;
type QueryExecutorOptionsParams<TParams, TParamsSchema extends StandardSchemaV1 | undefined> = TParams extends AsyncGeneratorFn<infer P> ? AsyncGeneratorFn<P> : TParams extends GeneratorFn<infer P> ? GeneratorFn<P> : TParams extends Array<infer P> ? P[] : TParamsSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TParamsSchema> : TParams;
type QueryExecutorResult<TQueryResult, TParams, TResultSchema extends StandardSchemaV1 | undefined> = IsIterativeExecution<TParams> extends true ? AsyncGenerator<SimpleQueryExecutorResult<TQueryResult, TResultSchema>, void, unknown> : SimpleQueryExecutorResult<TQueryResult, TResultSchema>;
type IterativeQueryExecutor<DB> = <TQueryResult = unknown, TParams extends Record<string, any> = Record<string, any>, TParamsSchema extends StandardSchemaV1 | undefined = undefined, TResultSchema extends StandardSchemaV1 | undefined = undefined>(options: {
params?: TParamsSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TParamsSchema> : TParams;
paramsSchema?: TParamsSchema;
resultSchema?: TResultSchema;
}) => (sqlOrBuilderFn: SqlOrBuilderFn<TResultSchema, TParams, DB>) => Promise<AsyncGenerator<SimpleQueryExecutorResult<TQueryResult, TResultSchema>, void, unknown>>;
declare class SchemQl<DB> {
private readonly options;
first: QueryExecutor<DB>;
firstOrThrow: QueryExecutor<DB>;
all: QueryExecutor<DB>;
iterate: IterativeQueryExecutor<DB>;
constructor(options: SchemQlOptions);
private createQueryExecutor;
private createIterativeExecutor;
private validateAndStringifyParams;
private createSqlHelper;
private processLiteralExpressions;
private processLiteralExpression;
}
export { SchemQl as a };
export type { SchemQlAdapter as S };

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

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