Skip to content

Commit

Permalink
Implemented rqb-v2 changes to new drivers, updated tests, fixed neon-…
Browse files Browse the repository at this point in the history
…http `$withAuth` rqbv2 tests
  • Loading branch information
Sukairo-02 committed Dec 27, 2024
1 parent 23e557c commit bad7b01
Show file tree
Hide file tree
Showing 14 changed files with 211 additions and 122 deletions.
38 changes: 22 additions & 16 deletions drizzle-orm/src/durable-sqlite/driver.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,36 @@
/// <reference types="@cloudflare/workers-types" />
import * as V1 from '~/_relations.ts';
import { entityKind } from '~/entity.ts';
import { DefaultLogger } from '~/logger.ts';
import {
createTableRelationsHelpers,
extractTablesRelationalConfig,
type ExtractTablesWithRelations,
type RelationalSchemaConfig,
type TablesRelationalConfig,
} from '~/relations.ts';
import type { AnyRelations, EmptyRelations, ExtractTablesWithRelations } from '~/relations.ts';
import { BaseSQLiteDatabase } from '~/sqlite-core/db.ts';
import { SQLiteSyncDialect } from '~/sqlite-core/dialect.ts';
import type { DrizzleConfig } from '~/utils.ts';
import { SQLiteDOSession } from './session.ts';

