🎩 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.1
to
0.5.2
+1
dist/adapters/nodeSqliteAdapter.cjs
"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;
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';
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;
}
declare class SchemQlAdapterError extends BaseAdapterError {
static createFromNodeSqlite: (error: any) => SchemQlAdapterError;
}
export { NodeSqliteAdapter, SchemQlAdapterError };
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';
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;
}
declare class SchemQlAdapterError extends BaseAdapterError {
static createFromNodeSqlite: (error: any) => SchemQlAdapterError;
}
export { NodeSqliteAdapter, SchemQlAdapterError };
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 { 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 };
+1
-1

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

"use strict";var S=Object.defineProperty;var t=(s,N)=>S(s,"name",{value:N,configurable:!0});var R=(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))(R||{});const i=class i extends Error{constructor(N,I,T){super(N),this.code=I,this.originalError=T,this.isNoResultError=()=>this.code==="NO_RESULT",this.name="AdapterError"}};t(i,"BaseAdapterError");let n=i;exports.AdapterErrorCode=R,exports.BaseAdapterError=n;
"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;

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

var S=Object.defineProperty;var R=(N,n)=>S(N,"name",{value:n,configurable:!0});var t=(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))(t||{});const s=class s extends Error{constructor(n,I,T){super(n),this.code=I,this.originalError=T,this.isNoResultError=()=>this.code==="NO_RESULT",this.name="AdapterError"}};R(s,"BaseAdapterError");let i=s;export{t as AdapterErrorCode,i as BaseAdapterError};
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};

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

"use strict";var l=Object.defineProperty;var c=(i,d)=>l(i,"name",{value:d,configurable:!0});var a,n=require("./baseAdapterError.cjs");const E=class E{constructor(d){this.db=d,this.queryAll=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(o){if(o instanceof TypeError&&o.message==="This statement does not return data. Use run() instead")return this.handleTypeErrorRun(e,r),[];throw s.createFromBetterSqlite3(o)}}},this.queryFirst=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(o){if(o instanceof TypeError&&o.message==="This statement does not return data. Use run() instead"){this.handleTypeErrorRun(e,r);return}throw s.createFromBetterSqlite3(o)}}},this.queryFirstOrThrow=t=>{const e=this.queryFirst(t);return r=>{const o=e(r);if(o===void 0)throw new s("No result",n.AdapterErrorCode.NoResult);return o}},this.queryIterate=t=>{const e=this.db.prepare(t);return r=>r?e.iterate(r):e.iterate()},this.handleTypeErrorRun=(t,e)=>{try{e?t.run(e):t.run()}catch(r){throw s.createFromBetterSqlite3(r)}}}};c(E,"BetterSqlite3Adapter");let h=E;const u=(a=class extends n.BaseAdapterError{},c(a,"_SchemQlAdapterError"),a);u.createFromBetterSqlite3=i=>{const d=new Map([["SQLITE_CONSTRAINT_UNIQUE",n.AdapterErrorCode.UniqueConstraint],["SQLITE_CONSTRAINT_FOREIGNKEY",n.AdapterErrorCode.ForeignkeyConstraint],["SQLITE_CONSTRAINT_NOTNULL",n.AdapterErrorCode.NotnullConstraint],["SQLITE_CONSTRAINT_CHECK",n.AdapterErrorCode.CheckConstraint],["SQLITE_CONSTRAINT_PRIMARYKEY",n.AdapterErrorCode.PrimarykeyConstraint]]);return new u(i.message,d.get(i.code)??n.AdapterErrorCode.Generic,i)};let s=u;exports.SchemQlAdapterErrorCode=n.AdapterErrorCode,exports.BetterSqlite3Adapter=h,exports.SchemQlAdapterError=s;
"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;

@@ -1,10 +0,12 @@

