From d0fb8cd58155a603dacecd5c47b87a8a00da2969 Mon Sep 17 00:00:00 2001 From: Pedro Rodrigues <44656907+Rodriguespn@users.noreply.github.com> Date: Tue, 1 Oct 2024 22:53:51 +0100 Subject: [PATCH] Fix/branch clean up for pr drizzle orm (#30) * branch clean up for pr * wip [last visited drizzle-kit/src/cli/validations/common.ts * wip [last visited drizzle-kit/src/schemaValidator.ts * drizzle kit cleaning * lint fix * remove unecessary readme.md * replace prepareAndMigrateSqlite for prepareAndMigrateSingleStore when dialect is singlestore * drizzle orm cleaning --- drizzle-orm/package.json | 6 +- drizzle-orm/src/better-sqlite3/driver.ts | 11 +- drizzle-orm/src/bun-sqlite/driver.ts | 9 +- drizzle-orm/src/expo-sqlite/driver.ts | 11 +- drizzle-orm/src/index.ts | 2 - drizzle-orm/src/libsql/migrator.ts | 4 +- drizzle-orm/src/libsql/session.ts | 15 - drizzle-orm/src/monodriver.ts | 406 ------------------ drizzle-orm/src/monomigrator.ts | 111 ----- drizzle-orm/src/mysql-core/db.ts | 11 +- .../src/mysql-core/query-builders/count.ts | 80 ---- drizzle-orm/src/mysql-core/session.ts | 8 - drizzle-orm/src/mysql-proxy/driver.ts | 9 +- drizzle-orm/src/mysql2/driver.ts | 8 +- drizzle-orm/src/mysql2/migrator.ts | 11 +- drizzle-orm/src/neon-http/session.ts | 10 +- drizzle-orm/src/neon-serverless/driver.ts | 8 +- drizzle-orm/src/node-postgres/driver.ts | 8 +- drizzle-orm/src/node-postgres/session.ts | 9 +- drizzle-orm/src/op-sqlite/driver.ts | 9 +- drizzle-orm/src/operations.ts | 1 - drizzle-orm/src/pg-core/db.ts | 17 +- .../src/pg-core/query-builders/count.ts | 79 ---- drizzle-orm/src/pg-core/session.ts | 8 - drizzle-orm/src/pg-proxy/driver.ts | 9 +- drizzle-orm/src/pg-proxy/session.ts | 3 +- drizzle-orm/src/pglite/driver.ts | 8 +- drizzle-orm/src/pglite/session.ts | 9 +- .../src/planetscale-serverless/driver.ts | 9 +- .../src/planetscale-serverless/migrator.ts | 11 +- .../src/planetscale-serverless/session.ts | 8 - drizzle-orm/src/postgres-js/driver.ts | 9 +- drizzle-orm/src/sqlite-core/db.ts | 11 +- .../src/sqlite-core/query-builders/count.ts | 77 ---- drizzle-orm/src/sqlite-core/session.ts | 6 - drizzle-orm/src/tidb-serverless/driver.ts | 9 +- drizzle-orm/src/tidb-serverless/session.ts | 8 - drizzle-orm/src/vercel-postgres/driver.ts | 8 +- drizzle-orm/src/version.ts | 2 +- drizzle-orm/type-tests/mysql/count.ts | 61 --- drizzle-orm/type-tests/pg/count.ts | 61 --- drizzle-orm/type-tests/sqlite/count.ts | 61 --- 42 files changed, 62 insertions(+), 1159 deletions(-) delete mode 100644 drizzle-orm/src/monodriver.ts delete mode 100644 drizzle-orm/src/monomigrator.ts delete mode 100644 drizzle-orm/src/mysql-core/query-builders/count.ts delete mode 100644 drizzle-orm/src/pg-core/query-builders/count.ts delete mode 100644 drizzle-orm/src/sqlite-core/query-builders/count.ts delete mode 100644 drizzle-orm/type-tests/mysql/count.ts delete mode 100644 drizzle-orm/type-tests/pg/count.ts delete mode 100644 drizzle-orm/type-tests/sqlite/count.ts diff --git a/drizzle-orm/package.json b/drizzle-orm/package.json index 333521a48..888f7efcb 100644 --- a/drizzle-orm/package.json +++ b/drizzle-orm/package.json @@ -1,6 +1,6 @@ { "name": "drizzle-orm", - "version": "0.34.0", + "version": "0.33.0", "description": "Drizzle ORM package for SQL databases", "type": "module", "scripts": { @@ -46,7 +46,7 @@ "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=3", "@electric-sql/pglite": ">=0.1.1", - "@libsql/client": ">=0.10.0", + "@libsql/client": "*", "@neondatabase/serverless": ">=0.1", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", @@ -161,7 +161,7 @@ "@aws-sdk/client-rds-data": "^3.549.0", "@cloudflare/workers-types": "^4.20230904.0", "@electric-sql/pglite": "^0.1.1", - "@libsql/client": "^0.10.0", + "@libsql/client": "^0.5.6", "@neondatabase/serverless": "^0.9.0", "@op-engineering/op-sqlite": "^2.0.16", "@opentelemetry/api": "^1.4.1", diff --git a/drizzle-orm/src/better-sqlite3/driver.ts b/drizzle-orm/src/better-sqlite3/driver.ts index 8fe7c00fb..728586e57 100644 --- a/drizzle-orm/src/better-sqlite3/driver.ts +++ b/drizzle-orm/src/better-sqlite3/driver.ts @@ -1,5 +1,4 @@ import type { Database, RunResult } from 'better-sqlite3'; -import { entityKind } from '~/entity.ts'; import { DefaultLogger } from '~/logger.ts'; import { createTableRelationsHelpers, @@ -12,11 +11,9 @@ import { SQLiteSyncDialect } from '~/sqlite-core/dialect.ts'; import type { DrizzleConfig } from '~/utils.ts'; import { BetterSQLiteSession } from './session.ts'; -export class BetterSQLite3Database = Record> - extends BaseSQLiteDatabase<'sync', RunResult, TSchema> -{ - static readonly [entityKind]: string = 'BetterSQLite3Database'; -} +export type BetterSQLite3Database< + TSchema extends Record = Record, +> = BaseSQLiteDatabase<'sync', RunResult, TSchema>; export function drizzle = Record>( client: Database, @@ -44,5 +41,5 @@ export function drizzle = Record; + return new BaseSQLiteDatabase('sync', dialect, session, schema) as BetterSQLite3Database; } diff --git a/drizzle-orm/src/bun-sqlite/driver.ts b/drizzle-orm/src/bun-sqlite/driver.ts index 5771bd371..0d196ff03 100644 --- a/drizzle-orm/src/bun-sqlite/driver.ts +++ b/drizzle-orm/src/bun-sqlite/driver.ts @@ -1,7 +1,6 @@ /// import type { Database } from 'bun:sqlite'; -import { entityKind } from '~/entity.ts'; import { DefaultLogger } from '~/logger.ts'; import { createTableRelationsHelpers, @@ -14,11 +13,9 @@ import { SQLiteSyncDialect } from '~/sqlite-core/dialect.ts'; import type { DrizzleConfig } from '~/utils.ts'; import { SQLiteBunSession } from './session.ts'; -export class BunSQLiteDatabase< +export type BunSQLiteDatabase< TSchema extends Record = Record, -> extends BaseSQLiteDatabase<'sync', void, TSchema> { - static readonly [entityKind]: string = 'BunSQLiteDatabase'; -} +> = BaseSQLiteDatabase<'sync', void, TSchema>; export function drizzle = Record>( client: Database, @@ -46,5 +43,5 @@ export function drizzle = Record; + return new BaseSQLiteDatabase('sync', dialect, session, schema) as BunSQLiteDatabase; } diff --git a/drizzle-orm/src/expo-sqlite/driver.ts b/drizzle-orm/src/expo-sqlite/driver.ts index fb858e482..ae8ce6577 100644 --- a/drizzle-orm/src/expo-sqlite/driver.ts +++ b/drizzle-orm/src/expo-sqlite/driver.ts @@ -1,5 +1,4 @@ import type { SQLiteDatabase, SQLiteRunResult } from 'expo-sqlite/next'; -import { entityKind } from '~/entity.ts'; import { DefaultLogger } from '~/logger.ts'; import { createTableRelationsHelpers, @@ -12,11 +11,9 @@ import { SQLiteSyncDialect } from '~/sqlite-core/dialect.ts'; import type { DrizzleConfig } from '~/utils.ts'; import { ExpoSQLiteSession } from './session.ts'; -export class ExpoSQLiteDatabase = Record> - extends BaseSQLiteDatabase<'sync', SQLiteRunResult, TSchema> -{ - static readonly [entityKind]: string = 'ExpoSQLiteDatabase'; -} +export type ExpoSQLiteDatabase< + TSchema extends Record = Record, +> = BaseSQLiteDatabase<'sync', SQLiteRunResult, TSchema>; export function drizzle = Record>( client: SQLiteDatabase, @@ -44,5 +41,5 @@ export function drizzle = Record; + return new BaseSQLiteDatabase('sync', dialect, session, schema) as ExpoSQLiteDatabase; } diff --git a/drizzle-orm/src/index.ts b/drizzle-orm/src/index.ts index 469f5713e..bc72260b9 100644 --- a/drizzle-orm/src/index.ts +++ b/drizzle-orm/src/index.ts @@ -5,8 +5,6 @@ export * from './entity.ts'; export * from './errors.ts'; export * from './expressions.ts'; export * from './logger.ts'; -export * from './monodriver.ts'; -export * from './monomigrator.ts'; export * from './operations.ts'; export * from './query-promise.ts'; export * from './relations.ts'; diff --git a/drizzle-orm/src/libsql/migrator.ts b/drizzle-orm/src/libsql/migrator.ts index d362a2e4d..58bcc9e05 100644 --- a/drizzle-orm/src/libsql/migrator.ts +++ b/drizzle-orm/src/libsql/migrator.ts @@ -5,7 +5,7 @@ import type { LibSQLDatabase } from './driver.ts'; export async function migrate>( db: LibSQLDatabase, - config: MigrationConfig | string, + config: MigrationConfig, ) { const migrations = readMigrationFiles(config); const migrationsTable = config === undefined @@ -47,5 +47,5 @@ export async function migrate>( } } - await db.session.migrate(statementToBatch); + await db.session.batch(statementToBatch); } diff --git a/drizzle-orm/src/libsql/session.ts b/drizzle-orm/src/libsql/session.ts index 640977734..29e4e268f 100644 --- a/drizzle-orm/src/libsql/session.ts +++ b/drizzle-orm/src/libsql/session.ts @@ -76,21 +76,6 @@ export class LibSQLSession< return batchResults.map((result, i) => preparedQueries[i]!.mapResult(result, true)); } - async migrate[] | readonly BatchItem<'sqlite'>[]>(queries: T) { - const preparedQueries: PreparedQuery[] = []; - const builtQueries: InStatement[] = []; - - for (const query of queries) { - const preparedQuery = query._prepare(); - const builtQuery = preparedQuery.getQuery(); - preparedQueries.push(preparedQuery); - builtQueries.push({ sql: builtQuery.sql, args: builtQuery.params as InArgs }); - } - - const batchResults = await this.client.migrate(builtQueries); - return batchResults.map((result, i) => preparedQueries[i]!.mapResult(result, true)); - } - override async transaction( transaction: (db: LibSQLTransaction) => T | Promise, _config?: SQLiteTransactionConfig, diff --git a/drizzle-orm/src/monodriver.ts b/drizzle-orm/src/monodriver.ts deleted file mode 100644 index 612da1bdc..000000000 --- a/drizzle-orm/src/monodriver.ts +++ /dev/null @@ -1,406 +0,0 @@ -/* eslint-disable import/extensions */ -import type { RDSDataClient, RDSDataClientConfig, RDSDataClientConfig as RDSConfig } from '@aws-sdk/client-rds-data'; -import type { Client as LibsqlClient, Config as LibsqlConfig } from '@libsql/client'; -import type { - HTTPTransactionOptions as NeonHttpConfig, - NeonQueryFunction, - Pool as NeonServerlessPool, - PoolConfig as NeonServerlessConfig, -} from '@neondatabase/serverless'; -import type { Client as PlanetscaleClient, Config as PlanetscaleConfig } from '@planetscale/database'; -import type { Config as TiDBServerlessConfig, Connection as TiDBConnection } from '@tidbcloud/serverless'; -import type { QueryResult, QueryResultRow, VercelPool } from '@vercel/postgres'; -import type { Database as BetterSQLite3Database, Options as BetterSQLite3Options } from 'better-sqlite3'; -import type { Database as BunDatabase } from 'bun:sqlite'; -import type { Pool as Mysql2Pool, PoolOptions as Mysql2Config } from 'mysql2'; -import type { Pool as NodePgPool, PoolConfig as NodePGPoolConfig } from 'pg'; -import type { - Options as PostgresJSOptions, - PostgresType as PostgresJSPostgresType, - Sql as PostgresJsClient, -} from 'postgres'; -import type { AwsDataApiPgDatabase, DrizzleAwsDataApiPgConfig } from './aws-data-api/pg/index.ts'; -import type { BetterSQLite3Database as DrizzleBetterSQLite3Database } from './better-sqlite3/index.ts'; -import type { BunSQLiteDatabase } from './bun-sqlite/index.ts'; -import type { DrizzleD1Database } from './d1/index.ts'; -import type { LibSQLDatabase } from './libsql/index.ts'; -import type { MySql2Database, MySql2DrizzleConfig } from './mysql2/index.ts'; -import type { NeonHttpDatabase } from './neon-http/index.ts'; -import type { NeonDatabase } from './neon-serverless/index.ts'; -import type { NodePgDatabase } from './node-postgres/index.ts'; -import type { PlanetScaleDatabase } from './planetscale-serverless/index.ts'; -import type { PostgresJsDatabase } from './postgres-js/index.ts'; -import type { SingleStoreDriverDatabase, SingleStoreDriverDrizzleConfig } from './singlestore/driver.ts'; -import type { TiDBServerlessDatabase } from './tidb-serverless/index.ts'; -import type { DrizzleConfig } from './utils.ts'; -import type { VercelPgDatabase } from './vercel-postgres/index.ts'; - -type BunSqliteDatabaseOptions = - | number - | { - /** - * Open the database as read-only (no write operations, no create). - * - * Equivalent to {@link constants.SQLITE_OPEN_READONLY} - */ - readonly?: boolean; - /** - * Allow creating a new database - * - * Equivalent to {@link constants.SQLITE_OPEN_CREATE} - */ - create?: boolean; - /** - * Open the database as read-write - * - * Equivalent to {@link constants.SQLITE_OPEN_READWRITE} - */ - readwrite?: boolean; - }; - -type BunSqliteDatabaseConfig = - | { - filename?: ':memory:' | (string & {}); - options?: BunSqliteDatabaseOptions; - } - | ':memory:' - | (string & {}) - | undefined; - -type BetterSQLite3DatabaseConfig = - | { - filename?: - | ':memory:' - | (string & {}) - | Buffer; - options?: BetterSQLite3Options; - } - | ':memory:' - | (string & {}) - | undefined; - -type MonodriverNeonHttpConfig = { - connectionString: string; - options?: NeonHttpConfig; -}; - -type VercelPrimitive = string | number | boolean | undefined | null; - -type DatabaseClient = - | 'node-postgres' - | 'postgres-js' - | 'neon-serverless' - | 'neon-http' - | 'vercel-postgres' - | 'aws-data-api-pg' - | 'planetscale' - | 'mysql2' - | 'tidb-serverless' - | 'libsql' - | 'd1' - | 'bun:sqlite' - | 'better-sqlite3' - | 'singlestore'; - -type ClientDrizzleInstanceMap> = { - 'node-postgres': NodePgDatabase; - 'postgres-js': PostgresJsDatabase; - 'neon-serverless': NeonDatabase; - 'neon-http': NeonHttpDatabase; - 'vercel-postgres': VercelPgDatabase; - 'aws-data-api-pg': AwsDataApiPgDatabase; - planetscale: PlanetScaleDatabase; - mysql2: MySql2Database; - 'tidb-serverless': TiDBServerlessDatabase; - libsql: LibSQLDatabase; - d1: DrizzleD1Database; - 'bun:sqlite': BunSQLiteDatabase; - 'better-sqlite3': DrizzleBetterSQLite3Database; - singlestore: SingleStoreDriverDatabase; -}; - -type ClientInstanceMap = { - 'node-postgres': NodePgPool; - 'postgres-js': PostgresJsClient; - 'neon-serverless': NeonServerlessPool; - 'neon-http': NeonQueryFunction; - 'vercel-postgres': - & VercelPool - & (( - strings: TemplateStringsArray, - ...values: VercelPrimitive[] - ) => Promise>); - 'aws-data-api-pg': RDSDataClient; - planetscale: PlanetscaleClient; - mysql2: Mysql2Pool; - 'tidb-serverless': TiDBConnection; - libsql: LibsqlClient; - d1: D1Database; - 'bun:sqlite': BunDatabase; - 'better-sqlite3': BetterSQLite3Database; - singlestore: SingleStoreDriverDatabase; -}; - -type InitializerParams = { - 'node-postgres': { - connection: NodePGPoolConfig; - }; - 'postgres-js': { - connection: string | PostgresJSOptions>; - }; - 'neon-serverless': { - connection: NeonServerlessConfig; - }; - 'neon-http': { - connection: MonodriverNeonHttpConfig; - }; - 'vercel-postgres': { - connection: VercelPool; - }; - 'aws-data-api-pg': { - connection?: RDSConfig; - }; - planetscale: { - connection: PlanetscaleConfig; - }; - mysql2: { - connection: Mysql2Config | string; - }; - 'tidb-serverless': { - connection: TiDBServerlessConfig; - }; - libsql: { - connection: LibsqlConfig; - }; - d1: { - connection: D1Database; - }; - 'bun:sqlite': { - connection?: BunSqliteDatabaseConfig; - }; - 'better-sqlite3': { - connection?: BetterSQLite3DatabaseConfig; - }; - singlestore: { - // This Mysql2Config is from the node package 'mysql2' and not the one from Drizzle - connection: Mysql2Config; - }; -}; - -type DetermineClient< - TClient extends DatabaseClient, - TSchema extends Record, -> = - & ClientDrizzleInstanceMap< - TSchema - >[TClient] - & { - $client: ClientInstanceMap[TClient]; - }; - -const importError = (libName: string) => { - throw new Error( - `Please install '${libName}' for Drizzle ORM to connect to database`, - ); -}; - -function assertUnreachable(_: never | undefined): never { - throw new Error("Didn't expect to get here"); -} - -export async function drizzle< - TClient extends DatabaseClient, - TSchema extends Record = Record, ->( - client: TClient, - params: - & InitializerParams[TClient] - & (TClient extends 'mysql2' ? MySql2DrizzleConfig - : TClient extends 'aws-data-api-pg' ? DrizzleAwsDataApiPgConfig - : TClient extends 'neon-serverless' ? DrizzleConfig & { - ws?: any; - } - : TClient extends 'singlestore' ? SingleStoreDriverDrizzleConfig - : DrizzleConfig), -): Promise> { - const { connection, ws, ...drizzleConfig } = params as typeof params & { - ws?: any; - }; - - switch (client) { - case 'node-postgres': { - const { Pool } = await import('pg').catch(() => importError('pg')); - const { drizzle } = await import('./node-postgres'); - const instance = new Pool(connection as NodePGPoolConfig); - - const db = drizzle(instance, drizzleConfig) as any; - db.$client = instance; - - return db; - } - case 'aws-data-api-pg': { - const { RDSDataClient } = await import('@aws-sdk/client-rds-data').catch(() => - importError('@aws-sdk/client-rds-data') - ); - const { drizzle } = await import('./aws-data-api/pg'); - const instance = new RDSDataClient(connection as RDSDataClientConfig); - - const db = drizzle(instance, drizzleConfig as any as DrizzleAwsDataApiPgConfig) as any; - db.$client = instance; - - return db; - } - case 'better-sqlite3': { - const { default: Client } = await import('better-sqlite3').catch(() => importError('better-sqlite3')); - const { drizzle } = await import('./better-sqlite3'); - - if (typeof connection === 'object') { - const { filename, options } = connection as Exclude; - - const instance = new Client(filename, options); - - const db = drizzle(instance, drizzleConfig) as any; - db.$client = instance; - - return db; - } - - const instance = new Client(connection); - - const db = drizzle(instance, drizzleConfig) as any; - db.$client = instance; - - return db; - } - case 'bun:sqlite': { - const { Database: Client } = await import('bun:sqlite').catch(() => importError('bun:sqlite')); - const { drizzle } = await import('./bun-sqlite'); - - if (typeof connection === 'object') { - const { filename, options } = connection as Exclude; - - const instance = new Client(filename, options); - - const db = drizzle(instance, drizzleConfig) as any; - db.$client = instance; - - return db; - } - - const instance = new Client(connection); - - const db = drizzle(instance, drizzleConfig) as any; - db.$client = instance; - - return db; - } - case 'd1': { - const { drizzle } = await import('./d1'); - - const db = drizzle(connection as D1Database, drizzleConfig) as any; - db.$client = connection; - - return db; - } - case 'libsql': { - const { createClient } = await import('@libsql/client').catch(() => importError('@libsql/client')); - const { drizzle } = await import('./libsql'); - const instance = createClient(connection as LibsqlConfig); - - const db = drizzle(instance, drizzleConfig) as any; - db.$client = instance; - - return db; - } - case 'mysql2': { - const { createPool } = await import('mysql2/promise').catch(() => importError('mysql2/promise')); - const instance = createPool(connection as Mysql2Config); - const { drizzle } = await import('./mysql2'); - - const db = drizzle(instance, drizzleConfig as MySql2DrizzleConfig) as any; - db.$client = instance; - - return db; - } - case 'neon-http': { - const { neon } = await import('@neondatabase/serverless').catch(() => importError('@neondatabase/serverless')); - const { connectionString, options } = connection as MonodriverNeonHttpConfig; - const { drizzle } = await import('./neon-http'); - const instance = neon(connectionString, options); - - const db = drizzle(instance, drizzleConfig) as any; - db.$client = instance; - - return db; - } - case 'neon-serverless': { - const { Pool, neonConfig } = await import('@neondatabase/serverless').catch(() => - importError('@neondatabase/serverless') - ); - const { drizzle } = await import('./neon-serverless'); - const instance = new Pool(connection as NeonServerlessConfig); - - if (ws) { - neonConfig.webSocketConstructor = ws; - } - - const db = drizzle(instance, drizzleConfig) as any; - db.$client = instance; - - return db; - } - case 'planetscale': { - const { Client } = await import('@planetscale/database').catch(() => importError('@planetscale/database')); - const { drizzle } = await import('./planetscale-serverless'); - const instance = new Client( - connection as PlanetscaleConfig, - ); - - const db = drizzle(instance, drizzleConfig) as any; - db.$client = instance; - - return db; - } - case 'postgres-js': { - const { default: client } = await import('postgres').catch(() => importError('postgres')); - const { drizzle } = await import('./postgres-js'); - const instance = client(connection as PostgresJSOptions>); - - const db = drizzle(instance, drizzleConfig) as any; - db.$client = instance; - - return db; - } - case 'tidb-serverless': { - const { connect } = await import('@tidbcloud/serverless').catch(() => importError('@tidbcloud/serverless')); - const { drizzle } = await import('./tidb-serverless'); - const instance = connect(connection as TiDBServerlessConfig); - - const db = drizzle(instance, drizzleConfig) as any; - db.$client = instance; - - return db; - } - case 'vercel-postgres': { - const { sql } = await import('@vercel/postgres').catch(() => importError('@vercel/postgres')); - const { drizzle } = await import('./vercel-postgres'); - - const db = drizzle(sql, drizzleConfig) as any; - db.$client = sql; - - return db; - } - case 'singlestore': { - const { createPool } = await import('mysql2/promise').catch(() => importError('mysql2/promise')); - const instance = createPool(connection as Mysql2Config); - const { drizzle } = await import('./mysql2'); - - const db = drizzle(instance, drizzleConfig as SingleStoreDriverDrizzleConfig) as any; - db.$client = instance; - - return db; - } - } - - assertUnreachable(client); -} diff --git a/drizzle-orm/src/monomigrator.ts b/drizzle-orm/src/monomigrator.ts deleted file mode 100644 index d113b223b..000000000 --- a/drizzle-orm/src/monomigrator.ts +++ /dev/null @@ -1,111 +0,0 @@ -/* eslint-disable import/extensions */ -import type { AwsDataApiPgDatabase } from './aws-data-api/pg/index.ts'; -import type { BetterSQLite3Database } from './better-sqlite3/index.ts'; -import type { BunSQLiteDatabase } from './bun-sqlite/index.ts'; -import type { DrizzleD1Database } from './d1/index.ts'; -import { entityKind } from './entity.ts'; -import type { LibSQLDatabase } from './libsql/index.ts'; -import type { MigrationConfig } from './migrator.ts'; -import type { MySql2Database } from './mysql2/index.ts'; -import type { NeonHttpDatabase } from './neon-http/index.ts'; -import type { NeonDatabase } from './neon-serverless/index.ts'; -import type { NodePgDatabase } from './node-postgres/index.ts'; -import type { PlanetScaleDatabase } from './planetscale-serverless/index.ts'; -import type { PostgresJsDatabase } from './postgres-js/index.ts'; -import type { SingleStoreDriverDatabase } from './singlestore/driver.ts'; -import type { TiDBServerlessDatabase } from './tidb-serverless/index.ts'; -import type { VercelPgDatabase } from './vercel-postgres/index.ts'; - -export async function migrate( - db: - | AwsDataApiPgDatabase - | BetterSQLite3Database - | BunSQLiteDatabase - | DrizzleD1Database - | LibSQLDatabase - | MySql2Database - | NeonHttpDatabase - | NeonDatabase - | NodePgDatabase - | PlanetScaleDatabase - | PostgresJsDatabase - | VercelPgDatabase - | TiDBServerlessDatabase - | SingleStoreDriverDatabase, - config: - | string - | MigrationConfig, -) { - switch (( db).constructor[entityKind]) { - case 'AwsDataApiPgDatabase': { - const { migrate } = await import('./aws-data-api/pg/migrator'); - - return migrate(db as AwsDataApiPgDatabase, config as string | MigrationConfig); - } - case 'BetterSQLite3Database': { - const { migrate } = await import('./better-sqlite3/migrator'); - - return migrate(db as BetterSQLite3Database, config as string | MigrationConfig); - } - case 'BunSQLiteDatabase': { - const { migrate } = await import('./bun-sqlite/migrator'); - - return migrate(db as BunSQLiteDatabase, config as string | MigrationConfig); - } - case 'D1Database': { - const { migrate } = await import('./d1/migrator'); - - return migrate(db as DrizzleD1Database, config as string | MigrationConfig); - } - case 'LibSQLDatabase': { - const { migrate } = await import('./libsql/migrator'); - - return migrate(db as LibSQLDatabase, config as string | MigrationConfig); - } - case 'MySql2Database': { - const { migrate } = await import('./mysql2/migrator'); - - return migrate(db as MySql2Database, config as string | MigrationConfig); - } - case 'NeonHttpDatabase': { - const { migrate } = await import('./neon-http/migrator'); - - return migrate(db as NeonHttpDatabase, config as string | MigrationConfig); - } - case 'NeonServerlessDatabase': { - const { migrate } = await import('./neon-serverless/migrator'); - - return migrate(db as NeonDatabase, config as string | MigrationConfig); - } - case 'NodePgDatabase': { - const { migrate } = await import('./node-postgres/migrator'); - - return migrate(db as NodePgDatabase, config as string | MigrationConfig); - } - case 'PlanetScaleDatabase': { - const { migrate } = await import('./planetscale-serverless/migrator'); - - return migrate(db as PlanetScaleDatabase, config as string | MigrationConfig); - } - case 'PostgresJsDatabase': { - const { migrate } = await import('./postgres-js/migrator'); - - return migrate(db as PostgresJsDatabase, config as string | MigrationConfig); - } - case 'TiDBServerlessDatabase': { - const { migrate } = await import('./tidb-serverless/migrator'); - - return migrate(db as TiDBServerlessDatabase, config as MigrationConfig); - } - case 'VercelPgDatabase': { - const { migrate } = await import('./vercel-postgres/migrator'); - - return migrate(db as VercelPgDatabase, config as string | MigrationConfig); - } - case 'SingleStoreDriverDatabase': { - const { migrate } = await import('./singlestore/migrator'); - - return migrate(db as SingleStoreDriverDatabase, config as MigrationConfig); - } - } -} diff --git a/drizzle-orm/src/mysql-core/db.ts b/drizzle-orm/src/mysql-core/db.ts index 8934c0edf..8df6ff343 100644 --- a/drizzle-orm/src/mysql-core/db.ts +++ b/drizzle-orm/src/mysql-core/db.ts @@ -3,11 +3,10 @@ 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 { ColumnsSelection, SQL, SQLWrapper } from '~/sql/sql.ts'; +import type { ColumnsSelection, SQLWrapper } from '~/sql/sql.ts'; import { WithSubquery } from '~/subquery.ts'; import type { DrizzleTypeError } from '~/utils.ts'; import type { MySqlDialect } from './dialect.ts'; -import { MySqlCountBuilder } from './query-builders/count.ts'; import { MySqlDeleteBase, MySqlInsertBuilder, @@ -28,7 +27,6 @@ import type { } from './session.ts'; import type { WithSubqueryWithSelection } from './subquery.ts'; import type { MySqlTable } from './table.ts'; -import type { MySqlViewBase } from './view-base.ts'; export class MySqlDatabase< TQueryResult extends MySqlQueryResultHKT, @@ -136,13 +134,6 @@ export class MySqlDatabase< }; } - $count( - source: MySqlTable | MySqlViewBase | SQL | SQLWrapper, - filters?: SQL, - ) { - return new MySqlCountBuilder({ source, filters, session: this.session }); - } - /** * Incorporates a previously defined CTE (using `$with`) into the main query. * diff --git a/drizzle-orm/src/mysql-core/query-builders/count.ts b/drizzle-orm/src/mysql-core/query-builders/count.ts deleted file mode 100644 index 645bb4753..000000000 --- a/drizzle-orm/src/mysql-core/query-builders/count.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { entityKind, sql } from '~/index.ts'; -import type { SQLWrapper } from '~/sql/sql.ts'; -import { SQL } from '~/sql/sql.ts'; -import type { MySqlSession } from '../session.ts'; -import type { MySqlTable } from '../table.ts'; -import type { MySqlViewBase } from '../view-base.ts'; - -export class MySqlCountBuilder< - TSession extends MySqlSession, -> extends SQL implements Promise, SQLWrapper { - private sql: SQL; - - static readonly [entityKind] = 'MySqlCountBuilder'; - [Symbol.toStringTag] = 'MySqlCountBuilder'; - - private session: TSession; - - private static buildEmbeddedCount( - source: MySqlTable | MySqlViewBase | SQL | SQLWrapper, - filters?: SQL, - ): SQL { - return sql`(select count(*) from ${source}${sql.raw(' where ').if(filters)}${filters})`; - } - - private static buildCount( - source: MySqlTable | MySqlViewBase | SQL | SQLWrapper, - filters?: SQL, - ): SQL { - return sql`select count(*) as count from ${source}${sql.raw(' where ').if(filters)}${filters}`; - } - - constructor( - readonly params: { - source: MySqlTable | MySqlViewBase | SQL | SQLWrapper; - filters?: SQL; - session: TSession; - }, - ) { - super(MySqlCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks); - - this.mapWith(Number); - - this.session = params.session; - - this.sql = MySqlCountBuilder.buildCount( - params.source, - params.filters, - ); - } - - then( - onfulfilled?: ((value: number) => TResult1 | PromiseLike) | null | undefined, - onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined, - ): Promise { - return Promise.resolve(this.session.count(this.sql)) - .then( - onfulfilled, - onrejected, - ); - } - - catch( - onRejected?: ((reason: any) => never | PromiseLike) | null | undefined, - ): Promise { - return this.then(undefined, onRejected); - } - - finally(onFinally?: (() => void) | null | undefined): Promise { - return this.then( - (value) => { - onFinally?.(); - return value; - }, - (reason) => { - onFinally?.(); - throw reason; - }, - ); - } -} diff --git a/drizzle-orm/src/mysql-core/session.ts b/drizzle-orm/src/mysql-core/session.ts index 021d4276d..6b6269639 100644 --- a/drizzle-orm/src/mysql-core/session.ts +++ b/drizzle-orm/src/mysql-core/session.ts @@ -86,14 +86,6 @@ export abstract class MySqlSession< abstract all(query: SQL): Promise; - async count(sql: SQL): Promise { - const res = await this.execute<[[{ count: string }]]>(sql); - - return Number( - res[0][0]['count'], - ); - } - abstract transaction( transaction: (tx: MySqlTransaction) => Promise, config?: MySqlTransactionConfig, diff --git a/drizzle-orm/src/mysql-proxy/driver.ts b/drizzle-orm/src/mysql-proxy/driver.ts index dfbf69cc9..574db42c1 100644 --- a/drizzle-orm/src/mysql-proxy/driver.ts +++ b/drizzle-orm/src/mysql-proxy/driver.ts @@ -1,4 +1,3 @@ -import { entityKind } from '~/entity.ts'; import { DefaultLogger } from '~/logger.ts'; import { MySqlDatabase } from '~/mysql-core/db.ts'; import { MySqlDialect } from '~/mysql-core/dialect.ts'; @@ -11,11 +10,9 @@ import { import type { DrizzleConfig } from '~/utils.ts'; import { type MySqlRemotePreparedQueryHKT, type MySqlRemoteQueryResultHKT, MySqlRemoteSession } from './session.ts'; -export class MySqlRemoteDatabase< +export type MySqlRemoteDatabase< TSchema extends Record = Record, -> extends MySqlDatabase { - static readonly [entityKind]: string = 'MySqlRemoteDatabase'; -} +> = MySqlDatabase; export type RemoteCallback = ( sql: string, @@ -49,5 +46,5 @@ export function drizzle = Record; + return new MySqlDatabase(dialect, session, schema, 'default') as MySqlRemoteDatabase; } diff --git a/drizzle-orm/src/mysql2/driver.ts b/drizzle-orm/src/mysql2/driver.ts index a8fb65c3b..3b21bf11d 100644 --- a/drizzle-orm/src/mysql2/driver.ts +++ b/drizzle-orm/src/mysql2/driver.ts @@ -40,11 +40,9 @@ export class MySql2Driver { export { MySqlDatabase } from '~/mysql-core/db.ts'; -export class MySql2Database< +export type MySql2Database< TSchema extends Record = Record, -> extends MySqlDatabase { - static readonly [entityKind]: string = 'MySql2Database'; -} +> = MySqlDatabase; export type MySql2DrizzleConfig = Record> = & Omit, 'schema'> @@ -89,7 +87,7 @@ export function drizzle = Record; + return new MySqlDatabase(dialect, session, schema, mode) as MySql2Database; } interface CallbackClient { diff --git a/drizzle-orm/src/mysql2/migrator.ts b/drizzle-orm/src/mysql2/migrator.ts index ae56e01f1..2f3c9c3dc 100644 --- a/drizzle-orm/src/mysql2/migrator.ts +++ b/drizzle-orm/src/mysql2/migrator.ts @@ -4,15 +4,8 @@ import type { MySql2Database } from './driver.ts'; export async function migrate>( db: MySql2Database, - config: MigrationConfig | string, + config: MigrationConfig, ) { const migrations = readMigrationFiles(config); - - const preparedConfig = typeof config === 'string' - ? { - migrationsFolder: config, - } - : config; - - await db.dialect.migrate(migrations, db.session, preparedConfig); + await db.dialect.migrate(migrations, db.session, config); } diff --git a/drizzle-orm/src/neon-http/session.ts b/drizzle-orm/src/neon-http/session.ts index 4dd768d3e..6d7685116 100644 --- a/drizzle-orm/src/neon-http/session.ts +++ b/drizzle-orm/src/neon-http/session.ts @@ -10,7 +10,7 @@ import type { PgQueryResultHKT, PgTransactionConfig, PreparedQueryConfig } from import { PgPreparedQuery as PgPreparedQuery, PgSession } from '~/pg-core/session.ts'; import type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts'; import type { PreparedQuery } from '~/session.ts'; -import { fillPlaceholders, type Query, type SQL } from '~/sql/sql.ts'; +import { fillPlaceholders, type Query } from '~/sql/sql.ts'; import { mapResultRow } from '~/utils.ts'; export type NeonHttpClient = NeonQueryFunction; @@ -161,14 +161,6 @@ export class NeonHttpSession< return this.client(query, params, { arrayMode: false, fullResults: true }); } - override async count(sql: SQL): Promise { - const res = await this.execute<{ rows: [{ count: string }] }>(sql); - - return Number( - res['rows'][0]['count'], - ); - } - override async transaction( _transaction: (tx: NeonTransaction) => Promise, // eslint-disable-next-line @typescript-eslint/no-unused-vars diff --git a/drizzle-orm/src/neon-serverless/driver.ts b/drizzle-orm/src/neon-serverless/driver.ts index 7f42cfeb3..8a15dd678 100644 --- a/drizzle-orm/src/neon-serverless/driver.ts +++ b/drizzle-orm/src/neon-serverless/driver.ts @@ -43,11 +43,9 @@ export class NeonDriver { } } -export class NeonDatabase< +export type NeonDatabase< TSchema extends Record = Record, -> extends PgDatabase { - static readonly [entityKind]: string = 'NeonServerlessDatabase'; -} +> = PgDatabase; export function drizzle = Record>( client: NeonClient, @@ -76,5 +74,5 @@ export function drizzle = Record; + return new PgDatabase(dialect, session, schema) as NeonDatabase; } diff --git a/drizzle-orm/src/node-postgres/driver.ts b/drizzle-orm/src/node-postgres/driver.ts index 15ac8fc06..4c233f891 100644 --- a/drizzle-orm/src/node-postgres/driver.ts +++ b/drizzle-orm/src/node-postgres/driver.ts @@ -45,11 +45,9 @@ export class NodePgDriver { } } -export class NodePgDatabase< +export type NodePgDatabase< TSchema extends Record = Record, -> extends PgDatabase { - static readonly [entityKind]: string = 'NodePgDatabase'; -} +> = PgDatabase; export function drizzle = Record>( client: NodePgClient, @@ -78,5 +76,5 @@ export function drizzle = Record; + return new PgDatabase(dialect, session, schema) as NodePgDatabase; } diff --git a/drizzle-orm/src/node-postgres/session.ts b/drizzle-orm/src/node-postgres/session.ts index ef6779354..91a21312a 100644 --- a/drizzle-orm/src/node-postgres/session.ts +++ b/drizzle-orm/src/node-postgres/session.ts @@ -8,7 +8,7 @@ import type { SelectedFieldsOrdered } from '~/pg-core/query-builders/select.type import type { PgQueryResultHKT, PgTransactionConfig, PreparedQueryConfig } from '~/pg-core/session.ts'; import { PgPreparedQuery, PgSession } from '~/pg-core/session.ts'; import type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts'; -import { fillPlaceholders, type Query, type SQL, sql } from '~/sql/sql.ts'; +import { fillPlaceholders, type Query, sql } from '~/sql/sql.ts'; import { tracer } from '~/tracing.ts'; import { type Assume, mapResultRow } from '~/utils.ts'; @@ -164,13 +164,6 @@ export class NodePgSession< } } } - - override async count(sql: SQL): Promise { - const res = await this.execute<{ rows: [{ count: string }] }>(sql); - return Number( - res['rows'][0]['count'], - ); - } } export class NodePgTransaction< diff --git a/drizzle-orm/src/op-sqlite/driver.ts b/drizzle-orm/src/op-sqlite/driver.ts index 94ee6e866..24c663abf 100644 --- a/drizzle-orm/src/op-sqlite/driver.ts +++ b/drizzle-orm/src/op-sqlite/driver.ts @@ -1,5 +1,4 @@ import type { OPSQLiteConnection, QueryResult } from '@op-engineering/op-sqlite'; -import { entityKind } from '~/entity.ts'; import { DefaultLogger } from '~/logger.ts'; import { createTableRelationsHelpers, @@ -12,11 +11,9 @@ import { SQLiteAsyncDialect } from '~/sqlite-core/dialect.ts'; import type { DrizzleConfig } from '~/utils.ts'; import { OPSQLiteSession } from './session.ts'; -export class OPSQLiteDatabase< +export type OPSQLiteDatabase< TSchema extends Record = Record, -> extends BaseSQLiteDatabase<'async', QueryResult, TSchema> { - static readonly [entityKind]: string = 'OPSQLiteDatabase'; -} +> = BaseSQLiteDatabase<'async', QueryResult, TSchema>; export function drizzle = Record>( client: OPSQLiteConnection, @@ -44,5 +41,5 @@ export function drizzle = Record; + return new BaseSQLiteDatabase('async', dialect, session, schema) as OPSQLiteDatabase; } diff --git a/drizzle-orm/src/operations.ts b/drizzle-orm/src/operations.ts index 6fb5cbd2e..492bb3f2a 100644 --- a/drizzle-orm/src/operations.ts +++ b/drizzle-orm/src/operations.ts @@ -21,7 +21,6 @@ export type OptionalKeyOnly< : T['_']['generated'] extends object ? T['_']['generated']['type'] extends 'byDefault' ? TKey : never : never; -// TODO: SQL -> SQLWrapper export type SelectedFieldsFlat = Record< string, TColumn | SQL | SQL.Aliased diff --git a/drizzle-orm/src/pg-core/db.ts b/drizzle-orm/src/pg-core/db.ts index 62b64fb8f..4e8d2f354 100644 --- a/drizzle-orm/src/pg-core/db.ts +++ b/drizzle-orm/src/pg-core/db.ts @@ -19,17 +19,15 @@ import type { PgTable } from '~/pg-core/table.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 { ColumnsSelection, SQL, SQLWrapper } from '~/sql/sql.ts'; +import type { ColumnsSelection, SQLWrapper } from '~/sql/sql.ts'; import { WithSubquery } from '~/subquery.ts'; import type { DrizzleTypeError } from '~/utils.ts'; import type { PgColumn } from './columns/index.ts'; -import { PgCountBuilder } from './query-builders/count.ts'; import { RelationalQueryBuilder } from './query-builders/query.ts'; import { PgRaw } from './query-builders/raw.ts'; import { PgRefreshMaterializedView } from './query-builders/refresh-materialized-view.ts'; import type { SelectedFields } from './query-builders/select.types.ts'; import type { WithSubqueryWithSelection } from './subquery.ts'; -import type { PgViewBase } from './view-base.ts'; import type { PgMaterializedView } from './view.ts'; export class PgDatabase< @@ -137,13 +135,6 @@ export class PgDatabase< }; } - $count( - source: PgTable | PgViewBase | SQL | SQLWrapper, - filters?: SQL, - ) { - return new PgCountBuilder({ source, filters, session: this.session }); - } - /** * Incorporates a previously defined CTE (using `$with`) into the main query. * @@ -631,11 +622,7 @@ export const withReplicas = < HKT extends PgQueryResultHKT, TFullSchema extends Record, TSchema extends TablesRelationalConfig, - Q extends PgDatabase< - HKT, - TFullSchema, - TSchema extends Record ? ExtractTablesWithRelations : TSchema - >, + Q extends PgDatabase, >( primary: Q, replicas: [Q, ...Q[]], diff --git a/drizzle-orm/src/pg-core/query-builders/count.ts b/drizzle-orm/src/pg-core/query-builders/count.ts deleted file mode 100644 index c93cbb18d..000000000 --- a/drizzle-orm/src/pg-core/query-builders/count.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { entityKind, sql } from '~/index.ts'; -import type { SQLWrapper } from '~/sql/sql.ts'; -import { SQL } from '~/sql/sql.ts'; -import type { PgSession } from '../session.ts'; -import type { PgTable } from '../table.ts'; - -export class PgCountBuilder< - TSession extends PgSession, -> extends SQL implements Promise, SQLWrapper { - private sql: SQL; - - static readonly [entityKind] = 'PgCountBuilder'; - [Symbol.toStringTag] = 'PgCountBuilder'; - - private session: TSession; - - private static buildEmbeddedCount( - source: PgTable | SQL | SQLWrapper, - filters?: SQL, - ): SQL { - return sql`(select count(*) from ${source}${sql.raw(' where ').if(filters)}${filters})`; - } - - private static buildCount( - source: PgTable | SQL | SQLWrapper, - filters?: SQL, - ): SQL { - return sql`select count(*) as count from ${source}${sql.raw(' where ').if(filters)}${filters};`; - } - - constructor( - readonly params: { - source: PgTable | SQL | SQLWrapper; - filters?: SQL; - session: TSession; - }, - ) { - super(PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks); - - this.mapWith(Number); - - this.session = params.session; - - this.sql = PgCountBuilder.buildCount( - params.source, - params.filters, - ); - } - - then( - onfulfilled?: ((value: number) => TResult1 | PromiseLike) | null | undefined, - onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined, - ): Promise { - return Promise.resolve(this.session.count(this.sql)) - .then( - onfulfilled, - onrejected, - ); - } - - catch( - onRejected?: ((reason: any) => never | PromiseLike) | null | undefined, - ): Promise { - return this.then(undefined, onRejected); - } - - finally(onFinally?: (() => void) | null | undefined): Promise { - return this.then( - (value) => { - onFinally?.(); - return value; - }, - (reason) => { - onFinally?.(); - throw reason; - }, - ); - } -} diff --git a/drizzle-orm/src/pg-core/session.ts b/drizzle-orm/src/pg-core/session.ts index ea820f2d8..434ebc086 100644 --- a/drizzle-orm/src/pg-core/session.ts +++ b/drizzle-orm/src/pg-core/session.ts @@ -86,14 +86,6 @@ export abstract class PgSession< ).all(); } - async count(sql: SQL): Promise { - const res = await this.execute<[{ count: string }]>(sql); - - return Number( - res[0]['count'], - ); - } - abstract transaction( transaction: (tx: PgTransaction) => Promise, config?: PgTransactionConfig, diff --git a/drizzle-orm/src/pg-proxy/driver.ts b/drizzle-orm/src/pg-proxy/driver.ts index d82e86962..cdffa15c1 100644 --- a/drizzle-orm/src/pg-proxy/driver.ts +++ b/drizzle-orm/src/pg-proxy/driver.ts @@ -1,4 +1,3 @@ -import { entityKind } from '~/entity.ts'; import { DefaultLogger } from '~/logger.ts'; import { PgDatabase } from '~/pg-core/db.ts'; import { PgDialect } from '~/pg-core/dialect.ts'; @@ -11,11 +10,9 @@ import { import type { DrizzleConfig } from '~/utils.ts'; import { type PgRemoteQueryResultHKT, PgRemoteSession } from './session.ts'; -export class PgRemoteDatabase< +export type PgRemoteDatabase< TSchema extends Record = Record, -> extends PgDatabase { - static readonly [entityKind]: string = 'PgRemoteDatabase'; -} +> = PgDatabase; export type RemoteCallback = ( sql: string, @@ -51,5 +48,5 @@ export function drizzle = Record; + return new PgDatabase(dialect, session, schema) as PgRemoteDatabase; } diff --git a/drizzle-orm/src/pg-proxy/session.ts b/drizzle-orm/src/pg-proxy/session.ts index 1a30c0a3c..eb6a1b1a3 100644 --- a/drizzle-orm/src/pg-proxy/session.ts +++ b/drizzle-orm/src/pg-proxy/session.ts @@ -130,8 +130,7 @@ export class PreparedQuery extends PreparedQueryB }); } - async all() { - } + async all() {} /** @internal */ isResponseInArrayMode(): boolean { diff --git a/drizzle-orm/src/pglite/driver.ts b/drizzle-orm/src/pglite/driver.ts index a801005d8..7de2ce110 100644 --- a/drizzle-orm/src/pglite/driver.ts +++ b/drizzle-orm/src/pglite/driver.ts @@ -34,11 +34,9 @@ export class PgliteDriver { } } -export class PgliteDatabase< +export type PgliteDatabase< TSchema extends Record = Record, -> extends PgDatabase { - static readonly [entityKind]: string = 'PgliteDatabase'; -} +> = PgDatabase; export function drizzle = Record>( client: PgliteClient, @@ -67,5 +65,5 @@ export function drizzle = Record; + return new PgDatabase(dialect, session, schema) as PgliteDatabase; } diff --git a/drizzle-orm/src/pglite/session.ts b/drizzle-orm/src/pglite/session.ts index ebf7701a6..c7a1dbb5d 100644 --- a/drizzle-orm/src/pglite/session.ts +++ b/drizzle-orm/src/pglite/session.ts @@ -7,7 +7,7 @@ import type { SelectedFieldsOrdered } from '~/pg-core/query-builders/select.type import type { PgQueryResultHKT, PgTransactionConfig, PreparedQueryConfig } from '~/pg-core/session.ts'; import { PgPreparedQuery, PgSession } from '~/pg-core/session.ts'; import type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts'; -import { fillPlaceholders, type Query, type SQL, sql } from '~/sql/sql.ts'; +import { fillPlaceholders, type Query, sql } from '~/sql/sql.ts'; import { type Assume, mapResultRow } from '~/utils.ts'; import { types } from '@electric-sql/pglite'; @@ -140,13 +140,6 @@ export class PgliteSession< return transaction(tx); }) as Promise; } - - override async count(sql: SQL): Promise { - const res = await this.execute<{ rows: [{ count: string }] }>(sql); - return Number( - res['rows'][0]['count'], - ); - } } export class PgliteTransaction< diff --git a/drizzle-orm/src/planetscale-serverless/driver.ts b/drizzle-orm/src/planetscale-serverless/driver.ts index fd1327bbc..b1d2d6e6f 100644 --- a/drizzle-orm/src/planetscale-serverless/driver.ts +++ b/drizzle-orm/src/planetscale-serverless/driver.ts @@ -1,6 +1,5 @@ import type { Connection } from '@planetscale/database'; import { Client } from '@planetscale/database'; -import { entityKind } from '~/entity.ts'; import type { Logger } from '~/logger.ts'; import { DefaultLogger } from '~/logger.ts'; import { MySqlDatabase } from '~/mysql-core/db.ts'; @@ -19,11 +18,9 @@ export interface PlanetscaleSDriverOptions { logger?: Logger; } -export class PlanetScaleDatabase< +export type PlanetScaleDatabase< TSchema extends Record = Record, -> extends MySqlDatabase { - static readonly [entityKind]: string = 'PlanetScaleDatabase'; -} +> = MySqlDatabase; export function drizzle = Record>( client: Client | Connection, @@ -85,5 +82,5 @@ Starting from version 0.30.0, you will encounter an error if you attempt to use } const session = new PlanetscaleSession(client, dialect, undefined, schema, { logger }); - return new PlanetScaleDatabase(dialect, session, schema as any, 'planetscale') as PlanetScaleDatabase; + return new MySqlDatabase(dialect, session, schema, 'planetscale') as PlanetScaleDatabase; } diff --git a/drizzle-orm/src/planetscale-serverless/migrator.ts b/drizzle-orm/src/planetscale-serverless/migrator.ts index 8b3713602..5a668ae01 100644 --- a/drizzle-orm/src/planetscale-serverless/migrator.ts +++ b/drizzle-orm/src/planetscale-serverless/migrator.ts @@ -4,15 +4,8 @@ import type { PlanetScaleDatabase } from './driver.ts'; export async function migrate>( db: PlanetScaleDatabase, - config: MigrationConfig | string, + config: MigrationConfig, ) { const migrations = readMigrationFiles(config); - - const preparedConfig = typeof config === 'string' - ? { - migrationsFolder: config, - } - : config; - - await db.dialect.migrate(migrations, db.session, preparedConfig); + await db.dialect.migrate(migrations, db.session, config); } diff --git a/drizzle-orm/src/planetscale-serverless/session.ts b/drizzle-orm/src/planetscale-serverless/session.ts index 987529d7c..f2275b7f2 100644 --- a/drizzle-orm/src/planetscale-serverless/session.ts +++ b/drizzle-orm/src/planetscale-serverless/session.ts @@ -164,14 +164,6 @@ export class PlanetscaleSession< ) => eQuery.rows as T[]); } - override async count(sql: SQL): Promise { - const res = await this.execute<{ rows: [{ count: string }] }>(sql); - - return Number( - res['rows'][0]['count'], - ); - } - override transaction( transaction: (tx: PlanetScaleTransaction) => Promise, ): Promise { diff --git a/drizzle-orm/src/postgres-js/driver.ts b/drizzle-orm/src/postgres-js/driver.ts index 6714cff8d..7f44344e8 100644 --- a/drizzle-orm/src/postgres-js/driver.ts +++ b/drizzle-orm/src/postgres-js/driver.ts @@ -1,5 +1,4 @@ import type { Sql } from 'postgres'; -import { entityKind } from '~/entity.ts'; import { DefaultLogger } from '~/logger.ts'; import { PgDatabase } from '~/pg-core/db.ts'; import { PgDialect } from '~/pg-core/dialect.ts'; @@ -13,11 +12,9 @@ import type { DrizzleConfig } from '~/utils.ts'; import type { PostgresJsQueryResultHKT } from './session.ts'; import { PostgresJsSession } from './session.ts'; -export class PostgresJsDatabase< +export type PostgresJsDatabase< TSchema extends Record = Record, -> extends PgDatabase { - static readonly [entityKind]: string = 'PostgresJsDatabase'; -} +> = PgDatabase; export function drizzle = Record>( client: Sql, @@ -55,5 +52,5 @@ export function drizzle = Record; + return new PgDatabase(dialect, session, schema) as PostgresJsDatabase; } diff --git a/drizzle-orm/src/sqlite-core/db.ts b/drizzle-orm/src/sqlite-core/db.ts index 7ae2736e0..65f807d08 100644 --- a/drizzle-orm/src/sqlite-core/db.ts +++ b/drizzle-orm/src/sqlite-core/db.ts @@ -2,7 +2,7 @@ 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 { ColumnsSelection, SQL, SQLWrapper } from '~/sql/sql.ts'; +import type { ColumnsSelection, SQLWrapper } from '~/sql/sql.ts'; import type { SQLiteAsyncDialect, SQLiteSyncDialect } from '~/sqlite-core/dialect.ts'; import { QueryBuilder, @@ -21,12 +21,10 @@ import type { import type { SQLiteTable } from '~/sqlite-core/table.ts'; import { WithSubquery } from '~/subquery.ts'; import type { DrizzleTypeError } from '~/utils.ts'; -import { SQLiteCountBuilder } from './query-builders/count.ts'; import { RelationalQueryBuilder } from './query-builders/query.ts'; import { SQLiteRaw } from './query-builders/raw.ts'; import type { SelectedFields } from './query-builders/select.types.ts'; import type { WithSubqueryWithSelection } from './subquery.ts'; -import type { SQLiteViewBase } from './view-base.ts'; export class BaseSQLiteDatabase< TResultKind extends 'sync' | 'async', @@ -136,13 +134,6 @@ export class BaseSQLiteDatabase< }; } - $count( - source: SQLiteTable | SQLiteViewBase | SQL | SQLWrapper, - filters?: SQL, - ) { - return new SQLiteCountBuilder({ source, filters, session: this.session }); - } - /** * Incorporates a previously defined CTE (using `$with`) into the main query. * diff --git a/drizzle-orm/src/sqlite-core/query-builders/count.ts b/drizzle-orm/src/sqlite-core/query-builders/count.ts deleted file mode 100644 index 1b19eed07..000000000 --- a/drizzle-orm/src/sqlite-core/query-builders/count.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { entityKind, sql } from '~/index.ts'; -import type { SQLWrapper } from '~/sql/sql.ts'; -import { SQL } from '~/sql/sql.ts'; -import type { SQLiteSession } from '../session.ts'; -import type { SQLiteTable } from '../table.ts'; -import type { SQLiteView } from '../view.ts'; - -export class SQLiteCountBuilder< - TSession extends SQLiteSession, -> extends SQL implements Promise, SQLWrapper { - private sql: SQL; - - static readonly [entityKind] = 'SQLiteCountBuilderAsync'; - [Symbol.toStringTag] = 'SQLiteCountBuilderAsync'; - - private session: TSession; - - private static buildEmbeddedCount( - source: SQLiteTable | SQLiteView | SQL | SQLWrapper, - filters?: SQL, - ): SQL { - return sql`(select count(*) from ${source}${sql.raw(' where ').if(filters)}${filters})`; - } - - private static buildCount( - source: SQLiteTable | SQLiteView | SQL | SQLWrapper, - filters?: SQL, - ): SQL { - return sql`select count(*) from ${source}${sql.raw(' where ').if(filters)}${filters}`; - } - - constructor( - readonly params: { - source: SQLiteTable | SQLiteView | SQL | SQLWrapper; - filters?: SQL; - session: TSession; - }, - ) { - super(SQLiteCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks); - - this.session = params.session; - - this.sql = SQLiteCountBuilder.buildCount( - params.source, - params.filters, - ); - } - - then( - onfulfilled?: ((value: number) => TResult1 | PromiseLike) | null | undefined, - onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined, - ): Promise { - return Promise.resolve(this.session.count(this.sql)).then( - onfulfilled, - onrejected, - ); - } - - catch( - onRejected?: ((reason: any) => never | PromiseLike) | null | undefined, - ): Promise { - return this.then(undefined, onRejected); - } - - finally(onFinally?: (() => void) | null | undefined): Promise { - return this.then( - (value) => { - onFinally?.(); - return value; - }, - (reason) => { - onFinally?.(); - throw reason; - }, - ); - } -} diff --git a/drizzle-orm/src/sqlite-core/session.ts b/drizzle-orm/src/sqlite-core/session.ts index d291b6fdf..4ac987b4a 100644 --- a/drizzle-orm/src/sqlite-core/session.ts +++ b/drizzle-orm/src/sqlite-core/session.ts @@ -187,12 +187,6 @@ export abstract class SQLiteSession< >; } - async count(sql: SQL) { - const result = await this.values(sql) as [[number]]; - - return result[0][0]; - } - /** @internal */ extractRawValuesValueFromBatchResult(_result: unknown): unknown { throw new Error('Not implemented'); diff --git a/drizzle-orm/src/tidb-serverless/driver.ts b/drizzle-orm/src/tidb-serverless/driver.ts index b762bd889..bdd5324db 100644 --- a/drizzle-orm/src/tidb-serverless/driver.ts +++ b/drizzle-orm/src/tidb-serverless/driver.ts @@ -1,5 +1,4 @@ import type { Connection } from '@tidbcloud/serverless'; -import { entityKind } from '~/entity.ts'; import type { Logger } from '~/logger.ts'; import { DefaultLogger } from '~/logger.ts'; import { MySqlDatabase } from '~/mysql-core/db.ts'; @@ -18,11 +17,9 @@ export interface TiDBServerlessSDriverOptions { logger?: Logger; } -export class TiDBServerlessDatabase< +export type TiDBServerlessDatabase< TSchema extends Record = Record, -> extends MySqlDatabase { - static readonly [entityKind]: string = 'TiDBServerlessDatabase'; -} +> = MySqlDatabase; export function drizzle = Record>( client: Connection, @@ -50,5 +47,5 @@ export function drizzle = Record; + return new MySqlDatabase(dialect, session, schema, 'default') as TiDBServerlessDatabase; } diff --git a/drizzle-orm/src/tidb-serverless/session.ts b/drizzle-orm/src/tidb-serverless/session.ts index b01b9f948..64a8d61d7 100644 --- a/drizzle-orm/src/tidb-serverless/session.ts +++ b/drizzle-orm/src/tidb-serverless/session.ts @@ -139,14 +139,6 @@ export class TiDBServerlessSession< return this.client.execute(querySql.sql, querySql.params) as Promise; } - override async count(sql: SQL): Promise { - const res = await this.execute<{ rows: [{ count: string }] }>(sql); - - return Number( - res['rows'][0]['count'], - ); - } - override async transaction( transaction: (tx: TiDBServerlessTransaction) => Promise, ): Promise { diff --git a/drizzle-orm/src/vercel-postgres/driver.ts b/drizzle-orm/src/vercel-postgres/driver.ts index bc990d0b3..07e73c732 100644 --- a/drizzle-orm/src/vercel-postgres/driver.ts +++ b/drizzle-orm/src/vercel-postgres/driver.ts @@ -42,11 +42,9 @@ export class VercelPgDriver { } } -export class VercelPgDatabase< +export type VercelPgDatabase< TSchema extends Record = Record, -> extends PgDatabase { - static readonly [entityKind]: string = 'VercelPgDatabase'; -} +> = PgDatabase; export function drizzle = Record>( client: VercelPgClient, @@ -75,5 +73,5 @@ export function drizzle = Record; + return new PgDatabase(dialect, session, schema) as VercelPgDatabase; } diff --git a/drizzle-orm/src/version.ts b/drizzle-orm/src/version.ts index d670a0575..0c11937c8 100644 --- a/drizzle-orm/src/version.ts +++ b/drizzle-orm/src/version.ts @@ -1,4 +1,4 @@ // @ts-ignore - imported using Rollup json plugin export { version as npmVersion } from '../package.json'; // In version 7, we changed the PostgreSQL indexes API -export const compatibilityVersion = 8; +export const compatibilityVersion = 7; diff --git a/drizzle-orm/type-tests/mysql/count.ts b/drizzle-orm/type-tests/mysql/count.ts deleted file mode 100644 index d9b9ba9ff..000000000 --- a/drizzle-orm/type-tests/mysql/count.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { Expect } from 'type-tests/utils.ts'; -import { and, gt, ne } from '~/expressions.ts'; -import { int, mysqlTable, serial, text } from '~/mysql-core/index.ts'; -import type { Equal } from '~/utils.ts'; -import { db } from './db.ts'; - -const names = mysqlTable('names', { - id: serial('id').primaryKey(), - name: text('name'), - authorId: int('author_id'), -}); - -const separate = await db.$count(names); - -const separateFilters = await db.$count(names, and(gt(names.id, 1), ne(names.name, 'forbidden'))); - -const embedded = await db - .select({ - id: names.id, - name: names.name, - authorId: names.authorId, - count1: db.$count(names).as('count1'), - }) - .from(names); - -const embeddedFilters = await db - .select({ - id: names.id, - name: names.name, - authorId: names.authorId, - count1: db.$count(names, and(gt(names.id, 1), ne(names.name, 'forbidden'))).as('count1'), - }) - .from(names); - -Expect>; - -Expect>; - -Expect< - Equal< - { - id: number; - name: string | null; - authorId: number | null; - count1: number; - }[], - typeof embedded - > ->; - -Expect< - Equal< - { - id: number; - name: string | null; - authorId: number | null; - count1: number; - }[], - typeof embeddedFilters - > ->; diff --git a/drizzle-orm/type-tests/pg/count.ts b/drizzle-orm/type-tests/pg/count.ts deleted file mode 100644 index 9ed5eeaf9..000000000 --- a/drizzle-orm/type-tests/pg/count.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { Expect } from 'type-tests/utils.ts'; -import { and, gt, ne } from '~/expressions.ts'; -import { integer, pgTable, serial, text } from '~/pg-core/index.ts'; -import type { Equal } from '~/utils.ts'; -import { db } from './db.ts'; - -const names = pgTable('names', { - id: serial('id').primaryKey(), - name: text('name'), - authorId: integer('author_id'), -}); - -const separate = await db.$count(names); - -const separateFilters = await db.$count(names, and(gt(names.id, 1), ne(names.name, 'forbidden'))); - -const embedded = await db - .select({ - id: names.id, - name: names.name, - authorId: names.authorId, - count1: db.$count(names).as('count1'), - }) - .from(names); - -const embeddedFilters = await db - .select({ - id: names.id, - name: names.name, - authorId: names.authorId, - count1: db.$count(names, and(gt(names.id, 1), ne(names.name, 'forbidden'))).as('count1'), - }) - .from(names); - -Expect>; - -Expect>; - -Expect< - Equal< - { - id: number; - name: string | null; - authorId: number | null; - count1: number; - }[], - typeof embedded - > ->; - -Expect< - Equal< - { - id: number; - name: string | null; - authorId: number | null; - count1: number; - }[], - typeof embeddedFilters - > ->; diff --git a/drizzle-orm/type-tests/sqlite/count.ts b/drizzle-orm/type-tests/sqlite/count.ts deleted file mode 100644 index 04350f000..000000000 --- a/drizzle-orm/type-tests/sqlite/count.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { Expect } from 'type-tests/utils.ts'; -import { and, gt, ne } from '~/expressions.ts'; -import { integer, sqliteTable, text } from '~/sqlite-core/index.ts'; -import type { Equal } from '~/utils.ts'; -import { db } from './db.ts'; - -const names = sqliteTable('names', { - id: integer('id').primaryKey(), - name: text('name'), - authorId: integer('author_id'), -}); - -const separate = await db.$count(names); - -const separateFilters = await db.$count(names, and(gt(names.id, 1), ne(names.name, 'forbidden'))); - -const embedded = await db - .select({ - id: names.id, - name: names.name, - authorId: names.authorId, - count1: db.$count(names).as('count1'), - }) - .from(names); - -const embeddedFilters = await db - .select({ - id: names.id, - name: names.name, - authorId: names.authorId, - count1: db.$count(names, and(gt(names.id, 1), ne(names.name, 'forbidden'))).as('count1'), - }) - .from(names); - -Expect>; - -Expect>; - -Expect< - Equal< - { - id: number; - name: string | null; - authorId: number | null; - count1: number; - }[], - typeof embedded - > ->; - -Expect< - Equal< - { - id: number; - name: string | null; - authorId: number | null; - count1: number; - }[], - typeof embeddedFilters - > ->;