Skip to content

Commit

Permalink
Merge branch 'beta' into transactions
Browse files Browse the repository at this point in the history
  • Loading branch information
dankochetov committed Apr 9, 2023
2 parents d798a9e + ecce0a2 commit 80c7de3
Show file tree
Hide file tree
Showing 42 changed files with 502 additions and 122 deletions.
22 changes: 0 additions & 22 deletions .eslintrc.cjs

This file was deleted.

19 changes: 19 additions & 0 deletions .eslintrc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
root: true
extends:
- 'plugin:@typescript-eslint/base'
parser: '@typescript-eslint/parser'
plugins:
- import
- unused-imports
rules:
'@typescript-eslint/consistent-type-imports':
- error
- disallowTypeAnnotations: false
fixStyle: inline-type-imports
import/no-cycle: error
import/no-self-import: error
import/no-empty-named-blocks: error
unused-imports/no-unused-imports: error
import/no-useless-path-segments: error
import/newline-after-import: error
import/no-duplicates: error
36 changes: 0 additions & 36 deletions .prettierrc.js

This file was deleted.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export const users = pgTable('users', {
id: serial('id').primaryKey(),
fullName: text('full_name').notNull(),
phone: varchar('phone', { length: 20 }).notNull(),
role: text<'user' | 'admin'>('role').default('user').notNull(),
role: text('role', { enum: ['user', 'admin'] }).default('user').notNull(),
cityId: integer('city_id').references(() => cities.id),
createdAt: timestamp('created_at').defaultNow().notNull(),
updatedAt: timestamp('updated_at').defaultNow().notNull(),
Expand Down
6 changes: 6 additions & 0 deletions changelogs/drizzle-orm/0.23.6.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
- 🐛 Fixed referencing the selected aliased field in the same query
- 🐛 Fixed decimal column data type in MySQL
- 🐛 Fixed mode autocompletion for integer column in SQLite
- 🐛 Fixed extra parentheses in the generated SQL for the `IN` operator (#382)
- 🐛 Fixed regression in `pgEnum.enumValues` type (#358)
- 🎉 Allowed readonly arrays to be passed to `pgEnum`
1 change: 1 addition & 0 deletions changelogs/drizzle-orm/0.23.7.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- 🎉 Added `INSERT IGNORE` support for MySQL (#305)
1 change: 1 addition & 0 deletions changelogs/drizzle-orm/0.23.8.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- 🎉 Fixed dates timezone differences for timestamps in Postgres and MySQL (contributed by @AppelBoomHD via #288)
1 change: 1 addition & 0 deletions changelogs/drizzle-zod/0.2.1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- 🐛 Fix insert schemas generation
5 changes: 3 additions & 2 deletions drizzle-orm/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "drizzle-orm",
"version": "0.23.5",
"version": "0.23.8",
"description": "Drizzle ORM package for SQL databases",
"scripts": {
"build": "tsc && resolve-tspaths && cp ../README.md package.json dist/",
Expand Down Expand Up @@ -126,6 +126,7 @@
"sql.js": "^1.8.0",
"sqlite3": "^5.1.2",
"vite-tsconfig-paths": "^4.0.7",
"vitest": "^0.29.8"
"vitest": "^0.29.8",
"zod": "^3.20.2"
}
}
4 changes: 2 additions & 2 deletions drizzle-orm/src/mysql-core/columns/decimal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ export interface MySqlDecimalHKT extends ColumnHKTBase {

export type MySqlDecimalBuilderInitial<TName extends string> = MySqlDecimalBuilder<{
name: TName;
data: number;
driverParam: number | string;
data: string;
driverParam: string;
notNull: false;
hasDefault: false;
}>;
Expand Down
9 changes: 5 additions & 4 deletions drizzle-orm/src/mysql-core/columns/enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ export class MySqlEnumColumnBuilder<T extends ColumnBuilderBaseConfig>
}

export class MySqlEnumColumn<T extends ColumnBaseConfig>
extends MySqlColumn<MySqlEnumColumnHKT, T, { values: string[] }>
extends MySqlColumn<MySqlEnumColumnHKT, T, { values: readonly string[] }>
{
readonly values: string[] = this.config.values;
readonly values: readonly string[] = this.config.values;

getSQLType(): string {
return `enum(${this.values.map((value) => `'${value}'`).join(',')})`;
Expand All @@ -53,8 +53,9 @@ export class MySqlEnumColumn<T extends ColumnBaseConfig>

export function mysqlEnum<TName extends string, U extends string, T extends Readonly<[U, ...U[]]>>(
name: TName,
values: Writable<T>,
): MySqlEnumColumnBuilderInitial<TName, Writable<T>> {
values: T | Writable<T>,
): MySqlEnumColumnBuilderInitial<TName, Writable<T>>;
export function mysqlEnum(name: string, values: string[]) {
if (values.length === 0) throw Error(`You have an empty array for "${name}" enum values`);

return new MySqlEnumColumnBuilder(name, values);
Expand Down
6 changes: 5 additions & 1 deletion drizzle-orm/src/mysql-core/columns/timestamp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@ export class MySqlTimestamp<T extends ColumnBaseConfig>
}

override mapFromDriverValue(value: string): Date {
return new Date(value);
return new Date(value + '+0000');
}

override mapToDriverValue(value: Date): string {
return value.toISOString().slice(0, 19).replace('T', ' ');
}
}

Expand Down
2 changes: 1 addition & 1 deletion drizzle-orm/src/mysql-core/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export class MySqlDatabase<TQueryResult extends QueryResultHKT> {

return new Proxy(
new WithSubquery(qb.getSQL(), qb.getSelectedFields() as SelectedFields, alias, true),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: 'subquery_selection', sqlBehavior: 'error' }),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),
) as WithSubqueryWithSelection<TSelection, TAlias>;
},
};
Expand Down
6 changes: 4 additions & 2 deletions drizzle-orm/src/mysql-core/dialect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ export class MySqlDialect {
return sql`${withSql}select ${selection} from ${table}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClausesSql}`;
}

buildInsertQuery({ table, values, onConflict, returning }: MySqlInsertConfig): SQL {
buildInsertQuery({ table, values, ignore, onConflict, returning }: MySqlInsertConfig): SQL {
const isSingleValue = values.length === 1;
const valuesSqlList: ((SQLChunk | SQL)[] | SQL)[] = [];
const columns: Record<string, AnyMySqlColumn> = table[Table.Symbol.Columns];
Expand All @@ -319,13 +319,15 @@ export class MySqlDialect {

const valuesSql = sql.fromList(valuesSqlList);

const ignoreSql = ignore ? sql` ignore` : undefined;

const returningSql = returning
? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`
: undefined;

const onConflictSql = onConflict ? sql` on duplicate key ${onConflict}` : undefined;

return sql`insert into ${table} ${insertOrder} values ${valuesSql}${onConflictSql}`;
return sql`insert${ignoreSql} into ${table} ${insertOrder} values ${valuesSql}${onConflictSql}`;
}

sqlToQuery(sql: SQL): Query {
Expand Down
13 changes: 11 additions & 2 deletions drizzle-orm/src/mysql-core/query-builders/insert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type { MySqlUpdateSetSource } from './update';
export interface MySqlInsertConfig<TTable extends AnyMySqlTable = AnyMySqlTable> {
table: TTable;
values: Record<string, Param | SQL>[];
ignore: boolean;
onConflict?: SQL;
returning?: SelectedFieldsOrdered;
}
Expand All @@ -32,12 +33,19 @@ export type MySqlInsertValue<TTable extends AnyMySqlTable> = Simplify<
>;

export class MySqlInsertBuilder<TTable extends AnyMySqlTable, TQueryResult extends QueryResultHKT> {
private shouldIgnore: boolean = false;

constructor(
private table: TTable,
private session: MySqlSession,
private dialect: MySqlDialect,
) {}

ignore(): this {
this.shouldIgnore = true;
return this;
}

values(value: MySqlInsertValue<TTable>): MySqlInsert<TTable, TQueryResult>;
values(values: MySqlInsertValue<TTable>[]): MySqlInsert<TTable, TQueryResult>;
/**
Expand Down Expand Up @@ -68,7 +76,7 @@ export class MySqlInsertBuilder<TTable extends AnyMySqlTable, TQueryResult exten
return result;
});

return new MySqlInsert(this.table, mappedValues, this.session, this.dialect);
return new MySqlInsert(this.table, mappedValues, this.shouldIgnore, this.session, this.dialect);
}
}

Expand All @@ -87,11 +95,12 @@ export class MySqlInsert<TTable extends AnyMySqlTable, TQueryResult extends Quer
constructor(
table: TTable,
values: MySqlInsertConfig['values'],
ignore: boolean,
private session: MySqlSession,
private dialect: MySqlDialect,
) {
super();
this.config = { table, values };
this.config = { table, values, ignore };
}

onDuplicateKeyUpdate(config: {
Expand Down
4 changes: 2 additions & 2 deletions drizzle-orm/src/mysql-core/query-builders/select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ export abstract class MySqlSelectQueryBuilder<
on = on(
new Proxy(
this.config.fields,
new SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' }),
new SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),
) as TSelection,
);
}
Expand Down Expand Up @@ -322,7 +322,7 @@ export abstract class MySqlSelectQueryBuilder<
): SubqueryWithSelection<BuildSubquerySelection<TSelection, TNullabilityMap>, TAlias> {
return new Proxy(
new Subquery(this.getSQL(), this.config.fields, alias),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: 'subquery_selection', sqlBehavior: 'error' }),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),
) as SubqueryWithSelection<BuildSubquerySelection<TSelection, TNullabilityMap>, TAlias>;
}
}
Expand Down
6 changes: 3 additions & 3 deletions drizzle-orm/src/pg-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ const publicUsersTable = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
verified: boolean('verified').notNull().default(false),
jsonb: jsonb<string[]>('jsonb'),
jsonb: jsonb('jsonb').$type<string[]>(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
});

Expand All @@ -394,7 +394,7 @@ const usersTable = mySchema.table('users', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
verified: boolean('verified').notNull().default(false),
jsonb: jsonb<string[]>('jsonb'),
jsonb: jsonb('jsonb').$type<string[]>(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
});
```
Expand Down Expand Up @@ -639,7 +639,7 @@ await db.update(users)
.set({ name: 'Mr. Dan' })
.where(eq(users.name, 'Dan'));

const updatedUser: InferModel<typeof users> = await db.delete(users)
const updatedUser: InferModel<typeof users> = await db.update(users)
.set({ name: 'Mr. Dan' })
.where(eq(users.name, 'Dan'))
.returning();
Expand Down
4 changes: 2 additions & 2 deletions drizzle-orm/src/pg-core/columns/enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export interface PgEnum<TValues extends [string, ...string[]]> {
<TName extends string>(name: TName): PgEnumColumnBuilderInitial<TName, TValues>;

readonly enumName: string;
readonly enumValues: string[];
readonly enumValues: TValues;
/** @internal */
[isPgEnumSym]: true;
}
Expand Down Expand Up @@ -71,7 +71,7 @@ export class PgEnumColumn<T extends ColumnBaseConfig> extends PgColumn<PgEnumCol
// Gratitude to zod for the enum function types
export function pgEnum<U extends string, T extends Readonly<[U, ...U[]]>>(
enumName: string,
values: Writable<T>,
values: T | Writable<T>,
): PgEnum<Writable<T>> {
const enumInstance = Object.assign(
<TName extends string>(name: TName): PgEnumColumnBuilderInitial<TName, Writable<T>> =>
Expand Down
6 changes: 5 additions & 1 deletion drizzle-orm/src/pg-core/columns/timestamp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,11 @@ export class PgTimestamp<T extends ColumnBaseConfig> extends PgColumn<PgTimestam
}

override mapFromDriverValue = (value: string): Date => {
return new Date(value);
return new Date(this.withTimezone ? value : value + '+0000');
};

override mapToDriverValue = (value: Date): string => {
return this.withTimezone ? value.toUTCString() : value.toISOString();
};
}

Expand Down
2 changes: 1 addition & 1 deletion drizzle-orm/src/pg-core/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class PgDatabase<TQueryResult extends QueryResultHKT> {

return new Proxy(
new WithSubquery(qb.getSQL(), qb.getSelectedFields() as SelectedFields, alias, true),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: 'subquery_selection', sqlBehavior: 'error' }),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),
) as WithSubqueryWithSelection<TSelection, TAlias>;
},
};
Expand Down
4 changes: 2 additions & 2 deletions drizzle-orm/src/pg-core/query-builders/select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ export abstract class PgSelectQueryBuilder<
on = on(
new Proxy(
this.config.fields,
new SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' }),
new SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),
) as TSelection,
);
}
Expand Down Expand Up @@ -315,7 +315,7 @@ export abstract class PgSelectQueryBuilder<
): SubqueryWithSelection<BuildSubquerySelection<TSelection, TNullabilityMap>, TAlias> {
return new Proxy(
new Subquery(this.getSQL(), this.config.fields, alias),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: 'subquery_selection', sqlBehavior: 'error' }),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),
) as SubqueryWithSelection<BuildSubquerySelection<TSelection, TNullabilityMap>, TAlias>;
}
}
Expand Down
2 changes: 1 addition & 1 deletion drizzle-orm/src/sql/expressions/conditions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ export function inArray(
if (values.length === 0) {
throw new Error('inArray requires at least one value');
}
return sql`${column} in (${values.map((v) => bindIfParam(v, column))})`;
return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;
}

return sql`${column} in ${bindIfParam(values, column)}`;
Expand Down
8 changes: 3 additions & 5 deletions drizzle-orm/src/sqlite-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -461,9 +461,7 @@ const users = sqliteTable('users', {
createdAt: integer('created_at', { mode: 'timestamp' }),
});

type NewUser = InferModel<typeof users>;

const db = drizzle(...);
type NewUser = InferModel<typeof users, "insert">;

const newUser: NewUser = {
name: 'Andrew',
Expand All @@ -472,10 +470,10 @@ const newUser: NewUser = {

db.insert(users).values(newUser).run();

const insertedUsers/*: NewUser[]*/ = db.insert(users).values(newUsers).returning().all();
const insertedUsers/*: NewUser[]*/ = db.insert(users).values(newUser).returning().all();

const insertedUsersIds/*: { insertedId: number }[]*/ = db.insert(users)
.values(newUsers)
.values(newUser)
.returning({ insertedId: users.id })
.all();
```
Expand Down
Loading

0 comments on commit 80c7de3

Please sign in to comment.