import SQLite from 'better-sqlite3';
import { BaseAdapterError } from './baseAdapterError.cjs';
export { AdapterErrorCode as SchemQlAdapterErrorCode } from './baseAdapterError.cjs';
import { S as SchemQlAdapter } from '../schemql-DJKXWmTu.js';
import { S as SchemQlAdapter } from '../schemql-DY-sGX-S.cjs';
import '@standard-schema/spec';
module.exports = require('./database');
module.exports.SqliteError = require('./sqlite-error');
declare class BetterSqlite3Adapter<T = unknown> implements SchemQlAdapter<T> {
private db;
constructor(db: SQLite.Database);
constructor(db: undefined);
queryAll: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult[];

@@ -17,5 +19,5 @@ queryFirst: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult | undefined;

declare class SchemQlAdapterError extends BaseAdapterError {
static createFromBetterSqlite3: (error: SQLite.SqliteError | TypeError) => SchemQlAdapterError;
static createFromBetterSqlite3: (error: undefined | TypeError) => SchemQlAdapterError;
}
export { BetterSqlite3Adapter, SchemQlAdapterError };

@@ -1,10 +0,12 @@

import SQLite from 'better-sqlite3';
import { BaseAdapterError } from './baseAdapterError.mjs';
export { AdapterErrorCode as SchemQlAdapterErrorCode } from './baseAdapterError.mjs';
import { S as SchemQlAdapter } from '../schemql-DJKXWmTu.js';
import { S as SchemQlAdapter } from '../schemql-DY-sGX-S.mjs';
import '@standard-schema/spec';
module.exports = require('./database');
module.exports.SqliteError = require('./sqlite-error');
declare class BetterSqlite3Adapter<T = unknown> implements SchemQlAdapter<T> {
private db;
constructor(db: SQLite.Database);
constructor(db: undefined);
queryAll: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult[];

@@ -17,5 +19,5 @@ queryFirst: <TResult, TParams extends Record<string, any> | undefined = Record<string, any> | undefined>(sql: string) => (params?: TParams) => TResult | undefined;

declare class SchemQlAdapterError extends BaseAdapterError {
static createFromBetterSqlite3: (error: SQLite.SqliteError | TypeError) => SchemQlAdapterError;
static createFromBetterSqlite3: (error: undefined | TypeError) => SchemQlAdapterError;
}
export { BetterSqlite3Adapter, SchemQlAdapterError };

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

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

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

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

@@ -1,7 +0,96 @@

import { D1Database } from '@cloudflare/workers-types';
import { BaseAdapterError } from './baseAdapterError.cjs';
export { AdapterErrorCode as SchemQlAdapterErrorCode } from './baseAdapterError.cjs';
import { S as SchemQlAdapter } from '../schemql-DJKXWmTu.js';
import { S as SchemQlAdapter } from '../schemql-DY-sGX-S.cjs';
import '@standard-schema/spec';
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[]>;
}
declare class D1Adapter<T = unknown> implements SchemQlAdapter<T> {

@@ -8,0 +97,0 @@ private db;

@@ -1,7 +0,96 @@

import { D1Database } from '@cloudflare/workers-types';
import { BaseAdapterError } from './baseAdapterError.mjs';
export { AdapterErrorCode as SchemQlAdapterErrorCode } from './baseAdapterError.mjs';
import { S as SchemQlAdapter } from '../schemql-DJKXWmTu.js';
import { S as SchemQlAdapter } from '../schemql-DY-sGX-S.mjs';
import '@standard-schema/spec';
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[]>;
}
declare class D1Adapter<T = unknown> implements SchemQlAdapter<T> {

@@ -8,0 +97,0 @@ private db;

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

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

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

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

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

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

@@ -79,2 +79,12 @@ "license": "MIT",

}
},
"./adapters/node-sqlite": {
"import": {
"types": "./dist/adapters/nodeSqliteAdapter.d.mts",
"default": "./dist/adapters/nodeSqliteAdapter.mjs"
},
"require": {
"types": "./dist/adapters/nodeSqliteAdapter.d.cts",
"default": "./dist/adapters/nodeSqliteAdapter.cjs"
}
}

@@ -86,20 +96,16 @@ },

"dependencies": {
"@standard-schema/spec": "^1.0.0"
"@standard-schema/spec": "^1.1.0"
},
"devDependencies": {
"@biomejs/biome": "^2.0.5",
"@cloudflare/workers-types": "^4.20250620.0",
"@types/node": "^24.0.3",
"arktype": "^2.1.20",
"better-sqlite3": "^12.1.0",
"pkgroll": "^2.13.1",
"@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.20.3",
"typescript": "^5.8.3",
"zod": "^3.25.67"
"tsx": "^4.21.0",
"typescript": "^5.9.3",
"zod": "^4.2.1"
},
"peerDependencies": {
"@cloudflare/workers-types": "*",
"better-sqlite3": "*"
},
"scripts": {

@@ -106,0 +112,0 @@ "biome": "biome check --write ./src ./tests",

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"
}
declare class BaseAdapterError extends Error {
code: AdapterErrorCode;
originalError?: Error | undefined;
constructor(message: string, code: AdapterErrorCode, originalError?: Error | undefined);
isNoResultError: () => boolean;
}
export { AdapterErrorCode, BaseAdapterError };
import SQLite from 'better-sqlite3';
import { BaseAdapterError } from './baseAdapterError.js';
export { AdapterErrorCode as SchemQlAdapterErrorCode } from './baseAdapterError.js';
import { S as SchemQlAdapter } from '../schemql-DJKXWmTu.js';
import '@standard-schema/spec';
declare class BetterSqlite3Adapter<T = unknown> implements SchemQlAdapter<T> {
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: SQLite.SqliteError | TypeError) => SchemQlAdapterError;
}
export { BetterSqlite3Adapter, SchemQlAdapterError };
import { D1Database } from '@cloudflare/workers-types';
import { BaseAdapterError } from './baseAdapterError.js';
export { AdapterErrorCode as SchemQlAdapterErrorCode } from './baseAdapterError.js';
import { S as SchemQlAdapter } from '../schemql-DJKXWmTu.js';
import '@standard-schema/spec';
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;
}
declare class SchemQlAdapterError extends BaseAdapterError {
static createFromD1: (error: Error) => SchemQlAdapterError;
}
export { D1Adapter, SchemQlAdapterError };
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 = {
adapter: SchemQlAdapter;
/** @deprecated Use `stringifyObjectParams` instead */
shouldStringifyObjectParams?: boolean;
stringifyObjectParams?: boolean;
quoteSqlIdentifiers?: boolean;
};
type IsIterativeExecution<TParams> = TParams extends any[] ? true : TParams extends AsyncGeneratorFn<any> ? true : TParams extends GeneratorFn<any> ? true : false;
type ParamsType<T> = T extends AsyncGeneratorFn<infer P> ? P : T extends GeneratorFn<infer P> ? P : T extends 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 { type SchemQlAdapter as S, SchemQl as a };

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

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

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