diff --git a/drizzle-orm/src/durable-sqlite/driver.ts b/drizzle-orm/src/durable-sqlite/driver.ts index 0be110084..a381b1d43 100644 --- a/drizzle-orm/src/durable-sqlite/driver.ts +++ b/drizzle-orm/src/durable-sqlite/driver.ts @@ -1,13 +1,8 @@ /// +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'; @@ -15,20 +10,27 @@ import { SQLiteDOSession } from './session.ts'; export class DrizzleSqliteDODatabase< TSchema extends Record = Record, -> extends BaseSQLiteDatabase<'sync', SqlStorageCursor>, TSchema> { + TRelations extends AnyRelations = EmptyRelations, +> extends BaseSQLiteDatabase<'sync', SqlStorageCursor>, TSchema, TRelations> { static override readonly [entityKind]: string = 'DrizzleSqliteDODatabase'; /** @internal */ - declare readonly session: SQLiteDOSession>; + declare readonly session: SQLiteDOSession< + TSchema, + TRelations, + ExtractTablesWithRelations, + V1.ExtractTablesWithRelations + >; } export function drizzle< TSchema extends Record = Record, + TRelations extends AnyRelations = EmptyRelations, TClient extends DurableObjectStorage = DurableObjectStorage, >( client: TClient, - config: DrizzleConfig = {}, -): DrizzleSqliteDODatabase & { + config: DrizzleConfig = {}, +): DrizzleSqliteDODatabase & { $client: TClient; } { const dialect = new SQLiteSyncDialect({ casing: config.casing }); @@ -39,11 +41,11 @@ export function drizzle< logger = config.logger; } - let schema: RelationalSchemaConfig | undefined; + let schema: V1.RelationalSchemaConfig | undefined; if (config.schema) { - const tablesConfig = extractTablesRelationalConfig( + const tablesConfig = V1.extractTablesRelationalConfig( config.schema, - createTableRelationsHelpers, + V1.createTableRelationsHelpers, ); schema = { fullSchema: config.schema, @@ -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; + 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 + >; ( db).$client = client; return db as any; diff --git a/drizzle-orm/src/durable-sqlite/migrator.ts b/drizzle-orm/src/durable-sqlite/migrator.ts index 8410b2900..25b725dfe 100644 --- a/drizzle-orm/src/durable-sqlite/migrator.ts +++ b/drizzle-orm/src/durable-sqlite/migrator.ts @@ -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'; @@ -40,8 +41,9 @@ function readMigrationFiles({ journal, migrations }: MigrationConfig): Migration export async function migrate< TSchema extends Record, + TRelations extends AnyRelations, >( - db: DrizzleSqliteDODatabase, + db: DrizzleSqliteDODatabase, config: MigrationConfig, ): Promise { const migrations = readMigrationFiles(config); diff --git a/drizzle-orm/src/durable-sqlite/session.ts b/drizzle-orm/src/durable-sqlite/session.ts index dca5ce7cf..4cd17546c 100644 --- a/drizzle-orm/src/durable-sqlite/session.ts +++ b/drizzle-orm/src/durable-sqlite/session.ts @@ -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'; @@ -20,14 +21,19 @@ export interface SQLiteDOSessionOptions { type PreparedQueryConfig = Omit; -export class SQLiteDOSession, TSchema extends TablesRelationalConfig> - extends SQLiteSession< - 'sync', - SqlStorageCursor>, - TFullSchema, - TSchema - > -{ +export class SQLiteDOSession< + TFullSchema extends Record, + TRelations extends AnyRelations, + TTablesConfig extends TablesRelationalConfig, + TSchema extends V1.TablesRelationalConfig, +> extends SQLiteSession< + 'sync', + SqlStorageCursor>, + TFullSchema, + TRelations, + TTablesConfig, + TSchema +> { static override readonly [entityKind]: string = 'SQLiteDOSession'; private logger: Logger; @@ -35,7 +41,8 @@ export class SQLiteDOSession, TSchem constructor( private client: DurableObjectStorage, dialect: SQLiteSyncDialect, - private schema: RelationalSchemaConfig | undefined, + private relations: AnyRelations | undefined, + private schema: V1.RelationalSchemaConfig | undefined, options: SQLiteDOSessionOptions = {}, ) { super(dialect); @@ -60,13 +67,38 @@ export class SQLiteDOSession, TSchem ); } + prepareRelationalQuery>( + query: Query, + fields: SelectedFieldsOrdered | undefined, + executeMethod: SQLiteExecuteMethod, + customResultMapper: (rows: Record[]) => unknown, + ): SQLiteDOPreparedQuery { + return new SQLiteDOPreparedQuery( + this.client, + query, + this.logger, + fields, + executeMethod, + false, + customResultMapper, + true, + ); + } + override transaction( transaction: ( - tx: SQLiteTransaction<'sync', SqlStorageCursor>, TFullSchema, TSchema>, + tx: SQLiteTransaction< + 'sync', + SqlStorageCursor>, + 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); }); @@ -74,25 +106,42 @@ export class SQLiteDOSession, TSchem } } -export class SQLiteDOTransaction, TSchema extends TablesRelationalConfig> - extends SQLiteTransaction< - 'sync', - SqlStorageCursor>, - TFullSchema, - TSchema - > -{ +export class SQLiteDOTransaction< + TFullSchema extends Record, + TRelations extends AnyRelations, + TTablesConfig extends TablesRelationalConfig, + TSchema extends V1.TablesRelationalConfig, +> extends SQLiteTransaction< + 'sync', + SqlStorageCursor>, + TFullSchema, + TRelations, + TTablesConfig, + TSchema +> { static override readonly [entityKind]: string = 'SQLiteDOTransaction'; - override transaction(transaction: (tx: SQLiteDOTransaction) => T): T { - const tx = new SQLiteDOTransaction('sync', this.dialect, this.session, this.schema, this.nestedIndex + 1); + override transaction( + transaction: (tx: SQLiteDOTransaction) => 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 extends PreparedQueryBase<{ +export class SQLiteDOPreparedQuery< + T extends PreparedQueryConfig = PreparedQueryConfig, + TIsRqbV2 extends boolean = false, +> extends PreparedQueryBase<{ type: 'sync'; run: void; all: T['all']; @@ -109,7 +158,10 @@ export class SQLiteDOPreparedQuery unknown, + private customResultMapper?: ( + rows: TIsRqbV2 extends true ? Record[] : unknown[][], + ) => unknown, + private isRqbV2Query?: TIsRqbV2, ) { super('sync', executeMethod, query); } @@ -122,6 +174,8 @@ export class SQLiteDOPreparedQuery): 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 ?? {}); @@ -133,13 +187,28 @@ export class SQLiteDOPreparedQuery unknown)(rows) as T['all']; } return rows.map((row) => mapResultRow(fields!, row, joinsNotNullableMap)); } + private allRqbV2(placeholderValues?: Record): 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[]) => unknown)(rows); + } + get(placeholderValues?: Record): T['get'] { + if (this.isRqbV2Query) return this.getRqbV2(placeholderValues); + const params = fillPlaceholders(this.query.params, placeholderValues ?? {}); this.logger.logQuery(this.query.sql, params); @@ -156,12 +225,27 @@ export class SQLiteDOPreparedQuery unknown)(rows) as T['get']; } return mapResultRow(fields!, row, joinsNotNullableMap); } + private getRqbV2(placeholderValues?: Record): 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[]) => unknown)([row]) as T['get']; + } + values(placeholderValues?: Record): T['values'] { const params = fillPlaceholders(this.query.params, placeholderValues ?? {}); this.logger.logQuery(this.query.sql, params); diff --git a/drizzle-orm/src/neon-http/session.ts b/drizzle-orm/src/neon-http/session.ts index f7dc9a7a3..ba599810b 100644 --- a/drizzle-orm/src/neon-http/session.ts +++ b/drizzle-orm/src/neon-http/session.ts @@ -90,7 +90,7 @@ export class NeonHttpPreparedQuery< private async executeRqbV2( placeholderValues: Record, - token: string | undefined, + token: NeonAuthToken | undefined, ): Promise { const params = fillPlaceholders(this.query.params, placeholderValues); diff --git a/drizzle-orm/src/singlestore-core/db.ts b/drizzle-orm/src/singlestore-core/db.ts index 1d64448da..871221958 100644 --- a/drizzle-orm/src/singlestore-core/db.ts +++ b/drizzle-orm/src/singlestore-core/db.ts @@ -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'; @@ -31,7 +31,7 @@ export class SingleStoreDatabase< TQueryResult extends SingleStoreQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase, TFullSchema extends Record = {}, - TSchema extends TablesRelationalConfig = ExtractTablesWithRelations, + TSchema extends V1.TablesRelationalConfig = V1.ExtractTablesWithRelations, > { static readonly [entityKind]: string = 'SingleStoreDatabase'; @@ -50,7 +50,7 @@ export class SingleStoreDatabase< readonly dialect: SingleStoreDialect, /** @internal */ readonly session: SingleStoreSession, - schema: RelationalSchemaConfig | undefined, + schema: V1.RelationalSchemaConfig | undefined, ) { this._ = schema ? { diff --git a/drizzle-orm/src/singlestore-core/dialect.ts b/drizzle-orm/src/singlestore-core/dialect.ts index 99a485ac6..0b22228e8 100644 --- a/drizzle-orm/src/singlestore-core/dialect.ts +++ b/drizzle-orm/src/singlestore-core/dialect.ts @@ -1,3 +1,4 @@ +import * as V1 from '~/_relations.ts'; import { aliasedTable, aliasedTableColumn, mapColumnsInAliasedSQLToAlias, mapColumnsInSQLToAlias } from '~/alias.ts'; import { CasingCache } from '~/casing.ts'; import { Column } from '~/column.ts'; @@ -5,18 +6,6 @@ import { entityKind, is } from '~/entity.ts'; import { DrizzleError } from '~/errors.ts'; import { and, eq } from '~/expressions.ts'; import type { MigrationConfig, MigrationMeta } from '~/migrator.ts'; -import { - type BuildRelationalQueryResult, - type DBQueryConfig, - getOperators, - getOrderByOperators, - Many, - normalizeRelation, - One, - type Relation, - type TableRelationalConfig, - type TablesRelationalConfig, -} from '~/relations.ts'; import type { Name, Placeholder, QueryWithTypings, SQLChunk } from '~/sql/sql.ts'; import { Param, SQL, sql, View } from '~/sql/sql.ts'; import { Subquery } from '~/subquery.ts'; @@ -525,16 +514,16 @@ export class SingleStoreDialect { joinOn, }: { fullSchema: Record; - schema: TablesRelationalConfig; + schema: V1.TablesRelationalConfig; tableNamesMap: Record; table: SingleStoreTable; - tableConfig: TableRelationalConfig; - queryConfig: true | DBQueryConfig<'many', true>; + tableConfig: V1.TableRelationalConfig; + queryConfig: true | V1.DBQueryConfig<'many', true>; tableAlias: string; - nestedQueryRelation?: Relation; + nestedQueryRelation?: V1.Relation; joinOn?: SQL; - }): BuildRelationalQueryResult { - let selection: BuildRelationalQueryResult['selection'] = []; + }): V1.BuildRelationalQueryResult { + let selection: V1.BuildRelationalQueryResult['selection'] = []; let limit, offset, orderBy: SingleStoreSelectConfig['orderBy'], where; const joins: SingleStoreSelectJoinConfig[] = []; @@ -557,7 +546,7 @@ export class SingleStoreDialect { if (config.where) { const whereSql = typeof config.where === 'function' - ? config.where(aliasedColumns, getOperators()) + ? config.where(aliasedColumns, V1.getOperators()) : config.where; where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias); } @@ -599,11 +588,11 @@ export class SingleStoreDialect { let selectedRelations: { tsKey: string; - queryConfig: true | DBQueryConfig<'many', false>; - relation: Relation; + queryConfig: true | V1.DBQueryConfig<'many', false>; + relation: V1.Relation; }[] = []; - // Figure out which relations to select + // Figure out which V1.relations to select if (config.with) { selectedRelations = Object.entries(config.with) .filter((entry): entry is [typeof entry[0], NonNullable] => !!entry[1]) @@ -639,7 +628,7 @@ export class SingleStoreDialect { } let orderByOrig = typeof config.orderBy === 'function' - ? config.orderBy(aliasedColumns, getOrderByOperators()) + ? config.orderBy(aliasedColumns, V1.getOrderByOperators()) : config.orderBy ?? []; if (!Array.isArray(orderByOrig)) { orderByOrig = [orderByOrig]; @@ -654,7 +643,7 @@ export class SingleStoreDialect { limit = config.limit; offset = config.offset; - // Process all relations + // Process all V1.relations for ( const { tsKey: selectedRelationTsKey, @@ -662,7 +651,7 @@ export class SingleStoreDialect { relation, } of selectedRelations ) { - const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); + const normalizedRelation = V1.normalizeRelation(schema, tableNamesMap, relation); const relationTableName = getTableUniqueName(relation.referencedTable); const relationTableTsName = tableNamesMap[relationTableName]!; const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; @@ -680,7 +669,7 @@ export class SingleStoreDialect { tableNamesMap, table: fullSchema[relationTableTsName] as SingleStoreTable, tableConfig: schema[relationTableTsName]!, - queryConfig: is(relation, One) + queryConfig: is(relation, V1.One) ? (selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 }) @@ -729,7 +718,7 @@ export class SingleStoreDialect { sql`, `, ) })`; - if (is(nestedQueryRelation, Many)) { + if (is(nestedQueryRelation, V1.Many)) { field = sql`json_agg(${field})`; } const nestedSelection = [{ diff --git a/drizzle-orm/src/singlestore-core/query-builders/query.ts b/drizzle-orm/src/singlestore-core/query-builders/query.ts index c15f7ad59..e456fa7a4 100644 --- a/drizzle-orm/src/singlestore-core/query-builders/query.ts +++ b/drizzle-orm/src/singlestore-core/query-builders/query.ts @@ -1,13 +1,6 @@ +import * as V1 from '~/_relations.ts'; import { entityKind } from '~/entity.ts'; import { QueryPromise } from '~/query-promise.ts'; -import { - type BuildQueryResult, - type BuildRelationalQueryResult, - type DBQueryConfig, - mapRelationalRow, - type TableRelationalConfig, - type TablesRelationalConfig, -} from '~/relations.ts'; import type { Query, QueryWithTypings, SQL } from '~/sql/sql.ts'; import type { KnownKeysOnly } from '~/utils.ts'; import type { SingleStoreDialect } from '../dialect.ts'; @@ -21,8 +14,8 @@ import type { SingleStoreTable } from '../table.ts'; export class RelationalQueryBuilder< TPreparedQueryHKT extends PreparedQueryHKTBase, - TSchema extends TablesRelationalConfig, - TFields extends TableRelationalConfig, + TSchema extends V1.TablesRelationalConfig, + TFields extends V1.TableRelationalConfig, > { static readonly [entityKind]: string = 'SingleStoreRelationalQueryBuilder'; @@ -31,14 +24,14 @@ export class RelationalQueryBuilder< private schema: TSchema, private tableNamesMap: Record, private table: SingleStoreTable, - private tableConfig: TableRelationalConfig, + private tableConfig: V1.TableRelationalConfig, private dialect: SingleStoreDialect, private session: SingleStoreSession, ) {} - findMany>( - config?: KnownKeysOnly>, - ): SingleStoreRelationalQuery[]> { + findMany>( + config?: KnownKeysOnly>, + ): SingleStoreRelationalQuery[]> { return new SingleStoreRelationalQuery( this.fullSchema, this.schema, @@ -47,14 +40,14 @@ export class RelationalQueryBuilder< this.tableConfig, this.dialect, this.session, - config ? (config as DBQueryConfig<'many', true>) : {}, + config ? (config as V1.DBQueryConfig<'many', true>) : {}, 'many', ); } - findFirst, 'limit'>>( - config?: KnownKeysOnly, 'limit'>>, - ): SingleStoreRelationalQuery | undefined> { + findFirst, 'limit'>>( + config?: KnownKeysOnly, 'limit'>>, + ): SingleStoreRelationalQuery | undefined> { return new SingleStoreRelationalQuery( this.fullSchema, this.schema, @@ -63,7 +56,7 @@ export class RelationalQueryBuilder< this.tableConfig, this.dialect, this.session, - config ? { ...(config as DBQueryConfig<'many', true> | undefined), limit: 1 } : { limit: 1 }, + config ? { ...(config as V1.DBQueryConfig<'many', true> | undefined), limit: 1 } : { limit: 1 }, 'first', ); } @@ -79,13 +72,13 @@ export class SingleStoreRelationalQuery< constructor( private fullSchema: Record, - private schema: TablesRelationalConfig, + private schema: V1.TablesRelationalConfig, private tableNamesMap: Record, private table: SingleStoreTable, - private tableConfig: TableRelationalConfig, + private tableConfig: V1.TableRelationalConfig, private dialect: SingleStoreDialect, private session: SingleStoreSession, - private config: DBQueryConfig<'many', true> | true, + private config: V1.DBQueryConfig<'many', true> | true, private queryMode: 'many' | 'first', ) { super(); @@ -97,7 +90,7 @@ export class SingleStoreRelationalQuery< builtQuery, undefined, (rawRows) => { - const rows = rawRows.map((row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection)); + const rows = rawRows.map((row) => V1.mapRelationalRow(this.schema, this.tableConfig, row, query.selection)); if (this.queryMode === 'first') { return rows[0] as TResult; } @@ -118,7 +111,7 @@ export class SingleStoreRelationalQuery< }); } - private _toSQL(): { query: BuildRelationalQueryResult; builtQuery: QueryWithTypings } { + private _toSQL(): { query: V1.BuildRelationalQueryResult; builtQuery: QueryWithTypings } { const query = this._getQuery(); const builtQuery = this.dialect.sqlToQuery(query.sql as SQL); diff --git a/drizzle-orm/src/singlestore-core/session.ts b/drizzle-orm/src/singlestore-core/session.ts index bc31f3d97..f07e53f30 100644 --- a/drizzle-orm/src/singlestore-core/session.ts +++ b/drizzle-orm/src/singlestore-core/session.ts @@ -1,6 +1,6 @@ +import type * as V1 from '~/_relations.ts'; import { entityKind } from '~/entity.ts'; import { TransactionRollbackError } from '~/errors.ts'; -import type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts'; import { type Query, type SQL, sql } from '~/sql/sql.ts'; import type { Assume, Equal } from '~/utils.ts'; import { SingleStoreDatabase } from './db.ts'; @@ -61,7 +61,7 @@ export abstract class SingleStoreSession< TQueryResult extends SingleStoreQueryResultHKT = SingleStoreQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase, TFullSchema extends Record = Record, - TSchema extends TablesRelationalConfig = Record, + TSchema extends V1.TablesRelationalConfig = Record, > { static readonly [entityKind]: string = 'SingleStoreSession'; @@ -129,14 +129,14 @@ export abstract class SingleStoreTransaction< TQueryResult extends SingleStoreQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase, TFullSchema extends Record = Record, - TSchema extends TablesRelationalConfig = Record, + TSchema extends V1.TablesRelationalConfig = Record, > extends SingleStoreDatabase { static override readonly [entityKind]: string = 'SingleStoreTransaction'; constructor( dialect: SingleStoreDialect, session: SingleStoreSession, - protected schema: RelationalSchemaConfig | undefined, + protected schema: V1.RelationalSchemaConfig | undefined, protected readonly nestedIndex: number, ) { super(dialect, session, schema); diff --git a/drizzle-orm/src/singlestore-proxy/driver.ts b/drizzle-orm/src/singlestore-proxy/driver.ts index ea24ae2d8..84f04035b 100644 --- a/drizzle-orm/src/singlestore-proxy/driver.ts +++ b/drizzle-orm/src/singlestore-proxy/driver.ts @@ -1,11 +1,11 @@ -import { entityKind } from '~/entity.ts'; -import { DefaultLogger } from '~/logger.ts'; import { createTableRelationsHelpers, extractTablesRelationalConfig, type RelationalSchemaConfig, type TablesRelationalConfig, -} from '~/relations.ts'; +} from '~/_relations.ts'; +import { entityKind } from '~/entity.ts'; +import { DefaultLogger } from '~/logger.ts'; import { SingleStoreDatabase } from '~/singlestore-core/db.ts'; import { SingleStoreDialect } from '~/singlestore-core/dialect.ts'; import type { DrizzleConfig } from '~/utils.ts'; diff --git a/drizzle-orm/src/singlestore-proxy/session.ts b/drizzle-orm/src/singlestore-proxy/session.ts index 42cc8ecde..56155e8e1 100644 --- a/drizzle-orm/src/singlestore-proxy/session.ts +++ b/drizzle-orm/src/singlestore-proxy/session.ts @@ -1,9 +1,9 @@ import type { FieldPacket, ResultSetHeader } from 'mysql2/promise'; +import type * as V1 from '~/_relations.ts'; import { Column } from '~/column.ts'; import { entityKind, is } from '~/entity.ts'; import type { Logger } from '~/logger.ts'; import { NoopLogger } from '~/logger.ts'; -import type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts'; import type { SingleStoreDialect } from '~/singlestore-core/dialect.ts'; import { SingleStoreTransaction } from '~/singlestore-core/index.ts'; import type { SelectedFieldsOrdered } from '~/singlestore-core/query-builders/select.types.ts'; @@ -28,7 +28,7 @@ export interface SingleStoreRemoteSessionOptions { export class SingleStoreRemoteSession< TFullSchema extends Record, - TSchema extends TablesRelationalConfig, + TSchema extends V1.TablesRelationalConfig, > extends SingleStoreSession { static override readonly [entityKind]: string = 'SingleStoreRemoteSession'; @@ -37,7 +37,7 @@ export class SingleStoreRemoteSession< constructor( private client: RemoteCallback, dialect: SingleStoreDialect, - private schema: RelationalSchemaConfig | undefined, + private schema: V1.RelationalSchemaConfig | undefined, options: SingleStoreRemoteSessionOptions, ) { super(dialect); @@ -79,7 +79,7 @@ export class SingleStoreRemoteSession< export class SingleStoreProxyTransaction< TFullSchema extends Record, - TSchema extends TablesRelationalConfig, + TSchema extends V1.TablesRelationalConfig, > extends SingleStoreTransaction< SingleStoreRemoteQueryResultHKT, SingleStoreRemotePreparedQueryHKT, diff --git a/drizzle-orm/src/singlestore/driver.ts b/drizzle-orm/src/singlestore/driver.ts index ba294f6dc..94f3a007b 100644 --- a/drizzle-orm/src/singlestore/driver.ts +++ b/drizzle-orm/src/singlestore/driver.ts @@ -1,14 +1,14 @@ import { type Connection as CallbackConnection, createPool, type Pool as CallbackPool, type PoolOptions } from 'mysql2'; import type { Connection, Pool } from 'mysql2/promise'; -import { entityKind } from '~/entity.ts'; -import type { Logger } from '~/logger.ts'; -import { DefaultLogger } from '~/logger.ts'; import { createTableRelationsHelpers, extractTablesRelationalConfig, type RelationalSchemaConfig, type TablesRelationalConfig, -} from '~/relations.ts'; +} from '~/_relations.ts'; +import { entityKind } from '~/entity.ts'; +import type { Logger } from '~/logger.ts'; +import { DefaultLogger } from '~/logger.ts'; import { SingleStoreDatabase } from '~/singlestore-core/db.ts'; import { SingleStoreDialect } from '~/singlestore-core/dialect.ts'; import { type DrizzleConfig, type IfNotImported, type ImportTypeError, isConfig } from '~/utils.ts'; diff --git a/drizzle-orm/src/singlestore/session.ts b/drizzle-orm/src/singlestore/session.ts index fd70a1d52..4c2e40670 100644 --- a/drizzle-orm/src/singlestore/session.ts +++ b/drizzle-orm/src/singlestore/session.ts @@ -10,11 +10,11 @@ import type { RowDataPacket, } from 'mysql2/promise'; import { once } from 'node:events'; +import type * as V1 from '~/_relations.ts'; import { Column } from '~/column.ts'; import { entityKind, is } from '~/entity.ts'; import type { Logger } from '~/logger.ts'; import { NoopLogger } from '~/logger.ts'; -import type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts'; import type { SingleStoreDialect } from '~/singlestore-core/dialect.ts'; import type { SelectedFieldsOrdered } from '~/singlestore-core/query-builders/select.types.ts'; import { @@ -188,7 +188,7 @@ export interface SingleStoreDriverSessionOptions { export class SingleStoreDriverSession< TFullSchema extends Record, - TSchema extends TablesRelationalConfig, + TSchema extends V1.TablesRelationalConfig, > extends SingleStoreSession { static override readonly [entityKind]: string = 'SingleStoreDriverSession'; @@ -197,7 +197,7 @@ export class SingleStoreDriverSession< constructor( private client: SingleStoreDriverClient, dialect: SingleStoreDialect, - private schema: RelationalSchemaConfig | undefined, + private schema: V1.RelationalSchemaConfig | undefined, private options: SingleStoreDriverSessionOptions, ) { super(dialect); @@ -296,7 +296,7 @@ export class SingleStoreDriverSession< export class SingleStoreDriverTransaction< TFullSchema extends Record, - TSchema extends TablesRelationalConfig, + TSchema extends V1.TablesRelationalConfig, > extends SingleStoreTransaction< SingleStoreDriverQueryResultHKT, SingleStoreDriverPreparedQueryHKT, diff --git a/integration-tests/tests/pg/neon-http.test.ts b/integration-tests/tests/pg/neon-http.test.ts index 45511bc66..649bd1923 100644 --- a/integration-tests/tests/pg/neon-http.test.ts +++ b/integration-tests/tests/pg/neon-http.test.ts @@ -561,9 +561,9 @@ describe('$withAuth tests', (it) => { }); it('rqbV2', async () => { - await db.$withAuth('rqb').query.usersTable.findFirst().catch(() => null); + await db.$withAuth('rqbV2').query.usersTable.findFirst().catch(() => null); - expect(client.mock.lastCall?.[2]).toStrictEqual({ arrayMode: true, fullResults: true, authToken: 'rqb' }); + expect(client.mock.lastCall?.[2]).toStrictEqual({ arrayMode: false, fullResults: true, authToken: 'rqbV2' }); }); it('exec', async () => { @@ -601,6 +601,7 @@ describe('$withAuth callback tests', (it) => { schema: { usersTable, }, + relations: defineRelations({ usersTable }, () => ({})), }); const auth = (token: string) => () => token; @@ -660,11 +661,17 @@ describe('$withAuth callback tests', (it) => { }); it('rqb', async () => { - await db.$withAuth(auth('rqb')).query.usersTable.findFirst().catch(() => null); + await db.$withAuth(auth('rqb'))._query.usersTable.findFirst().catch(() => null); expect(client.mock.lastCall?.[2]['authToken']()).toStrictEqual('rqb'); }); + it('rqbV2', async () => { + await db.$withAuth(auth('rqbV2')).query.usersTable.findFirst().catch(() => null); + + expect(client.mock.lastCall?.[2]).toStrictEqual({ arrayMode: false, fullResults: true, authToken: 'rqbV2' }); + }); + it('exec', async () => { await db.$withAuth(auth('exec')).execute(`SELECT 1`).catch(() => null); @@ -696,6 +703,7 @@ describe('$withAuth async callback tests', (it) => { schema: { usersTable, }, + relations: defineRelations({ usersTable }, () => ({})), }); const auth = (token: string) => async () => token; @@ -763,12 +771,19 @@ describe('$withAuth async callback tests', (it) => { }); it('rqb', async () => { - await db.$withAuth(auth('rqb')).query.usersTable.findFirst().catch(() => null); + await db.$withAuth(auth('rqb'))._query.usersTable.findFirst().catch(() => null); expect(client.mock.lastCall?.[2]['authToken']()).toBeInstanceOf(Promise); expect(await client.mock.lastCall?.[2]['authToken']()).toStrictEqual('rqb'); }); + it('rqbV2', async () => { + await db.$withAuth(auth('rqbV2'))._query.usersTable.findFirst().catch(() => null); + + expect(client.mock.lastCall?.[2]['authToken']()).toBeInstanceOf(Promise); + expect(await client.mock.lastCall?.[2]['authToken']()).toStrictEqual('rqbV2'); + }); + it('exec', async () => { await db.$withAuth(auth('exec')).execute(`SELECT 1`).catch(() => null); diff --git a/integration-tests/tests/relational/singlestore.schema.ts b/integration-tests/tests/relational/singlestore.schema.ts index ca3386ba0..04c7471bb 100644 --- a/integration-tests/tests/relational/singlestore.schema.ts +++ b/integration-tests/tests/relational/singlestore.schema.ts @@ -1,6 +1,6 @@ import { bigint, boolean, primaryKey, serial, singlestoreTable, text, timestamp } from 'drizzle-orm/singlestore-core'; -import { relations } from 'drizzle-orm'; +import { relations } from 'drizzle-orm/_relations'; export const usersTable = singlestoreTable('users', { id: serial('id').primaryKey(),