Skip to content

Commit

Permalink
Remove instanceof checks to fix usage in monorepos
Browse files Browse the repository at this point in the history
  • Loading branch information
dankochetov committed Jun 6, 2023
1 parent 1f8ff17 commit 92a27ec
Show file tree
Hide file tree
Showing 180 changed files with 2,474 additions and 1,262 deletions.
7 changes: 7 additions & 0 deletions .eslintrc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@ extends:
- 'plugin:@typescript-eslint/recommended'
- 'plugin:unicorn/recommended'
parser: '@typescript-eslint/parser'
parserOptions:
project: './tsconfig.json'
plugins:
- import
- unused-imports
- no-instanceof
- drizzle
rules:
'@typescript-eslint/consistent-type-imports':
- error
Expand Down Expand Up @@ -55,3 +59,6 @@ rules:
'unicorn/prefer-type-error': 'off'
'unicorn/relative-url-style': 'off'
'eqeqeq': 'error'
'no-instanceof/no-instanceof': 'error'
'drizzle/require-entity-kind': 'error'
'unicorn/prefer-string-replace-all': 'off'
12 changes: 6 additions & 6 deletions drizzle-orm/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,10 @@
}
},
"devDependencies": {
"@aws-sdk/client-rds-data": "^3.341.0",
"@aws-sdk/client-rds-data": "^3.344.0",
"@cloudflare/workers-types": "^4.20230518.0",
"@libsql/client": "^0.1.6",
"@neondatabase/serverless": "^0.4.8",
"@neondatabase/serverless": "^0.4.9",
"@opentelemetry/api": "^1.4.1",
"@originjs/vite-plugin-commonjs": "^1.0.3",
"@planetscale/database": "^1.7.0",
Expand All @@ -139,21 +139,21 @@
"@types/sql.js": "^1.4.4",
"@vercel/postgres": "^0.3.0",
"better-sqlite3": "^8.4.0",
"bun-types": "^0.6.4",
"concurrently": "^8.0.1",
"bun-types": "^0.6.6",
"concurrently": "^8.1.0",
"knex": "^2.4.2",
"kysely": "^0.25.0",
"mysql2": "^3.3.3",
"pg": "^8.11.0",
"postgres": "^3.3.3",
"postgres": "^3.3.5",
"rollup": "^3.23.0",
"rollup-plugin-dts": "^5.3.0",
"sql.js": "^1.8.0",
"sqlite3": "^5.1.2",
"tslib": "^2.5.2",
"tsx": "^3.12.7",
"vite-tsconfig-paths": "^4.2.0",
"vitest": "^0.31.1",
"vitest": "^0.31.4",
"zod": "^3.20.2",
"zx": "^7.2.2"
}
Expand Down
4 changes: 3 additions & 1 deletion drizzle-orm/scripts/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ resolve-tspaths --out dist-dts &&
rollup --config rollup.dts.config.ts --configPlugin typescript`,
name: 'dts',
},
]).result;
], {
killOthers: 'failure',
}).result.catch(() => process.exit(1));
fs.copySync('../README.md', 'dist.new/README.md');
updateAndCopyPackageJson();
fs.removeSync('dist');
Expand Down
17 changes: 12 additions & 5 deletions drizzle-orm/src/alias.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import type { AnyColumn } from './column';
import { Column } from './column';
import { entityKind, is } from './entity';
import type { Relation } from './relations';
import { SQL, sql } from './sql';
import { Table } from './table';
import { type View, ViewBaseConfig } from './view';

export class ColumnAliasProxyHandler<TColumn extends AnyColumn> implements ProxyHandler<TColumn> {
static readonly [entityKind]: string = 'ColumnAliasProxyHandler';

constructor(private table: Table | View) {}

get(columnObj: TColumn, prop: string | symbol): any {
Expand All @@ -18,6 +21,8 @@ export class ColumnAliasProxyHandler<TColumn extends AnyColumn> implements Proxy
}

export class TableAliasProxyHandler<T extends Table | View> implements ProxyHandler<T> {
static readonly [entityKind]: string = 'TableAliasProxyHandler';

constructor(private alias: string, private replaceOriginalName: boolean) {}

get(target: T, prop: string | symbol): any {
Expand Down Expand Up @@ -60,15 +65,17 @@ export class TableAliasProxyHandler<T extends Table | View> implements ProxyHand
}

const value = target[prop as keyof typeof target];
if (value instanceof Column) {
return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
if (is(value, Column)) {
return new Proxy(value as AnyColumn, new ColumnAliasProxyHandler(new Proxy(target, this)));
}

return value;
}
}

export class RelationTableAliasProxyHandler<T extends Relation> implements ProxyHandler<T> {
static readonly [entityKind]: string = 'RelationTableAliasProxyHandler';

constructor(private alias: string) {}

get(target: T, prop: string | symbol): any {
Expand Down Expand Up @@ -101,13 +108,13 @@ export function mapColumnsInAliasedSQLToAlias(query: SQL.Aliased, alias: string)

export function mapColumnsInSQLToAlias(query: SQL, alias: string): SQL {
return sql.fromList(query.queryChunks.map((c) => {
if (c instanceof Column) {
if (is(c, Column)) {
return aliasedTableColumn(c, alias);
}
if (c instanceof SQL) {
if (is(c, SQL)) {
return mapColumnsInSQLToAlias(c, alias);
}
if (c instanceof SQL.Aliased) {
if (is(c, SQL.Aliased)) {
return mapColumnsInAliasedSQLToAlias(c, alias);
}
return c;
Expand Down
2 changes: 1 addition & 1 deletion drizzle-orm/src/aws-data-api/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export function toValueParam(value: any, typings?: QueryTypingsValue): { value:
response.value = { doubleValue: value };
} else if (typeof value === 'boolean') {
response.value = { booleanValue: value };
} else if (value instanceof Date) {
} else if (value instanceof Date) { // eslint-disable-line no-instanceof/no-instanceof
response.value = { stringValue: value.toISOString().replace('T', ' ').replace('Z', '') };
} else {
throw new Error(`Unknown type for ${value}`);
Expand Down
3 changes: 3 additions & 0 deletions drizzle-orm/src/aws-data-api/pg/driver.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { entityKind } from '~/entity';
import type { Logger } from '~/logger';
import { DefaultLogger } from '~/logger';
import { PgDatabase } from '~/pg-core/db';
Expand Down Expand Up @@ -32,6 +33,8 @@ export type AwsDataApiPgDatabase<
> = PgDatabase<AwsDataApiPgQueryResultHKT, TSchema>;

export class AwsPgDialect extends PgDialect {
static readonly [entityKind]: string = 'AwsPgDialect';

override escapeParam(num: number): string {
return `:${num + 1}`;
}
Expand Down
7 changes: 7 additions & 0 deletions drizzle-orm/src/aws-data-api/pg/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
ExecuteStatementCommand,
RollbackTransactionCommand,
} from '@aws-sdk/client-rds-data';
import { entityKind } from '~/entity';
import type { Logger } from '~/logger';
import {
type PgDialect,
Expand All @@ -24,6 +25,8 @@ import { getValueFromDataApi, toValueParam } from '../common';
export type AwsDataApiClient = RDSDataClient;

export class AwsDataApiPreparedQuery<T extends PreparedQueryConfig> extends PreparedQuery<T> {
static readonly [entityKind]: string = 'AwsDataApiPreparedQuery';

private rawQuery: ExecuteStatementCommand;

constructor(
Expand Down Expand Up @@ -105,6 +108,8 @@ export class AwsDataApiSession<
TFullSchema extends Record<string, unknown>,
TSchema extends TablesRelationalConfig,
> extends PgSession<AwsDataApiPgQueryResultHKT, TFullSchema, TSchema> {
static readonly [entityKind]: string = 'AwsDataApiSession';

/** @internal */
readonly rawQuery: AwsDataApiQueryBase;

Expand Down Expand Up @@ -176,6 +181,8 @@ export class AwsDataApiTransaction<
TFullSchema extends Record<string, unknown>,
TSchema extends TablesRelationalConfig,
> extends PgTransaction<AwsDataApiPgQueryResultHKT, TFullSchema, TSchema> {
static readonly [entityKind]: string = 'AwsDataApiTransaction';

override transaction<T>(transaction: (tx: AwsDataApiTransaction<TFullSchema, TSchema>) => Promise<T>): Promise<T> {
const savepointName = `sp${this.nestedIndex + 1}`;
const tx = new AwsDataApiTransaction(this.dialect, this.session, this.schema, this.nestedIndex + 1);
Expand Down
7 changes: 7 additions & 0 deletions drizzle-orm/src/better-sqlite3/session.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Database, RunResult, Statement } from 'better-sqlite3';
import { entityKind } from '~/entity';
import type { Logger } from '~/logger';
import { NoopLogger } from '~/logger';
import { type RelationalSchemaConfig, type TablesRelationalConfig } from '~/relations';
Expand All @@ -20,6 +21,8 @@ export class BetterSQLiteSession<
TFullSchema extends Record<string, unknown>,
TSchema extends TablesRelationalConfig,
> extends SQLiteSession<'sync', RunResult, TFullSchema, TSchema> {
static readonly [entityKind]: string = 'BetterSQLiteSession';

private logger: Logger;

constructor(
Expand Down Expand Up @@ -55,6 +58,8 @@ export class BetterSQLiteTransaction<
TFullSchema extends Record<string, unknown>,
TSchema extends TablesRelationalConfig,
> extends SQLiteTransaction<'sync', RunResult, TFullSchema, TSchema> {
static readonly [entityKind]: string = 'BetterSQLiteTransaction';

override transaction<T>(transaction: (tx: BetterSQLiteTransaction<TFullSchema, TSchema>) => T): T {
const savepointName = `sp${this.nestedIndex}`;
const tx = new BetterSQLiteTransaction('sync', this.dialect, this.session, this.schema, this.nestedIndex + 1);
Expand All @@ -73,6 +78,8 @@ export class BetterSQLiteTransaction<
export class PreparedQuery<T extends PreparedQueryConfig = PreparedQueryConfig> extends PreparedQueryBase<
{ type: 'sync'; run: RunResult; all: T['all']; get: T['get']; values: T['values'] }
> {
static readonly [entityKind]: string = 'BetterSQLitePreparedQuery';

constructor(
private stmt: Statement,
private queryString: string,
Expand Down
7 changes: 7 additions & 0 deletions drizzle-orm/src/bun-sqlite/session.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/// <reference types="bun-types" />

import type { Database, Statement as BunStatement } from 'bun:sqlite';
import { entityKind } from '~/entity';
import type { Logger } from '~/logger';
import { NoopLogger } from '~/logger';
import { type RelationalSchemaConfig, type TablesRelationalConfig } from '~/relations';
Expand All @@ -23,6 +24,8 @@ export class SQLiteBunSession<
TFullSchema extends Record<string, unknown>,
TSchema extends TablesRelationalConfig,
> extends SQLiteSession<'sync', void, TFullSchema, TSchema> {
static readonly [entityKind]: string = 'SQLiteBunSession';

private logger: Logger;

constructor(
Expand Down Expand Up @@ -66,6 +69,8 @@ export class SQLiteBunTransaction<
TFullSchema extends Record<string, unknown>,
TSchema extends TablesRelationalConfig,
> extends SQLiteTransaction<'sync', void, TFullSchema, TSchema> {
static readonly [entityKind]: string = 'SQLiteBunTransaction';

override transaction<T>(transaction: (tx: SQLiteBunTransaction<TFullSchema, TSchema>) => T): T {
const savepointName = `sp${this.nestedIndex}`;
const tx = new SQLiteBunTransaction('sync', this.dialect, this.session, this.schema, this.nestedIndex + 1);
Expand All @@ -84,6 +89,8 @@ export class SQLiteBunTransaction<
export class PreparedQuery<T extends PreparedQueryConfig = PreparedQueryConfig> extends PreparedQueryBase<
{ type: 'sync'; run: void; all: T['all']; get: T['get']; values: T['values'] }
> {
static readonly [entityKind]: string = 'SQLiteBunPreparedQuery';

constructor(
private stmt: Statement,
private queryString: string,
Expand Down
29 changes: 19 additions & 10 deletions drizzle-orm/src/column-builder.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { entityKind } from '~/entity';
import type { AnyColumn, ColumnHKTBase, ColumnKind } from './column';
import type { SQL } from './sql';
import type { Assume, Simplify, Update } from './utils';
import { type Assume, type SimplifyShallow, type Update } from './utils';

export interface ColumnBuilderBaseConfig {
name: string;
Expand All @@ -13,7 +14,7 @@ export interface ColumnBuilderBaseConfig {
export type ColumnBuilderConfig<
TInitial extends Partial<ColumnBuilderBaseConfig> = {},
TDefaults extends Partial<ColumnBuilderBaseConfig> = {},
> = Simplify<
> = SimplifyShallow<
Required<
Update<
ColumnBuilderBaseConfig & {
Expand All @@ -28,7 +29,7 @@ export type ColumnBuilderConfig<
>
>;

export type MakeColumnConfig<T extends ColumnBuilderBaseConfig, TTableName extends string> = Simplify<
export type MakeColumnConfig<T extends ColumnBuilderBaseConfig, TTableName extends string> = SimplifyShallow<
Pick<T, keyof ColumnBuilderBaseConfig> & { tableName: TTableName }
>;

Expand Down Expand Up @@ -64,6 +65,8 @@ export abstract class ColumnBuilder<
TRuntimeConfig extends object = {},
TTypeConfig extends object = {},
> {
static readonly [entityKind]: string = 'ColumnBuilder';

declare _: {
brand: 'ColumnBuilder';
config: T;
Expand Down Expand Up @@ -124,18 +127,24 @@ export type BuildColumn<
> = Assume<
ColumnKind<
Assume<TBuilder['_']['columnHKT'], ColumnHKTBase>,
Simplify<{ tableName: TTableName } & TBuilder['_']['config']>
SimplifyShallow<{ tableName: TTableName } & TBuilder['_']['config']>
>,
AnyColumn
>;

export type BuildColumns<TTableName extends string, TConfigMap extends Record<string, AnyColumnBuilder>> = Simplify<
{
[Key in keyof TConfigMap]: BuildColumn<TTableName, TConfigMap[Key]>;
}
>;
export type BuildColumns<TTableName extends string, TConfigMap extends Record<string, AnyColumnBuilder>> =
SimplifyShallow<
{
[Key in keyof TConfigMap]: BuildColumn<TTableName, TConfigMap[Key]>;
}
>;

// export type ChangeColumnTableName<TColumn extends AnyColumn, TAlias extends string> = ColumnKind<
// TColumn['_']['hkt'],
// SimplifyShallow<Update<TColumn['_']['config'], { tableName: TAlias }>>
// >;

export type ChangeColumnTableName<TColumn extends AnyColumn, TAlias extends string> = ColumnKind<
TColumn['_']['hkt'],
Simplify<Update<TColumn['_']['config'], { tableName: TAlias }>>
SimplifyShallow<Update<TColumn['_']['config'], { tableName: TAlias }>>
>;
13 changes: 8 additions & 5 deletions drizzle-orm/src/column.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { ColumnBuilderBaseConfig, ColumnBuilderConfig, ColumnBuilderRuntimeConfig } from './column-builder';
import { entityKind } from './entity';
import type { DriverValueMapper, SQL } from './sql';
import type { Table } from './table';
import type { Assume, Update } from './utils';
import { type Assume, type Update } from './utils';

export interface ColumnBaseConfig extends ColumnBuilderBaseConfig {
tableName: string;
Expand Down Expand Up @@ -31,11 +32,13 @@ export interface ColumnHKT extends ColumnHKTBase {
See `GetColumnData` for example usage of inferring.
*/
export abstract class Column<
THKT extends ColumnHKTBase,
T extends ColumnBaseConfig,
TRuntimeConfig extends object = {},
TTypeConfig extends object = {},
THKT extends ColumnHKT = ColumnHKT,
T extends ColumnBaseConfig = ColumnBaseConfig,
TRuntimeConfig extends object = object,
TTypeConfig extends object = object,
> implements DriverValueMapper<T['data'], T['driverParam']> {
static readonly [entityKind]: string = 'Column';

declare _: {
hkt: THKT;
brand: 'Column';
Expand Down
7 changes: 7 additions & 0 deletions drizzle-orm/src/d1/session.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/// <reference types="@cloudflare/workers-types" />

import { entityKind } from '~/entity';
import type { Logger } from '~/logger';
import { NoopLogger } from '~/logger';
import { type RelationalSchemaConfig, type TablesRelationalConfig } from '~/relations';
Expand All @@ -25,6 +26,8 @@ export class SQLiteD1Session<
TFullSchema extends Record<string, unknown>,
TSchema extends TablesRelationalConfig,
> extends SQLiteSession<'async', D1Result, TFullSchema, TSchema> {
static readonly [entityKind]: string = 'SQLiteD1Session';

private logger: Logger;

constructor(
Expand Down Expand Up @@ -67,6 +70,8 @@ export class D1Transaction<
TFullSchema extends Record<string, unknown>,
TSchema extends TablesRelationalConfig,
> extends SQLiteTransaction<'async', D1Result, TFullSchema, TSchema> {
static readonly [entityKind]: string = 'D1Transaction';

override async transaction<T>(transaction: (tx: D1Transaction<TFullSchema, TSchema>) => Promise<T>): Promise<T> {
const savepointName = `sp${this.nestedIndex}`;
const tx = new D1Transaction('async', this.dialect, this.session, this.schema, this.nestedIndex + 1);
Expand All @@ -85,6 +90,8 @@ export class D1Transaction<
export class PreparedQuery<T extends PreparedQueryConfig = PreparedQueryConfig> extends PreparedQueryBase<
{ type: 'async'; run: D1Result; all: T['all']; get: T['get']; values: T['values'] }
> {
static readonly [entityKind]: string = 'D1PreparedQuery';

constructor(
private stmt: D1PreparedStatement,
private queryString: string,
Expand Down
Loading

0 comments on commit 92a27ec

Please sign in to comment.