export class DrizzleSqliteDODatabase<
TSchema extends Record<string, unknown> = Record<string, never>,
> extends BaseSQLiteDatabase<'sync', SqlStorageCursor<Record<string, SqlStorageValue>>, TSchema> {
TRelations extends AnyRelations = EmptyRelations,
> extends BaseSQLiteDatabase<'sync', SqlStorageCursor<Record<string, SqlStorageValue>>, TSchema, TRelations> {
static override readonly [entityKind]: string = 'DrizzleSqliteDODatabase';

/** @internal */
declare readonly session: SQLiteDOSession<TSchema, ExtractTablesWithRelations<TSchema>>;
declare readonly session: SQLiteDOSession<
TSchema,
TRelations,
ExtractTablesWithRelations<TRelations>,
V1.ExtractTablesWithRelations<TSchema>
>;
}

export function drizzle<
TSchema extends Record<string, unknown> = Record<string, never>,
TRelations extends AnyRelations = EmptyRelations,
TClient extends DurableObjectStorage = DurableObjectStorage,
>(
client: TClient,
config: DrizzleConfig<TSchema> = {},
): DrizzleSqliteDODatabase<TSchema> & {
config: DrizzleConfig<TSchema, TRelations> = {},
): DrizzleSqliteDODatabase<TSchema, TRelations> & {
$client: TClient;
} {
const dialect = new SQLiteSyncDialect({ casing: config.casing });
Expand All @@ -39,11 +41,11 @@ export function drizzle<
logger = config.logger;
}

let schema: RelationalSchemaConfig<TablesRelationalConfig> | undefined;
let schema: V1.RelationalSchemaConfig<V1.TablesRelationalConfig> | undefined;
if (config.schema) {
const tablesConfig = extractTablesRelationalConfig(
const tablesConfig = V1.extractTablesRelationalConfig(
config.schema,
createTableRelationsHelpers,
V1.createTableRelationsHelpers,
);
schema = {
fullSchema: config.schema,
Expand All @@ -52,8 +54,12 @@ export function drizzle<
};
}

const session = new SQLiteDOSession(client as DurableObjectStorage, dialect, schema, { logger });
const db = new DrizzleSqliteDODatabase('sync', dialect, session, schema) as DrizzleSqliteDODatabase<TSchema>;
const relations = config.relations;
const session = new SQLiteDOSession(client as DurableObjectStorage, dialect, relations, schema, { logger });
const db = new DrizzleSqliteDODatabase('sync', dialect, session, relations, schema) as DrizzleSqliteDODatabase<
TSchema,
TRelations
>;
(<any> db).$client = client;

return db as any;
Expand Down
4 changes: 3 additions & 1 deletion drizzle-orm/src/durable-sqlite/migrator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { MigrationMeta } from '~/migrator.ts';
import type { AnyRelations } from '~/relations.ts';
import { sql } from '~/sql/index.ts';
import type { DrizzleSqliteDODatabase } from './driver.ts';

Expand Down Expand Up @@ -40,8 +41,9 @@ function readMigrationFiles({ journal, migrations }: MigrationConfig): Migration

export async function migrate<
TSchema extends Record<string, unknown>,
TRelations extends AnyRelations,
>(
db: DrizzleSqliteDODatabase<TSchema>,
db: DrizzleSqliteDODatabase<TSchema, TRelations>,
config: MigrationConfig,
): Promise<void> {
const migrations = readMigrationFiles(config);
Expand Down
136 changes: 110 additions & 26 deletions drizzle-orm/src/durable-sqlite/session.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type * as V1 from '~/_relations.ts';
import { entityKind } from '~/entity.ts';
import type { Logger } from '~/logger.ts';
import { NoopLogger } from '~/logger.ts';
import type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts';
import type { AnyRelations, TablesRelationalConfig } from '~/relations.ts';
import { fillPlaceholders, type Query } from '~/sql/sql.ts';
import { type SQLiteSyncDialect, SQLiteTransaction } from '~/sqlite-core/index.ts';
import type { SelectedFieldsOrdered } from '~/sqlite-core/query-builders/select.types.ts';
Expand All @@ -20,22 +21,28 @@ export interface SQLiteDOSessionOptions {

type PreparedQueryConfig = Omit<PreparedQueryConfigBase, 'statement' | 'run'>;

export class SQLiteDOSession<TFullSchema extends Record<string, unknown>, TSchema extends TablesRelationalConfig>
extends SQLiteSession<
'sync',
SqlStorageCursor<Record<string, SqlStorageValue>>,
TFullSchema,
TSchema
>
{
export class SQLiteDOSession<
TFullSchema extends Record<string, unknown>,
TRelations extends AnyRelations,
TTablesConfig extends TablesRelationalConfig,
TSchema extends V1.TablesRelationalConfig,
> extends SQLiteSession<
'sync',
SqlStorageCursor<Record<string, SqlStorageValue>>,
TFullSchema,
TRelations,
TTablesConfig,
TSchema
> {
static override readonly [entityKind]: string = 'SQLiteDOSession';

private logger: Logger;

constructor(
private client: DurableObjectStorage,
dialect: SQLiteSyncDialect,
private schema: RelationalSchemaConfig<TSchema> | undefined,
private relations: AnyRelations | undefined,
private schema: V1.RelationalSchemaConfig<TSchema> | undefined,
options: SQLiteDOSessionOptions = {},
) {
super(dialect);
Expand All @@ -60,39 +67,81 @@ export class SQLiteDOSession<TFullSchema extends Record<string, unknown>, TSchem
);
}

prepareRelationalQuery<T extends Omit<PreparedQueryConfig, 'run'>>(
query: Query,
fields: SelectedFieldsOrdered | undefined,
executeMethod: SQLiteExecuteMethod,
customResultMapper: (rows: Record<string, unknown>[]) => unknown,
): SQLiteDOPreparedQuery<T, true> {
return new SQLiteDOPreparedQuery(
this.client,
query,
this.logger,
fields,
executeMethod,
false,
customResultMapper,
true,
);
}

override transaction<T>(
transaction: (
tx: SQLiteTransaction<'sync', SqlStorageCursor<Record<string, SqlStorageValue>>, TFullSchema, TSchema>,
tx: SQLiteTransaction<
'sync',
SqlStorageCursor<Record<string, SqlStorageValue>>,
TFullSchema,
TRelations,
TTablesConfig,
TSchema
>,
) => T,
_config?: SQLiteTransactionConfig,
): T {
const tx = new SQLiteDOTransaction('sync', this.dialect, this, this.schema);
const tx = new SQLiteDOTransaction('sync', this.dialect, this, this.relations, this.schema);
this.client.transactionSync(() => {
transaction(tx);
});
return {} as any;
}
}

export class SQLiteDOTransaction<TFullSchema extends Record<string, unknown>, TSchema extends TablesRelationalConfig>
extends SQLiteTransaction<
'sync',
SqlStorageCursor<Record<string, SqlStorageValue>>,
TFullSchema,
TSchema
>
{
export class SQLiteDOTransaction<
TFullSchema extends Record<string, unknown>,
TRelations extends AnyRelations,
TTablesConfig extends TablesRelationalConfig,
TSchema extends V1.TablesRelationalConfig,
> extends SQLiteTransaction<
'sync',
SqlStorageCursor<Record<string, SqlStorageValue>>,
TFullSchema,
TRelations,
TTablesConfig,
TSchema
> {
static override readonly [entityKind]: string = 'SQLiteDOTransaction';

override transaction<T>(transaction: (tx: SQLiteDOTransaction<TFullSchema, TSchema>) => T): T {
const tx = new SQLiteDOTransaction('sync', this.dialect, this.session, this.schema, this.nestedIndex + 1);
override transaction<T>(
transaction: (tx: SQLiteDOTransaction<TFullSchema, TRelations, TTablesConfig, TSchema>) => T,
): T {
const tx = new SQLiteDOTransaction(
'sync',
this.dialect,
this.session,
this.relations,
this.schema,
this.nestedIndex + 1,
);
this.session.transaction(() => transaction(tx));

return {} as any;
}
}

export class SQLiteDOPreparedQuery<T extends PreparedQueryConfig = PreparedQueryConfig> extends PreparedQueryBase<{
export class SQLiteDOPreparedQuery<
T extends PreparedQueryConfig = PreparedQueryConfig,
TIsRqbV2 extends boolean = false,
> extends PreparedQueryBase<{
type: 'sync';
run: void;
all: T['all'];
Expand All @@ -109,7 +158,10 @@ export class SQLiteDOPreparedQuery<T extends PreparedQueryConfig = PreparedQuery
private fields: SelectedFieldsOrdered | undefined,
executeMethod: SQLiteExecuteMethod,
private _isResponseInArrayMode: boolean,
private customResultMapper?: (rows: unknown[][]) => unknown,
private customResultMapper?: (
rows: TIsRqbV2 extends true ? Record<string, unknown>[] : unknown[][],
) => unknown,
private isRqbV2Query?: TIsRqbV2,
) {
super('sync', executeMethod, query);
}
Expand All @@ -122,6 +174,8 @@ export class SQLiteDOPreparedQuery<T extends PreparedQueryConfig = PreparedQuery
}

all(placeholderValues?: Record<string, unknown>): T['all'] {
if (this.isRqbV2Query) return this.allRqbV2(placeholderValues);

const { fields, joinsNotNullableMap, query, logger, client, customResultMapper } = this;
if (!fields && !customResultMapper) {
const params = fillPlaceholders(query.params, placeholderValues ?? {});
Expand All @@ -133,13 +187,28 @@ export class SQLiteDOPreparedQuery<T extends PreparedQueryConfig = PreparedQuery
const rows = this.values(placeholderValues) as unknown[][];

if (customResultMapper) {
return customResultMapper(rows) as T['all'];
return (customResultMapper as (rows: unknown[][]) => unknown)(rows) as T['all'];
}

return rows.map((row) => mapResultRow(fields!, row, joinsNotNullableMap));
}

private allRqbV2(placeholderValues?: Record<string, unknown>): T['all'] {
const { query, logger, client, customResultMapper } = this;

const params = fillPlaceholders(query.params, placeholderValues ?? {});
logger.logQuery(query.sql, params);

const rows = params.length > 0
? client.sql.exec(query.sql, ...params).toArray()
: client.sql.exec(query.sql).toArray();

return (customResultMapper as (rows: Record<string, unknown>[]) => unknown)(rows);
}

get(placeholderValues?: Record<string, unknown>): T['get'] {
if (this.isRqbV2Query) return this.getRqbV2(placeholderValues);

const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
this.logger.logQuery(this.query.sql, params);

Expand All @@ -156,12 +225,27 @@ export class SQLiteDOPreparedQuery<T extends PreparedQueryConfig = PreparedQuery
}

if (customResultMapper) {
return customResultMapper(rows) as T['get'];
return (customResultMapper as (rows: unknown[][]) => unknown)(rows) as T['get'];
}

return mapResultRow(fields!, row, joinsNotNullableMap);
}

private getRqbV2(placeholderValues?: Record<string, unknown>): T['get'] {
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
this.logger.logQuery(this.query.sql, params);

const { client, customResultMapper, query } = this;

const row = params.length > 0 ? client.sql.exec(query.sql, ...params).one() : client.sql.exec(query.sql).one();

if (!row) {
return undefined;
}

return (customResultMapper as (rows: Record<string, unknown>[]) => unknown)([row]) as T['get'];
}

values(placeholderValues?: Record<string, unknown>): T['values'] {
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
this.logger.logQuery(this.query.sql, params);
Expand Down
2 changes: 1 addition & 1 deletion drizzle-orm/src/neon-http/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export class NeonHttpPreparedQuery<

private async executeRqbV2(
placeholderValues: Record<string, unknown>,
token: string | undefined,
token: NeonAuthToken | undefined,
): Promise<T['execute']> {
const params = fillPlaceholders(this.query.params, placeholderValues);

Expand Down
6 changes: 3 additions & 3 deletions drizzle-orm/src/singlestore-core/db.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ResultSetHeader } from 'mysql2/promise';
import type * as V1 from '~/_relations.ts';
import { entityKind } from '~/entity.ts';
import type { TypedQueryBuilder } from '~/query-builders/query-builder.ts';
import type { ExtractTablesWithRelations, RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts';
import { SelectionProxyHandler } from '~/selection-proxy.ts';
import type { SingleStoreDriverDatabase } from '~/singlestore/driver.ts';
import { type ColumnsSelection, type SQL, sql, type SQLWrapper } from '~/sql/sql.ts';
Expand Down Expand Up @@ -31,7 +31,7 @@ export class SingleStoreDatabase<
TQueryResult extends SingleStoreQueryResultHKT,
TPreparedQueryHKT extends PreparedQueryHKTBase,
TFullSchema extends Record<string, unknown> = {},
TSchema extends TablesRelationalConfig = ExtractTablesWithRelations<TFullSchema>,
TSchema extends V1.TablesRelationalConfig = V1.ExtractTablesWithRelations<TFullSchema>,
> {
static readonly [entityKind]: string = 'SingleStoreDatabase';

Expand All @@ -50,7 +50,7 @@ export class SingleStoreDatabase<
readonly dialect: SingleStoreDialect,
/** @internal */
readonly session: SingleStoreSession<any, any, any, any>,
schema: RelationalSchemaConfig<TSchema> | undefined,
schema: V1.RelationalSchemaConfig<TSchema> | undefined,
) {
this._ = schema
? {
Expand Down
Loading

0 comments on commit bad7b01

Please sign in to comment.