Skip to content

Commit

Permalink
Build deno [autogenerated commit]
Browse files Browse the repository at this point in the history
  • Loading branch information
oguimbal committed Jul 31, 2024
1 parent 6d8e9a3 commit 61e2d5f
Show file tree
Hide file tree
Showing 11 changed files with 156 additions and 19 deletions.
96 changes: 84 additions & 12 deletions .deno/adapters/adapters.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { LibAdapters, IMemoryDb, NotSupported, QueryResult } from '../interfaces.ts';
import { LibAdapters, IMemoryDb, NotSupported, QueryResult, SlonikAdapterOptions } from '../interfaces.ts';
import lru from 'https://deno.land/x/[email protected]/mod.ts';
import { compareVersions } from '../utils.ts';
import { toLiteral } from '../misc/pg-utils.ts';
Expand All @@ -24,7 +24,7 @@ function timeoutOrImmediate(fn: () => void, time: number) {

const delay = (time: number | undefined) => new Promise<void>(done => timeoutOrImmediate(done, time ?? 0));

function replaceQueryArgs$(this: void, sql: string, values: any[]) {
export function replaceQueryArgs$(this: void, sql: string, values: any[]) {
return sql.replace(/\$(\d+)/g, (str: any, istr: any) => {
const i = Number.parseInt(istr);
if (i > values.length) {
Expand Down Expand Up @@ -210,16 +210,82 @@ export class Adapters implements LibAdapters {
return created;
}

createSlonik(queryLatency?: number) {
const { createMockPool, createMockQueryResult } = __non_webpack_require__('slonik');
return createMockPool({
query: async (sql: string, args: any[]) => {
await delay(queryLatency ?? 0);
const formatted = replaceQueryArgs$(sql, args);
const ret = this.db.public.many(formatted);
return createMockQueryResult(ret);
},
});
createSlonik(opts?: SlonikAdapterOptions) {
const slonik = __non_webpack_require__('slonik');
if (typeof slonik.createMockPool !== 'function') {
// see https://github.com/gajus/slonik/blob/main/packages/slonik/src/factories/createPool.ts
// and @slonik/pg-driver https://github.com/gajus/slonik/blob/main/packages/pg-driver/src/factories/createPgDriverFactory.ts
const { createDriverFactory } = __non_webpack_require__('@slonik/driver');
const createResultParserInterceptor = () => {
return {
transformRow: async (executionContext: any, actualQuery: any, row: any) => {
const { resultParser } = executionContext;
if (!resultParser) {
return row;
}
// It is recommended (but not required) to parse async to avoid blocking the event loop during validation
const validationResult = await resultParser.safeParseAsync(row);

if (!validationResult.success) {
throw new slonik.SchemaValidationError(
actualQuery,
row,
validationResult.error.issues
);
}

return validationResult.data;
},
};
};
return slonik.createPool('', {
...opts?.createPoolOptions ?? {},
...opts?.zodValidation ? { interceptors: [createResultParserInterceptor(), ...opts?.createPoolOptions?.interceptors ?? []] } : {},
// driverFactory: factory,
driverFactory: createDriverFactory(() => {
let connected = false;
return {
createPoolClient: async () => {
return {
connect: async () => {
await delay(opts?.queryLatency ?? 0);
connected = true;
},
end: async () => {
await delay(opts?.queryLatency ?? 0);
connected = false;
},
query: async (sql: string, args: any[]) => {
if (!connected) {
throw new Error('your fake pg pool is not connected');
}
if (sql === 'DISCARD ALL') {
return { rows: [] };
}
await delay(opts?.queryLatency ?? 0);
const formatted = replaceQueryArgs$(sql, args);
const result = this.db.public.query(formatted);
return result;
},
stream: (sql: any, values: any) => {
throw new Error('pg-mem does not support streaming');
},
}
},
}
})
})
} else {
// old slonik versions
return slonik.createMockPool({
query: async (sql: string, args: any[]) => {
await delay(opts?.queryLatency ?? 0);
const formatted = replaceQueryArgs$(sql, args);
const ret = this.db.public.many(formatted);
return slonik.createMockQueryResult(ret);
},
}, opts?.clientConfigurationInput);
}
}


Expand Down Expand Up @@ -347,6 +413,12 @@ export class Adapters implements LibAdapters {
return that.createKnex();
}

async execute(query: string, params: any[] = [], method: 'all' | 'get' | 'run' = 'all'): Promise<any> {
// pg-mem does not support `set names 'utf8';` yet
// the hack in line 355 works only for a single query while this one works beforehand to strip it from multiline queries
return super.execute(query.replace('set names \'utf8\';', ''), params, method);
}

}
// see https://github.com/mikro-orm/mikro-orm/blob/master/packages/postgresql/src/PostgreSqlDriver.ts
class PgMemDriver extends AbstractSqlDriver<PgMemConnection> {
Expand Down
2 changes: 2 additions & 0 deletions .deno/functions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import { stringFunctions } from './string.ts';
import { dateFunctions } from './date.ts';
import { systemFunctions } from './system.ts';
import { sequenceFunctions } from './sequence-fns.ts';
import { numberFunctions } from './numbers.ts';


export const allFunctions = [
...stringFunctions
, ... dateFunctions
, ... systemFunctions
, ... sequenceFunctions
, ... numberFunctions
]
18 changes: 18 additions & 0 deletions .deno/functions/numbers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { DataType, FunctionDefinition } from '../interfaces.ts';

export const numberFunctions: FunctionDefinition[] = [
{
name: 'greatest',
args: [DataType.integer],
argsVariadic: DataType.integer,
returns: DataType.integer,
implementation: (...args: number[]) => Math.max(...args),
},
{
name: 'least',
args: [DataType.integer],
argsVariadic: DataType.integer,
returns: DataType.integer,
implementation: (...args: number[]) => Math.min(...args),
},
]
14 changes: 14 additions & 0 deletions .deno/functions/sequence-fns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,18 @@ export const sequenceFunctions: FunctionDefinition[] = [
},
impure: true,
},
{
name: 'setval',
args: [Types.regclass, Types.integer, Types.bool],
returns: Types.integer,
implementation: (seqId: RegClass, val: number, increase: boolean) => {
const { seq, t } = getSeq(seqId);
if (typeof val !== 'number') {
throw new QueryError('Invalid setval() value');
}
seq.setValue(t, val, increase);
return val;
},
impure: true,
},
]
10 changes: 9 additions & 1 deletion .deno/functions/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,12 @@ export const stringFunctions: FunctionDefinition[] = [
allowNullArguments: true,
implementation: (...x: string[]) => x?.join(''),
},
]
{
name: 'concat_ws',
args: [DataType.text],
argsVariadic: DataType.text,
returns: DataType.text,
allowNullArguments: true,
implementation: (separator: string, ...x: string[]) => x?.join(separator),
},
]
1 change: 1 addition & 0 deletions .deno/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { newDb } from './db.ts';
export { enableStatementLocationTracking } from './parser/parse-cache.ts';
export { replaceQueryArgs$ } from './adapters/index.ts';
export * from './interfaces.ts';
2 changes: 1 addition & 1 deletion .deno/interfaces-private.ts
Original file line number Diff line number Diff line change
Expand Up @@ -772,7 +772,7 @@ export interface _ISequence extends _RelationBase {
alter(t: _Transaction, opts: CreateSequenceOptions | AlterSequenceChange): this;
nextValue(t: _Transaction): number;
restart(t: _Transaction): void;
setValue(t: _Transaction, value: number): void;
setValue(t: _Transaction, value: number, increase?: boolean): void;
currentValue(t: _Transaction): number;
drop(t: _Transaction): void;
}
Expand Down
12 changes: 11 additions & 1 deletion .deno/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ export interface LibAdapters {
createPgPromise(queryLatency?: number): any;

/** Create a slonik pool bound to this db */
createSlonik(queryLatency?: number): any;
createSlonik(opts?: SlonikAdapterOptions): Promise<any>;

/** Create a pg-native instance bound to this db */
createPgNative(queryLatency?: number): any;
Expand All @@ -226,6 +226,16 @@ export interface LibAdapters {
createMikroOrm(mikroOrmOptions: any, queryLatency?: number): Promise<any>
}

export interface SlonikAdapterOptions {
queryLatency?: number;
/** options you would give to the createPool() function */
createPoolOptions?: any;
/** add zod validation interceptor to create pool options, like with https://github.com/gajus/slonik?tab=readme-ov-file#result-parser-interceptor */
zodValidation?: boolean;
/** old versions of slonik, this be passed as client configuration */
clientConfigurationInput?: any;
}

export type QueryOrAst = string | Statement | Statement[];

export interface ISchema {
Expand Down
10 changes: 10 additions & 0 deletions .deno/schema/pg-catalog/binary-operators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,16 @@ function registerNumericOperators(schema: _ISchema) {


function registerDatetimeOperators(schema: _ISchema) {
// ======= date "-" date =======
schema.registerOperator({
operator: '-',
commutative: false,
left: Types.date,
right: Types.date,
returns: Types.interval,
implementation: (a, b) => moment(a).diff(moment(b), 'days'),
})

// ======= date/time "+ -" timestamp =======
for (const dt of dateTypes) {
for (const [operator, f] of [['+', 1], ['-', -1]] as const) {
Expand Down
4 changes: 2 additions & 2 deletions .deno/schema/sequence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ export class Sequence implements _ISequence {
return v;
}

setValue(t: _Transaction, value: number) {
setValue(t: _Transaction, value: number, increase: boolean = true) {
if (value > this.max) {
throw new QueryError(`reached maximum value of sequence "${this.name}"`);
}
Expand All @@ -134,7 +134,7 @@ export class Sequence implements _ISequence {
}
const data: SeqData = {
currval: value,
nextval: value + this.inc,
nextval: increase ? value + this.inc : value,
};
t.set(this.symbol, data);
}
Expand Down
6 changes: 4 additions & 2 deletions .deno/transforms/alias.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,10 @@ export class Alias<T> extends TransformBase<T> implements _IAlias {
private _getColumn(column: string | ExprRef): IValue | nil {
if (typeof column !== 'string'
&& column.table) {
if (!column.table.schema
&& column.table.name !== this.name) {
if (column.table.schema && column.table.schema !== this.ownerSchema.name) {
return null;
}
if (column.table.name !== this.name) {
return null;
}
column = column.name;
Expand Down

0 comments on commit 61e2d5f

Please sign in to comment.