chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 12:10:05 +08:00
commit d37d8d293b
1388 changed files with 484182 additions and 0 deletions
+51
View File
@@ -0,0 +1,51 @@
`drizzle-arktype` is a plugin for [Drizzle ORM](https://github.com/drizzle-team/drizzle-orm) that allows you to generate [arktype](https://arktype.io/) schemas from Drizzle ORM schemas.
**Features**
- Create a select schema for tables, views and enums.
- Create insert and update schemas for tables.
- Supports all dialects: PostgreSQL, MySQL and SQLite.
# Usage
```ts
import { pgEnum, pgTable, serial, text, timestamp } from 'drizzle-orm/pg-core';
import { createInsertSchema, createSelectSchema } from 'drizzle-arktype';
import { type } from 'arktype';
const users = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
email: text('email').notNull(),
role: text('role', { enum: ['admin', 'user'] }).notNull(),
createdAt: timestamp('created_at').notNull().defaultNow(),
});
// Schema for inserting a user - can be used to validate API requests
const insertUserSchema = createInsertSchema(users);
// Schema for updating a user - can be used to validate API requests
const updateUserSchema = createUpdateSchema(users);
// Schema for selecting a user - can be used to validate API responses
const selectUserSchema = createSelectSchema(users);
// Overriding the fields
const insertUserSchema = createInsertSchema(users, {
role: type('string'),
});
// Refining the fields - useful if you want to change the fields before they become nullable/optional in the final schema
const insertUserSchema = createInsertSchema(users, {
id: (schema) => schema.atLeast(1),
role: type('string'),
});
// Usage
const isUserValid = parse(insertUserSchema, {
name: 'John Doe',
email: 'johndoe@test.com',
role: 'admin',
});
```
+30
View File
@@ -0,0 +1,30 @@
import { bench, setup } from '@ark/attest';
import { type } from 'arktype';
import { boolean, integer, pgTable, text } from 'drizzle-orm/pg-core';
import { createSelectSchema } from '~/index.ts';
const users = pgTable('users', {
id: integer().primaryKey(),
firstName: text().notNull(),
middleName: text(),
lastName: text().notNull(),
age: integer().notNull(),
admin: boolean().notNull().default(false),
});
const teardown = setup();
bench('select schema', () => {
return createSelectSchema(users);
}).types([13129, 'instantiations']);
bench('select schema with refinements', () => {
return createSelectSchema(users, {
firstName: (t) => t.atMostLength(100),
middleName: (t) => t.atMostLength(100),
lastName: (t) => t.atMostLength(100),
age: type.number.atLeast(1),
});
}).types([21631, 'instantiations']);
teardown();
+77
View File
@@ -0,0 +1,77 @@
{
"name": "drizzle-arktype",
"version": "0.1.3",
"description": "Generate arktype schemas from Drizzle ORM schemas",
"type": "module",
"scripts": {
"build": "tsx scripts/build.ts",
"b": "pnpm build",
"test:types": "cd tests && tsc",
"pack": "(cd dist && npm pack --pack-destination ..) && rm -f package.tgz && mv *.tgz package.tgz",
"publish": "npm publish package.tgz",
"test": "vitest run",
"bench:types": "tsx ./benchmarks/types.ts"
},
"exports": {
".": {
"import": {
"types": "./index.d.mts",
"default": "./index.mjs"
},
"require": {
"types": "./index.d.cjs",
"default": "./index.cjs"
},
"types": "./index.d.ts",
"default": "./index.mjs"
}
},
"main": "./index.cjs",
"module": "./index.mjs",
"types": "./index.d.ts",
"publishConfig": {
"provenance": true
},
"repository": {
"type": "git",
"url": "git+https://github.com/drizzle-team/drizzle-orm.git"
},
"keywords": [
"arktype",
"validate",
"validation",
"schema",
"drizzle",
"orm",
"pg",
"mysql",
"postgresql",
"postgres",
"sqlite",
"database",
"sql",
"typescript",
"ts"
],
"author": "Drizzle Team",
"license": "Apache-2.0",
"peerDependencies": {
"arktype": ">=2.0.0",
"drizzle-orm": ">=0.36.0"
},
"devDependencies": {
"@ark/attest": "^0.45.8",
"@rollup/plugin-typescript": "^11.1.0",
"@types/node": "^18.15.10",
"arktype": "^2.1.10",
"cpy": "^10.1.0",
"drizzle-orm": "link:../drizzle-orm/dist",
"json-rules-engine": "7.3.1",
"rimraf": "^5.0.0",
"rollup": "^3.29.5",
"tsx": "^4.19.3",
"vite-tsconfig-paths": "^4.3.2",
"vitest": "^3.1.3",
"zx": "^7.2.2"
}
}
+33
View File
@@ -0,0 +1,33 @@
import typescript from '@rollup/plugin-typescript';
import { defineConfig } from 'rollup';
export default defineConfig([
{
input: 'src/index.ts',
output: [
{
format: 'esm',
dir: 'dist',
entryFileNames: '[name].mjs',
chunkFileNames: '[name]-[hash].mjs',
sourcemap: true,
},
{
format: 'cjs',
dir: 'dist',
entryFileNames: '[name].cjs',
chunkFileNames: '[name]-[hash].cjs',
sourcemap: true,
},
],
external: [
/^drizzle-orm\/?/,
'arktype',
],
plugins: [
typescript({
tsconfig: 'tsconfig.build.json',
}),
],
},
]);
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env -S pnpm tsx
import 'zx/globals';
import cpy from 'cpy';
await fs.remove('dist');
await $`rollup --config rollup.config.ts --configPlugin typescript`;
await $`resolve-tspaths`;
await fs.copy('README.md', 'dist/README.md');
await cpy('dist/**/*.d.ts', 'dist', {
rename: (basename) => basename.replace(/\.d\.ts$/, '.d.mts'),
});
await cpy('dist/**/*.d.ts', 'dist', {
rename: (basename) => basename.replace(/\.d\.ts$/, '.d.cts'),
});
await fs.copy('package.json', 'dist/package.json');
await $`scripts/fix-imports.ts`;
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env -S pnpm tsx
import 'zx/globals';
import path from 'node:path';
import { parse, print, visit } from 'recast';
import parser from 'recast/parsers/typescript';
function resolvePathAlias(importPath: string, file: string) {
if (importPath.startsWith('~/')) {
const relativePath = path.relative(path.dirname(file), path.resolve('dist.new', importPath.slice(2)));
importPath = relativePath.startsWith('.') ? relativePath : './' + relativePath;
}
return importPath;
}
function fixImportPath(importPath: string, file: string, ext: string) {
importPath = resolvePathAlias(importPath, file);
if (!/\..*\.(js|ts)$/.test(importPath)) {
return importPath;
}
return importPath.replace(/\.(js|ts)$/, ext);
}
const cjsFiles = await glob('dist/**/*.{cjs,d.cts}');
await Promise.all(cjsFiles.map(async (file) => {
const code = parse(await fs.readFile(file, 'utf8'), { parser });
visit(code, {
visitImportDeclaration(path) {
path.value.source.value = fixImportPath(path.value.source.value, file, '.cjs');
this.traverse(path);
},
visitExportAllDeclaration(path) {
path.value.source.value = fixImportPath(path.value.source.value, file, '.cjs');
this.traverse(path);
},
visitExportNamedDeclaration(path) {
if (path.value.source) {
path.value.source.value = fixImportPath(path.value.source.value, file, '.cjs');
}
this.traverse(path);
},
visitCallExpression(path) {
if (path.value.callee.type === 'Identifier' && path.value.callee.name === 'require') {
path.value.arguments[0].value = fixImportPath(path.value.arguments[0].value, file, '.cjs');
}
this.traverse(path);
},
visitTSImportType(path) {
path.value.argument.value = resolvePathAlias(path.value.argument.value, file);
this.traverse(path);
},
visitAwaitExpression(path) {
if (print(path.value).code.startsWith(`await import("./`)) {
path.value.argument.arguments[0].value = fixImportPath(path.value.argument.arguments[0].value, file, '.cjs');
}
this.traverse(path);
},
});
await fs.writeFile(file, print(code).code);
}));
let esmFiles = await glob('dist/**/*.{js,d.ts}');
await Promise.all(esmFiles.map(async (file) => {
const code = parse(await fs.readFile(file, 'utf8'), { parser });
visit(code, {
visitImportDeclaration(path) {
path.value.source.value = fixImportPath(path.value.source.value, file, '.js');
this.traverse(path);
},
visitExportAllDeclaration(path) {
path.value.source.value = fixImportPath(path.value.source.value, file, '.js');
this.traverse(path);
},
visitExportNamedDeclaration(path) {
if (path.value.source) {
path.value.source.value = fixImportPath(path.value.source.value, file, '.js');
}
this.traverse(path);
},
visitTSImportType(path) {
path.value.argument.value = fixImportPath(path.value.argument.value, file, '.js');
this.traverse(path);
},
visitAwaitExpression(path) {
if (print(path.value).code.startsWith(`await import("./`)) {
path.value.argument.arguments[0].value = fixImportPath(path.value.argument.arguments[0].value, file, '.js');
}
this.traverse(path);
},
});
await fs.writeFile(file, print(code).code);
}));
esmFiles = await glob('dist/**/*.{mjs,d.mts}');
await Promise.all(esmFiles.map(async (file) => {
const code = parse(await fs.readFile(file, 'utf8'), { parser });
visit(code, {
visitImportDeclaration(path) {
path.value.source.value = fixImportPath(path.value.source.value, file, '.mjs');
this.traverse(path);
},
visitExportAllDeclaration(path) {
path.value.source.value = fixImportPath(path.value.source.value, file, '.mjs');
this.traverse(path);
},
visitExportNamedDeclaration(path) {
if (path.value.source) {
path.value.source.value = fixImportPath(path.value.source.value, file, '.mjs');
}
this.traverse(path);
},
visitTSImportType(path) {
path.value.argument.value = fixImportPath(path.value.argument.value, file, '.mjs');
this.traverse(path);
},
visitAwaitExpression(path) {
if (print(path.value).code.startsWith(`await import("./`)) {
path.value.argument.arguments[0].value = fixImportPath(path.value.argument.arguments[0].value, file, '.mjs');
}
this.traverse(path);
},
});
await fs.writeFile(file, print(code).code);
}));
+294
View File
@@ -0,0 +1,294 @@
import { type Type, type } from 'arktype';
import type { Column, ColumnBaseConfig } from 'drizzle-orm';
import type {
MySqlBigInt53,
MySqlChar,
MySqlDouble,
MySqlFloat,
MySqlInt,
MySqlMediumInt,
MySqlReal,
MySqlSerial,
MySqlSmallInt,
MySqlText,
MySqlTinyInt,
MySqlVarChar,
MySqlYear,
} from 'drizzle-orm/mysql-core';
import type {
PgArray,
PgBigInt53,
PgBigSerial53,
PgBinaryVector,
PgChar,
PgDoublePrecision,
PgGeometry,
PgGeometryObject,
PgHalfVector,
PgInteger,
PgLineABC,
PgLineTuple,
PgPointObject,
PgPointTuple,
PgReal,
PgSerial,
PgSmallInt,
PgSmallSerial,
PgUUID,
PgVarchar,
PgVector,
} from 'drizzle-orm/pg-core';
import type {
SingleStoreBigInt53,
SingleStoreChar,
SingleStoreDouble,
SingleStoreFloat,
SingleStoreInt,
SingleStoreMediumInt,
SingleStoreReal,
SingleStoreSerial,
SingleStoreSmallInt,
SingleStoreText,
SingleStoreTinyInt,
SingleStoreVarChar,
SingleStoreYear,
} from 'drizzle-orm/singlestore-core';
import type { SQLiteInteger, SQLiteReal, SQLiteText } from 'drizzle-orm/sqlite-core';
import { CONSTANTS } from './constants.ts';
import { isColumnType, isWithEnum } from './utils.ts';
export const literalSchema = type.string.or(type.number).or(type.boolean).or(type.null);
export const jsonSchema = literalSchema.or(type.unknown.as<any>().array()).or(type.object.as<Record<string, any>>());
export const bufferSchema = type.unknown.narrow((value) => value instanceof Buffer).as<Buffer>().describe( // eslint-disable-line no-instanceof/no-instanceof
'a Buffer instance',
);
export function columnToSchema(column: Column): Type {
let schema!: Type;
if (isWithEnum(column)) {
schema = column.enumValues.length ? type.enumerated(...column.enumValues) : type.string;
}
if (!schema) {
// Handle specific types
if (isColumnType<PgGeometry<any> | PgPointTuple<any>>(column, ['PgGeometry', 'PgPointTuple'])) {
schema = type([type.number, type.number]);
} else if (
isColumnType<PgPointObject<any> | PgGeometryObject<any>>(column, ['PgGeometryObject', 'PgPointObject'])
) {
schema = type({
x: type.number,
y: type.number,
});
} else if (isColumnType<PgHalfVector<any> | PgVector<any>>(column, ['PgHalfVector', 'PgVector'])) {
schema = column.dimensions
? type.number.array().exactlyLength(column.dimensions)
: type.number.array();
} else if (isColumnType<PgLineTuple<any>>(column, ['PgLine'])) {
schema = type([type.number, type.number, type.number]);
} else if (isColumnType<PgLineABC<any>>(column, ['PgLineABC'])) {
schema = type({
a: type.number,
b: type.number,
c: type.number,
});
} // Handle other types
else if (isColumnType<PgArray<any, any>>(column, ['PgArray'])) {
const arraySchema = columnToSchema(column.baseColumn).array();
schema = column.size ? arraySchema.exactlyLength(column.size) : arraySchema;
} else if (column.dataType === 'array') {
schema = type.unknown.array();
} else if (column.dataType === 'number') {
schema = numberColumnToSchema(column);
} else if (column.dataType === 'bigint') {
schema = bigintColumnToSchema(column);
} else if (column.dataType === 'boolean') {
schema = type.boolean;
} else if (column.dataType === 'date') {
schema = type.Date;
} else if (column.dataType === 'string') {
schema = stringColumnToSchema(column);
} else if (column.dataType === 'json') {
schema = jsonSchema;
} else if (column.dataType === 'custom') {
schema = type.unknown;
} else if (column.dataType === 'buffer') {
schema = bufferSchema;
}
}
if (!schema) {
schema = type.unknown;
}
return schema;
}
function numberColumnToSchema(column: Column): Type<number, any> {
let unsigned = column.getSQLType().includes('unsigned');
let min!: number;
let max!: number;
let integer = false;
if (isColumnType<MySqlTinyInt<any> | SingleStoreTinyInt<any>>(column, ['MySqlTinyInt', 'SingleStoreTinyInt'])) {
min = unsigned ? 0 : CONSTANTS.INT8_MIN;
max = unsigned ? CONSTANTS.INT8_UNSIGNED_MAX : CONSTANTS.INT8_MAX;
integer = true;
} else if (
isColumnType<PgSmallInt<any> | PgSmallSerial<any> | MySqlSmallInt<any> | SingleStoreSmallInt<any>>(column, [
'PgSmallInt',
'PgSmallSerial',
'MySqlSmallInt',
'SingleStoreSmallInt',
])
) {
min = unsigned ? 0 : CONSTANTS.INT16_MIN;
max = unsigned ? CONSTANTS.INT16_UNSIGNED_MAX : CONSTANTS.INT16_MAX;
integer = true;
} else if (
isColumnType<
PgReal<any> | MySqlFloat<any> | MySqlMediumInt<any> | SingleStoreFloat<any> | SingleStoreMediumInt<any>
>(column, [
'PgReal',
'MySqlFloat',
'MySqlMediumInt',
'SingleStoreFloat',
'SingleStoreMediumInt',
])
) {
min = unsigned ? 0 : CONSTANTS.INT24_MIN;
max = unsigned ? CONSTANTS.INT24_UNSIGNED_MAX : CONSTANTS.INT24_MAX;
integer = isColumnType(column, ['MySqlMediumInt', 'SingleStoreMediumInt']);
} else if (
isColumnType<PgInteger<any> | PgSerial<any> | MySqlInt<any> | SingleStoreInt<any>>(column, [
'PgInteger',
'PgSerial',
'MySqlInt',
'SingleStoreInt',
])
) {
min = unsigned ? 0 : CONSTANTS.INT32_MIN;
max = unsigned ? CONSTANTS.INT32_UNSIGNED_MAX : CONSTANTS.INT32_MAX;
integer = true;
} else if (
isColumnType<
| PgDoublePrecision<any>
| MySqlReal<any>
| MySqlDouble<any>
| SingleStoreReal<any>
| SingleStoreDouble<any>
| SQLiteReal<any>
>(column, [
'PgDoublePrecision',
'MySqlReal',
'MySqlDouble',
'SingleStoreReal',
'SingleStoreDouble',
'SQLiteReal',
])
) {
min = unsigned ? 0 : CONSTANTS.INT48_MIN;
max = unsigned ? CONSTANTS.INT48_UNSIGNED_MAX : CONSTANTS.INT48_MAX;
} else if (
isColumnType<
| PgBigInt53<any>
| PgBigSerial53<any>
| MySqlBigInt53<any>
| MySqlSerial<any>
| SingleStoreBigInt53<any>
| SingleStoreSerial<any>
| SQLiteInteger<any>
>(
column,
[
'PgBigInt53',
'PgBigSerial53',
'MySqlBigInt53',
'MySqlSerial',
'SingleStoreBigInt53',
'SingleStoreSerial',
'SQLiteInteger',
],
)
) {
unsigned = unsigned || isColumnType(column, ['MySqlSerial', 'SingleStoreSerial']);
min = unsigned ? 0 : Number.MIN_SAFE_INTEGER;
max = Number.MAX_SAFE_INTEGER;
integer = true;
} else if (isColumnType<MySqlYear<any> | SingleStoreYear<any>>(column, ['MySqlYear', 'SingleStoreYear'])) {
min = 1901;
max = 2155;
integer = true;
} else {
min = Number.MIN_SAFE_INTEGER;
max = Number.MAX_SAFE_INTEGER;
}
return (integer ? type.keywords.number.integer : type.number).atLeast(min).atMost(max);
}
/** @internal */
export const unsignedBigintNarrow = (v: bigint, ctx: { mustBe: (expected: string) => false }) =>
v < 0n ? ctx.mustBe('greater than') : v > CONSTANTS.INT64_UNSIGNED_MAX ? ctx.mustBe('less than') : true;
/** @internal */
export const bigintNarrow = (v: bigint, ctx: { mustBe: (expected: string) => false }) =>
v < CONSTANTS.INT64_MIN ? ctx.mustBe('greater than') : v > CONSTANTS.INT64_MAX ? ctx.mustBe('less than') : true;
function bigintColumnToSchema(column: Column): Type {
const unsigned = column.getSQLType().includes('unsigned');
return type.bigint.narrow(unsigned ? unsignedBigintNarrow : bigintNarrow);
}
function stringColumnToSchema(column: Column): Type {
if (isColumnType<PgUUID<ColumnBaseConfig<'string', 'PgUUID'>>>(column, ['PgUUID'])) {
return type(/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/iu).describe('a RFC-4122-compliant UUID');
}
if (
isColumnType<
PgBinaryVector<
ColumnBaseConfig<'string', 'PgBinaryVector'> & {
dimensions: number;
}
>
>(column, ['PgBinaryVector'])
) {
return type(`/^[01]{${column.dimensions}}$/`)
.describe(`a string containing ones or zeros while being ${column.dimensions} characters long`);
}
let max: number | undefined;
let fixed = false;
if (isColumnType<PgVarchar<any> | SQLiteText<any>>(column, ['PgVarchar', 'SQLiteText'])) {
max = column.length;
} else if (
isColumnType<MySqlVarChar<any> | SingleStoreVarChar<any>>(column, ['MySqlVarChar', 'SingleStoreVarChar'])
) {
max = column.length ?? CONSTANTS.INT16_UNSIGNED_MAX;
} else if (isColumnType<MySqlText<any> | SingleStoreText<any>>(column, ['MySqlText', 'SingleStoreText'])) {
if (column.textType === 'longtext') {
max = CONSTANTS.INT32_UNSIGNED_MAX;
} else if (column.textType === 'mediumtext') {
max = CONSTANTS.INT24_UNSIGNED_MAX;
} else if (column.textType === 'text') {
max = CONSTANTS.INT16_UNSIGNED_MAX;
} else {
max = CONSTANTS.INT8_UNSIGNED_MAX;
}
}
if (
isColumnType<PgChar<any> | MySqlChar<any> | SingleStoreChar<any>>(column, [
'PgChar',
'MySqlChar',
'SingleStoreChar',
])
) {
max = column.length;
fixed = true;
}
return max && fixed ? type.string.exactlyLength(max) : max ? type.string.atMostLength(max) : type.string;
}
+41
View File
@@ -0,0 +1,41 @@
import { Type, type } from 'arktype';
import type { Column } from 'drizzle-orm';
import type { Json } from './utils.ts';
export type ArktypeNullable<TSchema> = Type<type.infer<TSchema> | null>;
export type ArktypeOptional<TSchema> = [Type<type.infer<TSchema>>, '?'];
export type GetArktypeType<
TColumn extends Column,
> = TColumn['_']['columnType'] extends
'PgJson' | 'PgJsonb' | 'MySqlJson' | 'SingleStoreJson' | 'SQLiteTextJson' | 'SQLiteBlobJson'
? unknown extends TColumn['_']['data'] ? Type<Json> : Type<TColumn['_']['data']>
: Type<TColumn['_']['data']>;
type HandleSelectColumn<
TSchema,
TColumn extends Column,
> = TColumn['_']['notNull'] extends true ? TSchema
: ArktypeNullable<TSchema>;
type HandleInsertColumn<
TSchema,
TColumn extends Column,
> = TColumn['_']['notNull'] extends true ? TColumn['_']['hasDefault'] extends true ? ArktypeOptional<TSchema>
: TSchema
: ArktypeOptional<ArktypeNullable<TSchema>>;
type HandleUpdateColumn<
TSchema,
TColumn extends Column,
> = TColumn['_']['notNull'] extends true ? ArktypeOptional<TSchema>
: ArktypeOptional<ArktypeNullable<TSchema>>;
export type HandleColumn<
TType extends 'select' | 'insert' | 'update',
TColumn extends Column,
> = TType extends 'select' ? HandleSelectColumn<GetArktypeType<TColumn>, TColumn>
: TType extends 'insert' ? HandleInsertColumn<GetArktypeType<TColumn>, TColumn>
: TType extends 'update' ? HandleUpdateColumn<GetArktypeType<TColumn>, TColumn>
: GetArktypeType<TColumn>;
+20
View File
@@ -0,0 +1,20 @@
export const CONSTANTS = {
INT8_MIN: -128,
INT8_MAX: 127,
INT8_UNSIGNED_MAX: 255,
INT16_MIN: -32768,
INT16_MAX: 32767,
INT16_UNSIGNED_MAX: 65535,
INT24_MIN: -8388608,
INT24_MAX: 8388607,
INT24_UNSIGNED_MAX: 16777215,
INT32_MIN: -2147483648,
INT32_MAX: 2147483647,
INT32_UNSIGNED_MAX: 4294967295,
INT48_MIN: -140737488355328,
INT48_MAX: 140737488355327,
INT48_UNSIGNED_MAX: 281474976710655,
INT64_MIN: -9223372036854775808n,
INT64_MAX: 9223372036854775807n,
INT64_UNSIGNED_MAX: 18446744073709551615n,
};
+6
View File
@@ -0,0 +1,6 @@
export { bufferSchema, jsonSchema, literalSchema } from './column.ts';
export * from './column.types.ts';
export * from './schema.ts';
export * from './schema.types.internal.ts';
export * from './schema.types.ts';
export * from './utils.ts';
+98
View File
@@ -0,0 +1,98 @@
import { Type, type } from 'arktype';
import { Column, getTableColumns, getViewSelectedFields, is, isTable, isView, SQL } from 'drizzle-orm';
import type { Table, View } from 'drizzle-orm';
import type { PgEnum } from 'drizzle-orm/pg-core';
import { columnToSchema } from './column.ts';
import type { Conditions } from './schema.types.internal.ts';
import type { CreateInsertSchema, CreateSelectSchema, CreateUpdateSchema } from './schema.types.ts';
import { isPgEnum } from './utils.ts';
function getColumns(tableLike: Table | View) {
return isTable(tableLike) ? getTableColumns(tableLike) : getViewSelectedFields(tableLike);
}
function handleColumns(
columns: Record<string, any>,
refinements: Record<string, any>,
conditions: Conditions,
): Type {
const columnSchemas: Record<string, Type> = {};
for (const [key, selected] of Object.entries(columns)) {
if (!is(selected, Column) && !is(selected, SQL) && !is(selected, SQL.Aliased) && typeof selected === 'object') {
const columns = isTable(selected) || isView(selected) ? getColumns(selected) : selected;
columnSchemas[key] = handleColumns(columns, refinements[key] ?? {}, conditions);
continue;
}
const refinement = refinements[key];
if (
refinement !== undefined
&& (typeof refinement !== 'function' || (typeof refinement === 'function' && refinement.expression !== undefined))
) {
columnSchemas[key] = refinement;
continue;
}
const column = is(selected, Column) ? selected : undefined;
const schema = column ? columnToSchema(column) : type.unknown;
const refined = typeof refinement === 'function' ? refinement(schema) : schema;
if (conditions.never(column)) {
continue;
} else {
columnSchemas[key] = refined;
}
if (column) {
if (conditions.nullable(column)) {
columnSchemas[key] = columnSchemas[key]!.or(type.null);
}
if (conditions.optional(column)) {
columnSchemas[key] = columnSchemas[key]!.optional() as any;
}
}
}
return type(columnSchemas);
}
export const createSelectSchema = ((
entity: Table | View | PgEnum<[string, ...string[]]>,
refine?: Record<string, any>,
) => {
if (isPgEnum(entity)) {
return type.enumerated(...entity.enumValues);
}
const columns = getColumns(entity);
return handleColumns(columns, refine ?? {}, {
never: () => false,
optional: () => false,
nullable: (column) => !column.notNull,
}) as any;
}) as CreateSelectSchema;
export const createInsertSchema = ((
entity: Table,
refine?: Record<string, any>,
) => {
const columns = getColumns(entity);
return handleColumns(columns, refine ?? {}, {
never: (column) => column?.generated?.type === 'always' || column?.generatedIdentity?.type === 'always',
optional: (column) => !column.notNull || (column.notNull && column.hasDefault),
nullable: (column) => !column.notNull,
}) as any;
}) as CreateInsertSchema;
export const createUpdateSchema = ((
entity: Table,
refine?: Record<string, any>,
) => {
const columns = getColumns(entity);
return handleColumns(columns, refine ?? {}, {
never: (column) => column?.generated?.type === 'always' || column?.generatedIdentity?.type === 'always',
optional: () => true,
nullable: (column) => !column.notNull,
}) as any;
}) as CreateUpdateSchema;
@@ -0,0 +1,73 @@
import type { Type, type } from 'arktype';
import type { Column, DrizzleTypeError, SelectedFieldsFlat, Simplify, Table, View } from 'drizzle-orm';
import type { ArktypeNullable, ArktypeOptional, GetArktypeType, HandleColumn } from './column.types.ts';
import type { ColumnIsGeneratedAlwaysAs, GetSelection } from './utils.ts';
export interface Conditions {
never: (column?: Column) => boolean;
optional: (column: Column) => boolean;
nullable: (column: Column) => boolean;
}
type GenericSchema = type.cast<unknown> | [type.cast<unknown>, '?'];
type BuildRefineField<T> = T extends GenericSchema ? ((schema: T) => GenericSchema) | GenericSchema : never;
export type BuildRefine<
TColumns extends Record<string, any>,
> = {
[K in keyof TColumns as TColumns[K] extends Column | SelectedFieldsFlat<Column> | Table | View ? K : never]?:
TColumns[K] extends Column ? BuildRefineField<GetArktypeType<TColumns[K]>>
: BuildRefine<GetSelection<TColumns[K]>>;
};
type HandleRefinement<
TType extends 'select' | 'insert' | 'update',
TRefinement,
TColumn extends Column,
> = TRefinement extends (schema: any) => GenericSchema ? (
TColumn['_']['notNull'] extends true ? ReturnType<TRefinement>
: ArktypeNullable<ReturnType<TRefinement>>
) extends infer TSchema ? TType extends 'update' ? ArktypeOptional<TSchema>
: TSchema
: Type<any>
: TRefinement;
type IsRefinementDefined<
TRefinements extends Record<string | symbol | number, any> | undefined,
TKey extends string | symbol | number,
> = TRefinements extends object ? TRefinements[TKey] extends GenericSchema | ((schema: any) => any) ? true
: false
: false;
export type BuildSchema<
TType extends 'select' | 'insert' | 'update',
TColumns extends Record<string, any>,
TRefinements extends Record<string, any> | undefined,
> = type.instantiate<
Simplify<
{
readonly [K in keyof TColumns as ColumnIsGeneratedAlwaysAs<TColumns[K]> extends true ? never : K]:
TColumns[K] extends infer TColumn extends Column
? IsRefinementDefined<TRefinements, K> extends true
? HandleRefinement<TType, TRefinements[K & keyof TRefinements], TColumn>
: HandleColumn<TType, TColumn>
: TColumns[K] extends infer TNested extends SelectedFieldsFlat<Column> | Table | View ? BuildSchema<
TType,
GetSelection<TNested>,
TRefinements extends object ? TRefinements[K & keyof TRefinements] : undefined
>
: any;
}
>
>;
export type NoUnknownKeys<
TRefinement extends Record<string, any>,
TCompare extends Record<string, any>,
> = {
[K in keyof TRefinement]: K extends keyof TCompare
? TRefinement[K] extends Record<string, GenericSchema> ? NoUnknownKeys<TRefinement[K], TCompare[K]>
: TRefinement[K]
: DrizzleTypeError<`Found unknown key in refinement: "${K & string}"`>;
};
+48
View File
@@ -0,0 +1,48 @@
import type { Type } from 'arktype';
import type { Table, View } from 'drizzle-orm';
import type { PgEnum } from 'drizzle-orm/pg-core';
import type { BuildRefine, BuildSchema, NoUnknownKeys } from './schema.types.internal.ts';
export interface CreateSelectSchema {
<TTable extends Table>(table: TTable): BuildSchema<'select', TTable['_']['columns'], undefined>;
<
TTable extends Table,
TRefine extends BuildRefine<TTable['_']['columns']>,
>(
table: TTable,
refine?: NoUnknownKeys<TRefine, TTable['$inferSelect']>,
): BuildSchema<'select', TTable['_']['columns'], TRefine>;
<TView extends View>(view: TView): BuildSchema<'select', TView['_']['selectedFields'], undefined>;
<
TView extends View,
TRefine extends BuildRefine<TView['_']['selectedFields']>,
>(
view: TView,
refine: NoUnknownKeys<TRefine, TView['$inferSelect']>,
): BuildSchema<'select', TView['_']['selectedFields'], TRefine>;
<TEnum extends PgEnum<any>>(enum_: TEnum): Type<TEnum['enumValues'][number]>;
}
export interface CreateInsertSchema {
<TTable extends Table>(table: TTable): BuildSchema<'insert', TTable['_']['columns'], undefined>;
<
TTable extends Table,
TRefine extends BuildRefine<Pick<TTable['_']['columns'], keyof TTable['$inferInsert']>>,
>(
table: TTable,
refine?: NoUnknownKeys<TRefine, TTable['$inferInsert']>,
): BuildSchema<'insert', TTable['_']['columns'], TRefine>;
}
export interface CreateUpdateSchema {
<TTable extends Table>(table: TTable): BuildSchema<'update', TTable['_']['columns'], undefined>;
<
TTable extends Table,
TRefine extends BuildRefine<Pick<TTable['_']['columns'], keyof TTable['$inferInsert']>>,
>(
table: TTable,
refine?: TRefine,
): BuildSchema<'update', TTable['_']['columns'], TRefine>;
}
+27
View File
@@ -0,0 +1,27 @@
import type { type } from 'arktype';
import type { Column, SelectedFieldsFlat, Table, View } from 'drizzle-orm';
import type { PgEnum } from 'drizzle-orm/pg-core';
import type { literalSchema } from './column.ts';
export function isColumnType<T extends Column>(column: Column, columnTypes: string[]): column is T {
return columnTypes.includes(column.columnType);
}
export function isWithEnum(column: Column): column is typeof column & { enumValues: [string, ...string[]] } {
return 'enumValues' in column && Array.isArray(column.enumValues) && column.enumValues.length > 0;
}
export const isPgEnum: (entity: any) => entity is PgEnum<[string, ...string[]]> = isWithEnum as any;
type Literal = type.infer<typeof literalSchema>;
export type Json = Literal | Record<string, any> | any[];
export type ColumnIsGeneratedAlwaysAs<TColumn> = TColumn extends Column
? TColumn['_']['identity'] extends 'always' ? true
: TColumn['_']['generated'] extends { type: 'byDefault' } | undefined ? false
: true
: false;
export type GetSelection<T extends SelectedFieldsFlat<Column> | Table | View> = T extends Table ? T['_']['columns']
: T extends View ? T['_']['selectedFields']
: T;
+501
View File
@@ -0,0 +1,501 @@
import { Type, type } from 'arktype';
import { type Equal, sql } from 'drizzle-orm';
import { customType, int, json, mysqlSchema, mysqlTable, mysqlView, serial, text } from 'drizzle-orm/mysql-core';
import type { TopLevelCondition } from 'json-rules-engine';
import { test } from 'vitest';
import { bigintNarrow, jsonSchema, unsignedBigintNarrow } from '~/column.ts';
import { CONSTANTS } from '~/constants.ts';
import { createInsertSchema, createSelectSchema, createUpdateSchema } from '../src';
import { Expect, expectSchemaShape } from './utils.ts';
const intSchema = type.keywords.number.integer.atLeast(CONSTANTS.INT32_MIN).atMost(CONSTANTS.INT32_MAX);
const serialNumberModeSchema = type.keywords.number.integer.atLeast(0).atMost(Number.MAX_SAFE_INTEGER);
const textSchema = type.string.atMostLength(CONSTANTS.INT16_UNSIGNED_MAX);
test('table - select', (t) => {
const table = mysqlTable('test', {
id: serial().primaryKey(),
name: text().notNull(),
});
const result = createSelectSchema(table);
const expected = type({ id: serialNumberModeSchema, name: textSchema });
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('table in schema - select', (tc) => {
const schema = mysqlSchema('test');
const table = schema.table('test', {
id: serial().primaryKey(),
name: text().notNull(),
});
const result = createSelectSchema(table);
const expected = type({ id: serialNumberModeSchema, name: textSchema });
expectSchemaShape(tc, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('table - insert', (t) => {
const table = mysqlTable('test', {
id: serial().primaryKey(),
name: text().notNull(),
age: int(),
});
const result = createInsertSchema(table);
const expected = type({
id: serialNumberModeSchema.optional(),
name: textSchema,
age: intSchema.or(type.null).optional(),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('table - update', (t) => {
const table = mysqlTable('test', {
id: serial().primaryKey(),
name: text().notNull(),
age: int(),
});
const result = createUpdateSchema(table);
const expected = type({
id: serialNumberModeSchema.optional(),
name: textSchema.optional(),
age: intSchema.or(type.null).optional(),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('view qb - select', (t) => {
const table = mysqlTable('test', {
id: serial().primaryKey(),
name: text().notNull(),
});
const view = mysqlView('test').as((qb) => qb.select({ id: table.id, age: sql``.as('age') }).from(table));
const result = createSelectSchema(view);
const expected = type({ id: serialNumberModeSchema, age: type('unknown.any') });
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('view columns - select', (t) => {
const view = mysqlView('test', {
id: serial().primaryKey(),
name: text().notNull(),
}).as(sql``);
const result = createSelectSchema(view);
const expected = type({ id: serialNumberModeSchema, name: textSchema });
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('view with nested fields - select', (t) => {
const table = mysqlTable('test', {
id: serial().primaryKey(),
name: text().notNull(),
});
const view = mysqlView('test').as((qb) =>
qb.select({
id: table.id,
nested: {
name: table.name,
age: sql``.as('age'),
},
table,
}).from(table)
);
const result = createSelectSchema(view);
const expected = type({
id: serialNumberModeSchema,
nested: type({ name: textSchema, age: type('unknown.any') }),
table: type({ id: serialNumberModeSchema, name: textSchema }),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('nullability - select', (t) => {
const table = mysqlTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().default(1),
c4: int().notNull().default(1),
});
const result = createSelectSchema(table);
const expected = type({
c1: intSchema.or(type.null),
c2: intSchema,
c3: intSchema.or(type.null),
c4: intSchema,
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('nullability - insert', (t) => {
const table = mysqlTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().default(1),
c4: int().notNull().default(1),
c5: int().generatedAlwaysAs(1),
});
const result = createInsertSchema(table);
const expected = type({
c1: intSchema.or(type.null).optional(),
c2: intSchema,
c3: intSchema.or(type.null).optional(),
c4: intSchema.optional(),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('nullability - update', (t) => {
const table = mysqlTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().default(1),
c4: int().notNull().default(1),
c5: int().generatedAlwaysAs(1),
});
const result = createUpdateSchema(table);
const expected = type({
c1: intSchema.or(type.null).optional(),
c2: intSchema.optional(),
c3: intSchema.or(type.null).optional(),
c4: intSchema.optional(),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - select', (t) => {
const table = mysqlTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().notNull(),
});
const result = createSelectSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
});
const expected = type({
c1: intSchema.or(type.null),
c2: intSchema.atMost(1000),
c3: type.string.pipe(Number),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - select with custom data type', (t) => {
const customText = customType({ dataType: () => 'text' });
const table = mysqlTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().notNull(),
c4: customText(),
});
const customTextSchema = type.string.atLeastLength(1).atMostLength(100);
const result = createSelectSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
c4: customTextSchema,
});
const expected = type({
c1: intSchema.or(type.null),
c2: intSchema.atMost(1000),
c3: type.string.pipe(Number),
c4: customTextSchema,
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - insert', (t) => {
const table = mysqlTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().notNull(),
c4: int().generatedAlwaysAs(1),
});
const result = createInsertSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
});
const expected = type({
c1: intSchema.or(type.null).optional(),
c2: intSchema.atMost(1000),
c3: type.string.pipe(Number),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - update', (t) => {
const table = mysqlTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().notNull(),
c4: int().generatedAlwaysAs(1),
});
const result = createUpdateSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
});
const expected = type({
c1: intSchema.or(type.null).optional(),
c2: intSchema.atMost(1000).optional(),
c3: type.string.pipe(Number),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine view - select', (t) => {
const table = mysqlTable('test', {
c1: int(),
c2: int(),
c3: int(),
c4: int(),
c5: int(),
c6: int(),
});
const view = mysqlView('test').as((qb) =>
qb.select({
c1: table.c1,
c2: table.c2,
c3: table.c3,
nested: {
c4: table.c4,
c5: table.c5,
c6: table.c6,
},
table,
}).from(table)
);
const result = createSelectSchema(view, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
nested: {
c5: (schema) => schema.atMost(1000),
c6: type.string.pipe(Number),
},
table: {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
},
});
const expected = type({
c1: intSchema.or(type.null),
c2: intSchema.atMost(1000).or(type.null),
c3: type.string.pipe(Number),
nested: type({
c4: intSchema.or(type.null),
c5: intSchema.atMost(1000).or(type.null),
c6: type.string.pipe(Number),
}),
table: type({
c1: intSchema.or(type.null),
c2: intSchema.atMost(1000).or(type.null),
c3: type.string.pipe(Number),
c4: intSchema.or(type.null),
c5: intSchema.or(type.null),
c6: intSchema.or(type.null),
}),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('all data types', (t) => {
const table = mysqlTable('test', ({
bigint,
binary,
boolean,
char,
date,
datetime,
decimal,
double,
float,
int,
json,
mediumint,
mysqlEnum,
real,
serial,
smallint,
text,
time,
timestamp,
tinyint,
varchar,
varbinary,
year,
longtext,
mediumtext,
tinytext,
}) => ({
bigint1: bigint({ mode: 'number' }).notNull(),
bigint2: bigint({ mode: 'bigint' }).notNull(),
bigint3: bigint({ unsigned: true, mode: 'number' }).notNull(),
bigint4: bigint({ unsigned: true, mode: 'bigint' }).notNull(),
binary: binary({ length: 10 }).notNull(),
boolean: boolean().notNull(),
char1: char({ length: 10 }).notNull(),
char2: char({ length: 1, enum: ['a', 'b', 'c'] }).notNull(),
date1: date({ mode: 'date' }).notNull(),
date2: date({ mode: 'string' }).notNull(),
datetime1: datetime({ mode: 'date' }).notNull(),
datetime2: datetime({ mode: 'string' }).notNull(),
decimal1: decimal().notNull(),
decimal2: decimal({ unsigned: true }).notNull(),
double1: double().notNull(),
double2: double({ unsigned: true }).notNull(),
float1: float().notNull(),
float2: float({ unsigned: true }).notNull(),
int1: int().notNull(),
int2: int({ unsigned: true }).notNull(),
json: json().notNull(),
mediumint1: mediumint().notNull(),
mediumint2: mediumint({ unsigned: true }).notNull(),
enum: mysqlEnum('enum', ['a', 'b', 'c']).notNull(),
real: real().notNull(),
serial: serial().notNull(),
smallint1: smallint().notNull(),
smallint2: smallint({ unsigned: true }).notNull(),
text1: text().notNull(),
text2: text({ enum: ['a', 'b', 'c'] }).notNull(),
time: time().notNull(),
timestamp1: timestamp({ mode: 'date' }).notNull(),
timestamp2: timestamp({ mode: 'string' }).notNull(),
tinyint1: tinyint().notNull(),
tinyint2: tinyint({ unsigned: true }).notNull(),
varchar1: varchar({ length: 10 }).notNull(),
varchar2: varchar({ length: 1, enum: ['a', 'b', 'c'] }).notNull(),
varbinary: varbinary({ length: 10 }).notNull(),
year: year().notNull(),
longtext1: longtext().notNull(),
longtext2: longtext({ enum: ['a', 'b', 'c'] }).notNull(),
mediumtext1: mediumtext().notNull(),
mediumtext2: mediumtext({ enum: ['a', 'b', 'c'] }).notNull(),
tinytext1: tinytext().notNull(),
tinytext2: tinytext({ enum: ['a', 'b', 'c'] }).notNull(),
}));
const result = createSelectSchema(table);
const expected = type({
bigint1: type.keywords.number.integer.atLeast(Number.MIN_SAFE_INTEGER).atMost(Number.MAX_SAFE_INTEGER),
bigint2: type.bigint.narrow(bigintNarrow),
bigint3: type.keywords.number.integer.atLeast(0).atMost(Number.MAX_SAFE_INTEGER),
bigint4: type.bigint.narrow(unsignedBigintNarrow),
binary: type.string,
boolean: type.boolean,
char1: type.string.exactlyLength(10),
char2: type.enumerated('a', 'b', 'c'),
date1: type.Date,
date2: type.string,
datetime1: type.Date,
datetime2: type.string,
decimal1: type.string,
decimal2: type.string,
double1: type.number.atLeast(CONSTANTS.INT48_MIN).atMost(CONSTANTS.INT48_MAX),
double2: type.number.atLeast(0).atMost(CONSTANTS.INT48_UNSIGNED_MAX),
float1: type.number.atLeast(CONSTANTS.INT24_MIN).atMost(CONSTANTS.INT24_MAX),
float2: type.number.atLeast(0).atMost(CONSTANTS.INT24_UNSIGNED_MAX),
int1: type.keywords.number.integer.atLeast(CONSTANTS.INT32_MIN).atMost(CONSTANTS.INT32_MAX),
int2: type.keywords.number.integer.atLeast(0).atMost(CONSTANTS.INT32_UNSIGNED_MAX),
json: jsonSchema,
mediumint1: type.keywords.number.integer.atLeast(CONSTANTS.INT24_MIN).atMost(CONSTANTS.INT24_MAX),
mediumint2: type.keywords.number.integer.atLeast(0).atMost(CONSTANTS.INT24_UNSIGNED_MAX),
enum: type.enumerated('a', 'b', 'c'),
real: type.number.atLeast(CONSTANTS.INT48_MIN).atMost(CONSTANTS.INT48_MAX),
serial: type.keywords.number.integer.atLeast(0).atMost(Number.MAX_SAFE_INTEGER),
smallint1: type.keywords.number.integer.atLeast(CONSTANTS.INT16_MIN).atMost(CONSTANTS.INT16_MAX),
smallint2: type.keywords.number.integer.atLeast(0).atMost(CONSTANTS.INT16_UNSIGNED_MAX),
text1: type.string.atMostLength(CONSTANTS.INT16_UNSIGNED_MAX),
text2: type.enumerated('a', 'b', 'c'),
time: type.string,
timestamp1: type.Date,
timestamp2: type.string,
tinyint1: type.keywords.number.integer.atLeast(CONSTANTS.INT8_MIN).atMost(CONSTANTS.INT8_MAX),
tinyint2: type.keywords.number.integer.atLeast(0).atMost(CONSTANTS.INT8_UNSIGNED_MAX),
varchar1: type.string.atMostLength(10),
varchar2: type.enumerated('a', 'b', 'c'),
varbinary: type.string,
year: type.keywords.number.integer.atLeast(1901).atMost(2155),
longtext1: type.string.atMostLength(CONSTANTS.INT32_UNSIGNED_MAX),
longtext2: type.enumerated('a', 'b', 'c'),
mediumtext1: type.string.atMostLength(CONSTANTS.INT24_UNSIGNED_MAX),
mediumtext2: type.enumerated('a', 'b', 'c'),
tinytext1: type.string.atMostLength(CONSTANTS.INT8_UNSIGNED_MAX),
tinytext2: type.enumerated('a', 'b', 'c'),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
/* Infinitely recursive type */ {
const TopLevelCondition: Type<TopLevelCondition, {}> = type('unknown.any') as any;
const table = mysqlTable('test', {
json: json().$type<TopLevelCondition>(),
});
const result = createSelectSchema(table);
const expected = type({
json: TopLevelCondition.or(type.null),
});
Expect<Equal<type.infer<typeof result>, type.infer<typeof expected>>>();
}
/* Disallow unknown keys in table refinement - select */ {
const table = mysqlTable('test', { id: int() });
// @ts-expect-error
createSelectSchema(table, { unknown: type.string });
}
/* Disallow unknown keys in table refinement - insert */ {
const table = mysqlTable('test', { id: int() });
// @ts-expect-error
createInsertSchema(table, { unknown: type.string });
}
/* Disallow unknown keys in table refinement - update */ {
const table = mysqlTable('test', { id: int() });
// @ts-expect-error
createUpdateSchema(table, { unknown: type.string });
}
/* Disallow unknown keys in view qb - select */ {
const table = mysqlTable('test', { id: int() });
const view = mysqlView('test').as((qb) => qb.select().from(table));
const nestedSelect = mysqlView('test').as((qb) => qb.select({ table }).from(table));
// @ts-expect-error
createSelectSchema(view, { unknown: type.string });
// @ts-expect-error
createSelectSchema(nestedSelect, { table: { unknown: type.string } });
}
/* Disallow unknown keys in view columns - select */ {
const view = mysqlView('test', { id: int() }).as(sql``);
// @ts-expect-error
createSelectSchema(view, { unknown: type.string });
}
+557
View File
@@ -0,0 +1,557 @@
import { Type, type } from 'arktype';
import { type Equal, sql } from 'drizzle-orm';
import {
customType,
integer,
json,
jsonb,
pgEnum,
pgMaterializedView,
pgSchema,
pgTable,
pgView,
serial,
text,
} from 'drizzle-orm/pg-core';
import type { TopLevelCondition } from 'json-rules-engine';
import { test } from 'vitest';
import { bigintNarrow, jsonSchema } from '~/column.ts';
import { CONSTANTS } from '~/constants.ts';
import { createInsertSchema, createSelectSchema, createUpdateSchema } from '../src';
import { Expect, expectEnumValues, expectSchemaShape } from './utils.ts';
const integerSchema = type.keywords.number.integer.atLeast(CONSTANTS.INT32_MIN).atMost(CONSTANTS.INT32_MAX);
const textSchema = type.string;
test('table - select', (t) => {
const table = pgTable('test', {
id: serial().primaryKey(),
name: text().notNull(),
});
const result = createSelectSchema(table);
const expected = type({ id: integerSchema, name: textSchema });
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('table in schema - select', (tc) => {
const schema = pgSchema('test');
const table = schema.table('test', {
id: serial().primaryKey(),
name: text().notNull(),
});
const result = createSelectSchema(table);
const expected = type({ id: integerSchema, name: textSchema });
expectSchemaShape(tc, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('table - insert', (t) => {
const table = pgTable('test', {
id: integer().generatedAlwaysAsIdentity().primaryKey(),
name: text().notNull(),
age: integer(),
});
const result = createInsertSchema(table);
const expected = type({ name: textSchema, age: integerSchema.or(type.null).optional() });
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('table - update', (t) => {
const table = pgTable('test', {
id: integer().generatedAlwaysAsIdentity().primaryKey(),
name: text().notNull(),
age: integer(),
});
const result = createUpdateSchema(table);
const expected = type({
name: textSchema.optional(),
age: integerSchema.or(type.null).optional(),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('view qb - select', (t) => {
const table = pgTable('test', {
id: serial().primaryKey(),
name: text().notNull(),
});
const view = pgView('test').as((qb) => qb.select({ id: table.id, age: sql``.as('age') }).from(table));
const result = createSelectSchema(view);
const expected = type({ id: integerSchema, age: type('unknown.any') });
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('view columns - select', (t) => {
const view = pgView('test', {
id: serial().primaryKey(),
name: text().notNull(),
}).as(sql``);
const result = createSelectSchema(view);
const expected = type({ id: integerSchema, name: textSchema });
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('materialized view qb - select', (t) => {
const table = pgTable('test', {
id: serial().primaryKey(),
name: text().notNull(),
});
const view = pgMaterializedView('test').as((qb) => qb.select({ id: table.id, age: sql``.as('age') }).from(table));
const result = createSelectSchema(view);
const expected = type({ id: integerSchema, age: type('unknown.any') });
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('materialized view columns - select', (t) => {
const view = pgView('test', {
id: serial().primaryKey(),
name: text().notNull(),
}).as(sql``);
const result = createSelectSchema(view);
const expected = type({ id: integerSchema, name: textSchema });
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('view with nested fields - select', (t) => {
const table = pgTable('test', {
id: serial().primaryKey(),
name: text().notNull(),
});
const view = pgMaterializedView('test').as((qb) =>
qb.select({
id: table.id,
nested: {
name: table.name,
age: sql``.as('age'),
},
table,
}).from(table)
);
const result = createSelectSchema(view);
const expected = type({
id: integerSchema,
nested: { name: textSchema, age: type('unknown.any') },
table: { id: integerSchema, name: textSchema },
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('enum - select', (t) => {
const enum_ = pgEnum('test', ['a', 'b', 'c']);
const result = createSelectSchema(enum_);
const expected = type.enumerated('a', 'b', 'c');
expectEnumValues(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('nullability - select', (t) => {
const table = pgTable('test', {
c1: integer(),
c2: integer().notNull(),
c3: integer().default(1),
c4: integer().notNull().default(1),
});
const result = createSelectSchema(table);
const expected = type({
c1: integerSchema.or(type.null),
c2: integerSchema,
c3: integerSchema.or(type.null),
c4: integerSchema,
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('nullability - insert', (t) => {
const table = pgTable('test', {
c1: integer(),
c2: integer().notNull(),
c3: integer().default(1),
c4: integer().notNull().default(1),
c5: integer().generatedAlwaysAs(1),
c6: integer().generatedAlwaysAsIdentity(),
c7: integer().generatedByDefaultAsIdentity(),
});
const result = createInsertSchema(table);
const expected = type({
c1: integerSchema.or(type.null).optional(),
c2: integerSchema,
c3: integerSchema.or(type.null).optional(),
c4: integerSchema.optional(),
c7: integerSchema.optional(),
});
expectSchemaShape(t, expected).from(result);
});
test('nullability - update', (t) => {
const table = pgTable('test', {
c1: integer(),
c2: integer().notNull(),
c3: integer().default(1),
c4: integer().notNull().default(1),
c5: integer().generatedAlwaysAs(1),
c6: integer().generatedAlwaysAsIdentity(),
c7: integer().generatedByDefaultAsIdentity(),
});
const result = createUpdateSchema(table);
const expected = type({
c1: integerSchema.or(type.null).optional(),
c2: integerSchema.optional(),
c3: integerSchema.or(type.null).optional(),
c4: integerSchema.optional(),
c7: integerSchema.optional(),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - select', (t) => {
const table = pgTable('test', {
c1: integer(),
c2: integer().notNull(),
c3: integer().notNull(),
});
const result = createSelectSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
});
const expected = type({
c1: integerSchema.or(type.null),
c2: integerSchema.atMost(1000),
c3: type.string.pipe(Number),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - select with custom data type', (t) => {
const customText = customType({ dataType: () => 'text' });
const table = pgTable('test', {
c1: integer(),
c2: integer().notNull(),
c3: integer().notNull(),
c4: customText(),
});
const customTextSchema = type.string.atLeastLength(1).atMostLength(100);
const result = createSelectSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
c4: customTextSchema,
});
const expected = type({
c1: integerSchema.or(type.null),
c2: integerSchema.atMost(1000),
c3: type.string.pipe(Number),
c4: customTextSchema,
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - insert', (t) => {
const table = pgTable('test', {
c1: integer(),
c2: integer().notNull(),
c3: integer().notNull(),
c4: integer().generatedAlwaysAs(1),
});
const result = createInsertSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
});
const expected = type({
c1: integerSchema.or(type.null).optional(),
c2: integerSchema.atMost(1000),
c3: type.string.pipe(Number),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - update', (t) => {
const table = pgTable('test', {
c1: integer(),
c2: integer().notNull(),
c3: integer().notNull(),
c4: integer().generatedAlwaysAs(1),
});
const result = createUpdateSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
});
const expected = type({
c1: integerSchema.or(type.null).optional(),
c2: integerSchema.atMost(1000).optional(),
c3: type.string.pipe(Number),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine view - select', (t) => {
const table = pgTable('test', {
c1: integer(),
c2: integer(),
c3: integer(),
c4: integer(),
c5: integer(),
c6: integer(),
});
const view = pgView('test').as((qb) =>
qb.select({
c1: table.c1,
c2: table.c2,
c3: table.c3,
nested: {
c4: table.c4,
c5: table.c5,
c6: table.c6,
},
table,
}).from(table)
);
const result = createSelectSchema(view, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
nested: {
c5: (schema) => schema.atMost(1000),
c6: type.string.pipe(Number),
},
table: {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
},
});
const expected = type({
c1: integerSchema.or(type.null),
c2: integerSchema.atMost(1000).or(type.null),
c3: type.string.pipe(Number),
nested: type({
c4: integerSchema.or(type.null),
c5: integerSchema.atMost(1000).or(type.null),
c6: type.string.pipe(Number),
}),
table: type({
c1: integerSchema.or(type.null),
c2: integerSchema.atMost(1000).or(type.null),
c3: type.string.pipe(Number),
c4: integerSchema.or(type.null),
c5: integerSchema.or(type.null),
c6: integerSchema.or(type.null),
}),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('all data types', (t) => {
const table = pgTable('test', ({
bigint,
bigserial,
bit,
boolean,
date,
char,
cidr,
doublePrecision,
geometry,
halfvec,
inet,
integer,
interval,
json,
jsonb,
line,
macaddr,
macaddr8,
numeric,
point,
real,
serial,
smallint,
smallserial,
text,
sparsevec,
time,
timestamp,
uuid,
varchar,
vector,
}) => ({
bigint1: bigint({ mode: 'number' }).notNull(),
bigint2: bigint({ mode: 'bigint' }).notNull(),
bigserial1: bigserial({ mode: 'number' }).notNull(),
bigserial2: bigserial({ mode: 'bigint' }).notNull(),
bit: bit({ dimensions: 5 }).notNull(),
boolean: boolean().notNull(),
date1: date({ mode: 'date' }).notNull(),
date2: date({ mode: 'string' }).notNull(),
char1: char({ length: 10 }).notNull(),
char2: char({ length: 1, enum: ['a', 'b', 'c'] }).notNull(),
cidr: cidr().notNull(),
doublePrecision: doublePrecision().notNull(),
geometry1: geometry({ type: 'point', mode: 'tuple' }).notNull(),
geometry2: geometry({ type: 'point', mode: 'xy' }).notNull(),
halfvec: halfvec({ dimensions: 3 }).notNull(),
inet: inet().notNull(),
integer: integer().notNull(),
interval: interval().notNull(),
json: json().notNull(),
jsonb: jsonb().notNull(),
line1: line({ mode: 'abc' }).notNull(),
line2: line({ mode: 'tuple' }).notNull(),
macaddr: macaddr().notNull(),
macaddr8: macaddr8().notNull(),
numeric: numeric().notNull(),
point1: point({ mode: 'xy' }).notNull(),
point2: point({ mode: 'tuple' }).notNull(),
real: real().notNull(),
serial: serial().notNull(),
smallint: smallint().notNull(),
smallserial: smallserial().notNull(),
text1: text().notNull(),
text2: text({ enum: ['a', 'b', 'c'] }).notNull(),
sparsevec: sparsevec({ dimensions: 3 }).notNull(),
time: time().notNull(),
timestamp1: timestamp({ mode: 'date' }).notNull(),
timestamp2: timestamp({ mode: 'string' }).notNull(),
uuid: uuid().notNull(),
varchar1: varchar({ length: 10 }).notNull(),
varchar2: varchar({ length: 1, enum: ['a', 'b', 'c'] }).notNull(),
vector: vector({ dimensions: 3 }).notNull(),
array1: integer().array().notNull(),
array2: integer().array().array(2).notNull(),
array3: varchar({ length: 10 }).array().array(2).notNull(),
}));
const result = createSelectSchema(table);
const expected = type({
bigint1: type.keywords.number.integer.atLeast(Number.MIN_SAFE_INTEGER).atMost(Number.MAX_SAFE_INTEGER),
bigint2: type.bigint.narrow(bigintNarrow),
bigserial1: type.keywords.number.integer.atLeast(Number.MIN_SAFE_INTEGER).atMost(Number.MAX_SAFE_INTEGER),
bigserial2: type.bigint.narrow(bigintNarrow),
bit: type(/^[01]{5}$/).describe('a string containing ones or zeros while being 5 characters long'),
boolean: type.boolean,
date1: type.Date,
date2: type.string,
char1: type.string.exactlyLength(10),
char2: type.enumerated('a', 'b', 'c'),
cidr: type.string,
doublePrecision: type.number.atLeast(CONSTANTS.INT48_MIN).atMost(CONSTANTS.INT48_MAX),
geometry1: type([type.number, type.number]),
geometry2: type({ x: type.number, y: type.number }),
halfvec: type.number.array().exactlyLength(3),
inet: type.string,
integer: type.keywords.number.integer.atLeast(CONSTANTS.INT32_MIN).atMost(CONSTANTS.INT32_MAX),
interval: type.string,
json: jsonSchema,
jsonb: jsonSchema,
line1: type({ a: type.number, b: type.number, c: type.number }),
line2: type([type.number, type.number, type.number]),
macaddr: type.string,
macaddr8: type.string,
numeric: type.string,
point1: type({ x: type.number, y: type.number }),
point2: type([type.number, type.number]),
real: type.number.atLeast(CONSTANTS.INT24_MIN).atMost(CONSTANTS.INT24_MAX),
serial: type.keywords.number.integer.atLeast(CONSTANTS.INT32_MIN).atMost(CONSTANTS.INT32_MAX),
smallint: type.keywords.number.integer.atLeast(CONSTANTS.INT16_MIN).atMost(CONSTANTS.INT16_MAX),
smallserial: type.keywords.number.integer.atLeast(CONSTANTS.INT16_MIN).atMost(CONSTANTS.INT16_MAX),
text1: type.string,
text2: type.enumerated('a', 'b', 'c'),
sparsevec: type.string,
time: type.string,
timestamp1: type.Date,
timestamp2: type.string,
uuid: type(/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/iu).describe('a RFC-4122-compliant UUID'),
varchar1: type.string.atMostLength(10),
varchar2: type.enumerated('a', 'b', 'c'),
vector: type.number.array().exactlyLength(3),
array1: integerSchema.array(),
array2: integerSchema.array().array().exactlyLength(2),
array3: type.string.atMostLength(10).array().array().exactlyLength(2),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
/* Infinitely recursive type */ {
const TopLevelCondition: Type<TopLevelCondition, {}> = type('unknown.any') as any;
const table = pgTable('test', {
json: json().$type<TopLevelCondition>().notNull(),
jsonb: jsonb().$type<TopLevelCondition>(),
});
const result = createSelectSchema(table);
const expected = type({
json: TopLevelCondition,
jsonb: TopLevelCondition.or(type.null),
});
Expect<Equal<type.infer<typeof result>, type.infer<typeof expected>>>();
}
/* Disallow unknown keys in table refinement - select */ {
const table = pgTable('test', { id: integer() });
// @ts-expect-error
createSelectSchema(table, { unknown: type.string });
}
/* Disallow unknown keys in table refinement - insert */ {
const table = pgTable('test', { id: integer() });
// @ts-expect-error
createInsertSchema(table, { unknown: type.string });
}
/* Disallow unknown keys in table refinement - update */ {
const table = pgTable('test', { id: integer() });
// @ts-expect-error
createUpdateSchema(table, { unknown: type.string });
}
/* Disallow unknown keys in view qb - select */ {
const table = pgTable('test', { id: integer() });
const view = pgView('test').as((qb) => qb.select().from(table));
const mView = pgMaterializedView('test').as((qb) => qb.select().from(table));
const nestedSelect = pgView('test').as((qb) => qb.select({ table }).from(table));
// @ts-expect-error
createSelectSchema(view, { unknown: type.string });
// @ts-expect-error
createSelectSchema(mView, { unknown: type.string });
// @ts-expect-error
createSelectSchema(nestedSelect, { table: { unknown: type.string } });
}
/* Disallow unknown keys in view columns - select */ {
const view = pgView('test', { id: integer() }).as(sql``);
const mView = pgView('test', { id: integer() }).as(sql``);
// @ts-expect-error
createSelectSchema(view, { unknown: type.string });
// @ts-expect-error
createSelectSchema(mView, { unknown: type.string });
}
+503
View File
@@ -0,0 +1,503 @@
import { Type, type } from 'arktype';
import { type Equal } from 'drizzle-orm';
import { customType, int, json, serial, singlestoreSchema, singlestoreTable, text } from 'drizzle-orm/singlestore-core';
import type { TopLevelCondition } from 'json-rules-engine';
import { test } from 'vitest';
import { bigintNarrow, jsonSchema, unsignedBigintNarrow } from '~/column.ts';
import { CONSTANTS } from '~/constants.ts';
import { createInsertSchema, createSelectSchema, createUpdateSchema } from '../src';
import { Expect, expectSchemaShape } from './utils.ts';
const intSchema = type.keywords.number.integer.atLeast(CONSTANTS.INT32_MIN).atMost(CONSTANTS.INT32_MAX);
const serialNumberModeSchema = type.keywords.number.integer.atLeast(0).atMost(Number.MAX_SAFE_INTEGER);
const textSchema = type.string.atMostLength(CONSTANTS.INT16_UNSIGNED_MAX);
test('table - select', (t) => {
const table = singlestoreTable('test', {
id: serial().primaryKey(),
name: text().notNull(),
});
const result = createSelectSchema(table);
const expected = type({ id: serialNumberModeSchema, name: textSchema });
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('table in schema - select', (tc) => {
const schema = singlestoreSchema('test');
const table = schema.table('test', {
id: serial().primaryKey(),
name: text().notNull(),
});
const result = createSelectSchema(table);
const expected = type({ id: serialNumberModeSchema, name: textSchema });
expectSchemaShape(tc, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('table - insert', (t) => {
const table = singlestoreTable('test', {
id: serial().primaryKey(),
name: text().notNull(),
age: int(),
});
const result = createInsertSchema(table);
const expected = type({
id: serialNumberModeSchema.optional(),
name: textSchema,
age: intSchema.or(type.null).optional(),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('table - update', (t) => {
const table = singlestoreTable('test', {
id: serial().primaryKey(),
name: text().notNull(),
age: int(),
});
const result = createUpdateSchema(table);
const expected = type({
id: serialNumberModeSchema.optional(),
name: textSchema.optional(),
age: intSchema.or(type.null).optional(),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
// TODO: SingleStore doesn't support views yet. Add these tests when they're added
// test('view qb - select', (t) => {
// const table = singlestoreTable('test', {
// id: serial().primaryKey(),
// name: text().notNull(),
// });
// const view = mysqlView('test').as((qb) => qb.select({ id: table.id, age: sql``.as('age') }).from(table));
// const result = createSelectSchema(view);
// const expected = v.object({ id: serialNumberModeSchema, age: v.any() });
// expectSchemaShape(t, expected).from(result);
// Expect<Equal<typeof result, typeof expected>>();
// });
// test('view columns - select', (t) => {
// const view = mysqlView('test', {
// id: serial().primaryKey(),
// name: text().notNull(),
// }).as(sql``);
// const result = createSelectSchema(view);
// const expected = v.object({ id: serialNumberModeSchema, name: textSchema });
// expectSchemaShape(t, expected).from(result);
// Expect<Equal<typeof result, typeof expected>>();
// });
// test('view with nested fields - select', (t) => {
// const table = singlestoreTable('test', {
// id: serial().primaryKey(),
// name: text().notNull(),
// });
// const view = mysqlView('test').as((qb) =>
// qb.select({
// id: table.id,
// nested: {
// name: table.name,
// age: sql``.as('age'),
// },
// table,
// }).from(table)
// );
// const result = createSelectSchema(view);
// const expected = v.object({
// id: serialNumberModeSchema,
// nested: v.object({ name: textSchema, age: v.any() }),
// table: v.object({ id: serialNumberModeSchema, name: textSchema }),
// });
// expectSchemaShape(t, expected).from(result);
// Expect<Equal<typeof result, typeof expected>>();
// });
test('nullability - select', (t) => {
const table = singlestoreTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().default(1),
c4: int().notNull().default(1),
});
const result = createSelectSchema(table);
const expected = type({
c1: intSchema.or(type.null),
c2: intSchema,
c3: intSchema.or(type.null),
c4: intSchema,
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('nullability - insert', (t) => {
const table = singlestoreTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().default(1),
c4: int().notNull().default(1),
c5: int().generatedAlwaysAs(1),
});
const result = createInsertSchema(table);
const expected = type({
c1: intSchema.or(type.null).optional(),
c2: intSchema,
c3: intSchema.or(type.null).optional(),
c4: intSchema.optional(),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('nullability - update', (t) => {
const table = singlestoreTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().default(1),
c4: int().notNull().default(1),
c5: int().generatedAlwaysAs(1),
});
const result = createUpdateSchema(table);
const expected = type({
c1: intSchema.or(type.null).optional(),
c2: intSchema.optional(),
c3: intSchema.or(type.null).optional(),
c4: intSchema.optional(),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - select', (t) => {
const table = singlestoreTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().notNull(),
});
const result = createSelectSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
});
const expected = type({
c1: intSchema.or(type.null),
c2: intSchema.atMost(1000),
c3: type.string.pipe(Number),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - select with custom data type', (t) => {
const customText = customType({ dataType: () => 'text' });
const table = singlestoreTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().notNull(),
c4: customText(),
});
const customTextSchema = type.string.atLeastLength(1).atMostLength(100);
const result = createSelectSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
c4: customTextSchema,
});
const expected = type({
c1: intSchema.or(type.null),
c2: intSchema.atMost(1000),
c3: type.string.pipe(Number),
c4: customTextSchema,
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - insert', (t) => {
const table = singlestoreTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().notNull(),
c4: int().generatedAlwaysAs(1),
});
const result = createInsertSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
});
const expected = type({
c1: intSchema.or(type.null).optional(),
c2: intSchema.atMost(1000),
c3: type.string.pipe(Number),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - update', (t) => {
const table = singlestoreTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().notNull(),
c4: int().generatedAlwaysAs(1),
});
const result = createUpdateSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
});
const expected = type({
c1: intSchema.or(type.null).optional(),
c2: intSchema.atMost(1000).optional(),
c3: type.string.pipe(Number),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
// test('refine view - select', (t) => {
// const table = singlestoreTable('test', {
// c1: int(),
// c2: int(),
// c3: int(),
// c4: int(),
// c5: int(),
// c6: int(),
// });
// const view = mysqlView('test').as((qb) =>
// qb.select({
// c1: table.c1,
// c2: table.c2,
// c3: table.c3,
// nested: {
// c4: table.c4,
// c5: table.c5,
// c6: table.c6,
// },
// table,
// }).from(table)
// );
// const result = createSelectSchema(view, {
// c2: (schema) => v.pipe(schema, v.maxValue(1000)),
// c3: v.pipe(type.string, v.transform(Number)),
// nested: {
// c5: (schema) => v.pipe(schema, v.maxValue(1000)),
// c6: v.pipe(type.string, v.transform(Number)),
// },
// table: {
// c2: (schema) => v.pipe(schema, v.maxValue(1000)),
// c3: v.pipe(type.string, v.transform(Number)),
// },
// });
// const expected = v.object({
// c1: v.nullable(intSchema),
// c2: v.nullable(v.pipe(intSchema, v.maxValue(1000))),
// c3: v.pipe(type.string, v.transform(Number)),
// nested: v.object({
// c4: v.nullable(intSchema),
// c5: v.nullable(v.pipe(intSchema, v.maxValue(1000))),
// c6: v.pipe(type.string, v.transform(Number)),
// }),
// table: v.object({
// c1: v.nullable(intSchema),
// c2: v.nullable(v.pipe(intSchema, v.maxValue(1000))),
// c3: v.pipe(type.string, v.transform(Number)),
// c4: v.nullable(intSchema),
// c5: v.nullable(intSchema),
// c6: v.nullable(intSchema),
// }),
// });
// expectSchemaShape(t, expected).from(result);
// Expect<Equal<typeof result, typeof expected>>();
// });
test('all data types', (t) => {
const table = singlestoreTable('test', ({
bigint,
binary,
boolean,
char,
date,
datetime,
decimal,
double,
float,
int,
json,
mediumint,
singlestoreEnum,
real,
serial,
smallint,
text,
time,
timestamp,
tinyint,
varchar,
varbinary,
year,
longtext,
mediumtext,
tinytext,
}) => ({
bigint1: bigint({ mode: 'number' }).notNull(),
bigint2: bigint({ mode: 'bigint' }).notNull(),
bigint3: bigint({ unsigned: true, mode: 'number' }).notNull(),
bigint4: bigint({ unsigned: true, mode: 'bigint' }).notNull(),
binary: binary({ length: 10 }).notNull(),
boolean: boolean().notNull(),
char1: char({ length: 10 }).notNull(),
char2: char({ length: 1, enum: ['a', 'b', 'c'] }).notNull(),
date1: date({ mode: 'date' }).notNull(),
date2: date({ mode: 'string' }).notNull(),
datetime1: datetime({ mode: 'date' }).notNull(),
datetime2: datetime({ mode: 'string' }).notNull(),
decimal1: decimal().notNull(),
decimal2: decimal({ unsigned: true }).notNull(),
double1: double().notNull(),
double2: double({ unsigned: true }).notNull(),
float1: float().notNull(),
float2: float({ unsigned: true }).notNull(),
int1: int().notNull(),
int2: int({ unsigned: true }).notNull(),
json: json().notNull(),
mediumint1: mediumint().notNull(),
mediumint2: mediumint({ unsigned: true }).notNull(),
enum: singlestoreEnum('enum', ['a', 'b', 'c']).notNull(),
real: real().notNull(),
serial: serial().notNull(),
smallint1: smallint().notNull(),
smallint2: smallint({ unsigned: true }).notNull(),
text1: text().notNull(),
text2: text({ enum: ['a', 'b', 'c'] }).notNull(),
time: time().notNull(),
timestamp1: timestamp({ mode: 'date' }).notNull(),
timestamp2: timestamp({ mode: 'string' }).notNull(),
tinyint1: tinyint().notNull(),
tinyint2: tinyint({ unsigned: true }).notNull(),
varchar1: varchar({ length: 10 }).notNull(),
varchar2: varchar({ length: 1, enum: ['a', 'b', 'c'] }).notNull(),
varbinary: varbinary({ length: 10 }).notNull(),
year: year().notNull(),
longtext1: longtext().notNull(),
longtext2: longtext({ enum: ['a', 'b', 'c'] }).notNull(),
mediumtext1: mediumtext().notNull(),
mediumtext2: mediumtext({ enum: ['a', 'b', 'c'] }).notNull(),
tinytext1: tinytext().notNull(),
tinytext2: tinytext({ enum: ['a', 'b', 'c'] }).notNull(),
}));
const result = createSelectSchema(table);
const expected = type({
bigint1: type.keywords.number.integer.atLeast(Number.MIN_SAFE_INTEGER).atMost(Number.MAX_SAFE_INTEGER),
bigint2: type.bigint.narrow(bigintNarrow),
bigint3: type.keywords.number.integer.atLeast(0).atMost(Number.MAX_SAFE_INTEGER),
bigint4: type.bigint.narrow(unsignedBigintNarrow),
binary: type.string,
boolean: type.boolean,
char1: type.string.exactlyLength(10),
char2: type.enumerated('a', 'b', 'c'),
date1: type.Date,
date2: type.string,
datetime1: type.Date,
datetime2: type.string,
decimal1: type.string,
decimal2: type.string,
double1: type.number.atLeast(CONSTANTS.INT48_MIN).atMost(CONSTANTS.INT48_MAX),
double2: type.number.atLeast(0).atMost(CONSTANTS.INT48_UNSIGNED_MAX),
float1: type.number.atLeast(CONSTANTS.INT24_MIN).atMost(CONSTANTS.INT24_MAX),
float2: type.number.atLeast(0).atMost(CONSTANTS.INT24_UNSIGNED_MAX),
int1: type.keywords.number.integer.atLeast(CONSTANTS.INT32_MIN).atMost(CONSTANTS.INT32_MAX),
int2: type.keywords.number.integer.atLeast(0).atMost(CONSTANTS.INT32_UNSIGNED_MAX),
json: jsonSchema,
mediumint1: type.keywords.number.integer.atLeast(CONSTANTS.INT24_MIN).atMost(CONSTANTS.INT24_MAX),
mediumint2: type.keywords.number.integer.atLeast(0).atMost(CONSTANTS.INT24_UNSIGNED_MAX),
enum: type.enumerated('a', 'b', 'c'),
real: type.number.atLeast(CONSTANTS.INT48_MIN).atMost(CONSTANTS.INT48_MAX),
serial: type.keywords.number.integer.atLeast(0).atMost(Number.MAX_SAFE_INTEGER),
smallint1: type.keywords.number.integer.atLeast(CONSTANTS.INT16_MIN).atMost(CONSTANTS.INT16_MAX),
smallint2: type.keywords.number.integer.atLeast(0).atMost(CONSTANTS.INT16_UNSIGNED_MAX),
text1: type.string.atMostLength(CONSTANTS.INT16_UNSIGNED_MAX),
text2: type.enumerated('a', 'b', 'c'),
time: type.string,
timestamp1: type.Date,
timestamp2: type.string,
tinyint1: type.keywords.number.integer.atLeast(CONSTANTS.INT8_MIN).atMost(CONSTANTS.INT8_MAX),
tinyint2: type.keywords.number.integer.atLeast(0).atMost(CONSTANTS.INT8_UNSIGNED_MAX),
varchar1: type.string.atMostLength(10),
varchar2: type.enumerated('a', 'b', 'c'),
varbinary: type.string,
year: type.keywords.number.integer.atLeast(1901).atMost(2155),
longtext1: type.string.atMostLength(CONSTANTS.INT32_UNSIGNED_MAX),
longtext2: type.enumerated('a', 'b', 'c'),
mediumtext1: type.string.atMostLength(CONSTANTS.INT24_UNSIGNED_MAX),
mediumtext2: type.enumerated('a', 'b', 'c'),
tinytext1: type.string.atMostLength(CONSTANTS.INT8_UNSIGNED_MAX),
tinytext2: type.enumerated('a', 'b', 'c'),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
/* Infinitely recursive type */ {
const TopLevelCondition: Type<TopLevelCondition, {}> = type('unknown.any') as any;
const table = singlestoreTable('test', {
json: json().$type<TopLevelCondition>(),
});
const result = createSelectSchema(table);
const expected = type({
json: TopLevelCondition.or(type.null),
});
Expect<Equal<type.infer<typeof result>, type.infer<typeof expected>>>();
}
/* Disallow unknown keys in table refinement - select */ {
const table = singlestoreTable('test', { id: int() });
// @ts-expect-error
createSelectSchema(table, { unknown: type.string });
}
/* Disallow unknown keys in table refinement - insert */ {
const table = singlestoreTable('test', { id: int() });
// @ts-expect-error
createInsertSchema(table, { unknown: type.string });
}
/* Disallow unknown keys in table refinement - update */ {
const table = singlestoreTable('test', { id: int() });
// @ts-expect-error
createUpdateSchema(table, { unknown: type.string });
}
// /* Disallow unknown keys in view qb - select */ {
// const table = singlestoreTable('test', { id: int() });
// const view = mysqlView('test').as((qb) => qb.select().from(table));
// const nestedSelect = mysqlView('test').as((qb) => qb.select({ table }).from(table));
// // @ts-expect-error
// createSelectSchema(view, { unknown: type.string });
// // @ts-expect-error
// createSelectSchema(nestedSelect, { table: { unknown: type.string } });
// }
// /* Disallow unknown keys in view columns - select */ {
// const view = mysqlView('test', { id: int() }).as(sql``);
// // @ts-expect-error
// createSelectSchema(view, { unknown: type.string });
// }
+400
View File
@@ -0,0 +1,400 @@
import { Type, type } from 'arktype';
import { type Equal, sql } from 'drizzle-orm';
import { blob, customType, int, sqliteTable, sqliteView, text } from 'drizzle-orm/sqlite-core';
import type { TopLevelCondition } from 'json-rules-engine';
import { test } from 'vitest';
import { bigintNarrow, bufferSchema, jsonSchema } from '~/column.ts';
import { CONSTANTS } from '~/constants.ts';
import { createInsertSchema, createSelectSchema, createUpdateSchema } from '../src';
import { Expect, expectSchemaShape } from './utils.ts';
const intSchema = type.keywords.number.integer.atLeast(Number.MIN_SAFE_INTEGER).atMost(Number.MAX_SAFE_INTEGER);
const textSchema = type.string;
test('table - select', (t) => {
const table = sqliteTable('test', {
id: int().primaryKey({ autoIncrement: true }),
name: text().notNull(),
});
const result = createSelectSchema(table);
const expected = type({ id: intSchema, name: textSchema });
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('table - insert', (t) => {
const table = sqliteTable('test', {
id: int().primaryKey({ autoIncrement: true }),
name: text().notNull(),
age: int(),
});
const result = createInsertSchema(table);
const expected = type({ id: intSchema.optional(), name: textSchema, age: intSchema.or(type.null).optional() });
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('table - update', (t) => {
const table = sqliteTable('test', {
id: int().primaryKey({ autoIncrement: true }),
name: text().notNull(),
age: int(),
});
const result = createUpdateSchema(table);
const expected = type({
id: intSchema.optional(),
name: textSchema.optional(),
age: intSchema.or(type.null).optional(),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('view qb - select', (t) => {
const table = sqliteTable('test', {
id: int().primaryKey({ autoIncrement: true }),
name: text().notNull(),
});
const view = sqliteView('test').as((qb) => qb.select({ id: table.id, age: sql``.as('age') }).from(table));
const result = createSelectSchema(view);
const expected = type({ id: intSchema, age: type('unknown.any') });
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('view columns - select', (t) => {
const view = sqliteView('test', {
id: int().primaryKey({ autoIncrement: true }),
name: text().notNull(),
}).as(sql``);
const result = createSelectSchema(view);
const expected = type({ id: intSchema, name: textSchema });
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('view with nested fields - select', (t) => {
const table = sqliteTable('test', {
id: int().primaryKey({ autoIncrement: true }),
name: text().notNull(),
});
const view = sqliteView('test').as((qb) =>
qb.select({
id: table.id,
nested: {
name: table.name,
age: sql``.as('age'),
},
table,
}).from(table)
);
const result = createSelectSchema(view);
const expected = type({
id: intSchema,
nested: type({ name: textSchema, age: type('unknown.any') }),
table: type({ id: intSchema, name: textSchema }),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('nullability - select', (t) => {
const table = sqliteTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().default(1),
c4: int().notNull().default(1),
});
const result = createSelectSchema(table);
const expected = type({
c1: intSchema.or(type.null),
c2: intSchema,
c3: intSchema.or(type.null),
c4: intSchema,
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('nullability - insert', (t) => {
const table = sqliteTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().default(1),
c4: int().notNull().default(1),
c5: int().generatedAlwaysAs(1),
});
const result = createInsertSchema(table);
const expected = type({
c1: intSchema.or(type.null).optional(),
c2: intSchema,
c3: intSchema.or(type.null).optional(),
c4: intSchema.optional(),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('nullability - update', (t) => {
const table = sqliteTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().default(1),
c4: int().notNull().default(1),
c5: int().generatedAlwaysAs(1),
});
const result = createUpdateSchema(table);
const expected = type({
c1: intSchema.or(type.null).optional(),
c2: intSchema.optional(),
c3: intSchema.or(type.null).optional(),
c4: intSchema.optional(),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - select', (t) => {
const table = sqliteTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().notNull(),
});
const result = createSelectSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
});
const expected = type({
c1: intSchema.or(type.null),
c2: intSchema.atMost(1000),
c3: type.string.pipe(Number),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - select with custom data type', (t) => {
const customText = customType({ dataType: () => 'text' });
const table = sqliteTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().notNull(),
c4: customText(),
});
const customTextSchema = type.string.atLeastLength(1).atMostLength(100);
const result = createSelectSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
c4: customTextSchema,
});
const expected = type({
c1: intSchema.or(type.null),
c2: intSchema.atMost(1000),
c3: type.string.pipe(Number),
c4: customTextSchema,
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - insert', (t) => {
const table = sqliteTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().notNull(),
c4: int().generatedAlwaysAs(1),
});
const result = createInsertSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
});
const expected = type({
c1: intSchema.or(type.null).optional(),
c2: intSchema.atMost(1000),
c3: type.string.pipe(Number),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine table - update', (t) => {
const table = sqliteTable('test', {
c1: int(),
c2: int().notNull(),
c3: int().notNull(),
c4: int().generatedAlwaysAs(1),
});
const result = createUpdateSchema(table, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
});
const expected = type({
c1: intSchema.or(type.null).optional(),
c2: intSchema.atMost(1000).optional(),
c3: type.string.pipe(Number),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('refine view - select', (t) => {
const table = sqliteTable('test', {
c1: int(),
c2: int(),
c3: int(),
c4: int(),
c5: int(),
c6: int(),
});
const view = sqliteView('test').as((qb) =>
qb.select({
c1: table.c1,
c2: table.c2,
c3: table.c3,
nested: {
c4: table.c4,
c5: table.c5,
c6: table.c6,
},
table,
}).from(table)
);
const result = createSelectSchema(view, {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
nested: {
c5: (schema) => schema.atMost(1000),
c6: type.string.pipe(Number),
},
table: {
c2: (schema) => schema.atMost(1000),
c3: type.string.pipe(Number),
},
});
const expected = type({
c1: intSchema.or(type.null),
c2: intSchema.atMost(1000).or(type.null),
c3: type.string.pipe(Number),
nested: type({
c4: intSchema.or(type.null),
c5: intSchema.atMost(1000).or(type.null),
c6: type.string.pipe(Number),
}),
table: type({
c1: intSchema.or(type.null),
c2: intSchema.atMost(1000).or(type.null),
c3: type.string.pipe(Number),
c4: intSchema.or(type.null),
c5: intSchema.or(type.null),
c6: intSchema.or(type.null),
}),
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
test('all data types', (t) => {
const table = sqliteTable('test', ({
blob,
integer,
numeric,
real,
text,
}) => ({
blob1: blob({ mode: 'buffer' }).notNull(),
blob2: blob({ mode: 'bigint' }).notNull(),
blob3: blob({ mode: 'json' }).notNull(),
integer1: integer({ mode: 'number' }).notNull(),
integer2: integer({ mode: 'boolean' }).notNull(),
integer3: integer({ mode: 'timestamp' }).notNull(),
integer4: integer({ mode: 'timestamp_ms' }).notNull(),
numeric: numeric().notNull(),
real: real().notNull(),
text1: text({ mode: 'text' }).notNull(),
text2: text({ mode: 'text', length: 10 }).notNull(),
text3: text({ mode: 'text', enum: ['a', 'b', 'c'] }).notNull(),
text4: text({ mode: 'json' }).notNull(),
}));
const result = createSelectSchema(table);
const expected = type({
blob1: bufferSchema,
blob2: type.bigint.narrow(bigintNarrow),
blob3: jsonSchema,
integer1: type.keywords.number.integer.atLeast(Number.MIN_SAFE_INTEGER).atMost(Number.MAX_SAFE_INTEGER),
integer2: type.boolean,
integer3: type.Date,
integer4: type.Date,
numeric: type.string,
real: type.number.atLeast(CONSTANTS.INT48_MIN).atMost(CONSTANTS.INT48_MAX),
text1: type.string,
text2: type.string.atMostLength(10),
text3: type.enumerated('a', 'b', 'c'),
text4: jsonSchema,
});
expectSchemaShape(t, expected).from(result);
Expect<Equal<typeof result, typeof expected>>();
});
/* Infinitely recursive type */ {
const TopLevelCondition: Type<TopLevelCondition, {}> = type('unknown.any') as any;
const table = sqliteTable('test', {
json1: text({ mode: 'json' }).$type<TopLevelCondition>().notNull(),
json2: blob({ mode: 'json' }).$type<TopLevelCondition>(),
});
const result = createSelectSchema(table);
const expected = type({
json1: TopLevelCondition,
json2: TopLevelCondition.or(type.null),
});
Expect<Equal<type.infer<typeof result>, type.infer<typeof expected>>>();
}
/* Disallow unknown keys in table refinement - select */ {
const table = sqliteTable('test', { id: int() });
// @ts-expect-error
createSelectSchema(table, { unknown: type.string });
}
/* Disallow unknown keys in table refinement - insert */ {
const table = sqliteTable('test', { id: int() });
// @ts-expect-error
createInsertSchema(table, { unknown: type.string });
}
/* Disallow unknown keys in table refinement - update */ {
const table = sqliteTable('test', { id: int() });
// @ts-expect-error
createUpdateSchema(table, { unknown: type.string });
}
/* Disallow unknown keys in view qb - select */ {
const table = sqliteTable('test', { id: int() });
const view = sqliteView('test').as((qb) => qb.select().from(table));
const nestedSelect = sqliteView('test').as((qb) => qb.select({ table }).from(table));
// @ts-expect-error
createSelectSchema(view, { unknown: type.string });
// @ts-expect-error
createSelectSchema(nestedSelect, { table: { unknown: type.string } });
}
/* Disallow unknown keys in view columns - select */ {
const view = sqliteView('test', { id: int() }).as(sql``);
// @ts-expect-error
createSelectSchema(view, { unknown: type.string });
}
+11
View File
@@ -0,0 +1,11 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"module": "esnext",
"target": "esnext",
"noEmit": true,
"rootDir": "..",
"outDir": "./.cache"
},
"include": [".", "../src"]
}
+15
View File
@@ -0,0 +1,15 @@
import { Type } from 'arktype';
import { expect, type TaskContext } from 'vitest';
export function expectSchemaShape<T extends Type<any, any>>(t: TaskContext, expected: T) {
return {
from(actual: T) {
expect(actual.json).toStrictEqual(expected.json);
expect(actual.expression).toStrictEqual(expected.expression);
},
};
}
export const expectEnumValues = expectSchemaShape;
export function Expect<_ extends true>() {}
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"rootDir": "src"
},
"include": ["src"]
}
+13
View File
@@ -0,0 +1,13 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "dist",
"baseUrl": ".",
"declaration": true,
"noEmit": true,
"paths": {
"~/*": ["src/*"]
}
},
"include": ["src", "*.ts", "benchmarks"]
}
+25
View File
@@ -0,0 +1,25 @@
import tsconfigPaths from 'vite-tsconfig-paths';
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: [
'tests/**/*.test.ts',
],
exclude: [
'tests/bun/**/*',
],
typecheck: {
tsconfig: 'tsconfig.json',
},
testTimeout: 100000,
hookTimeout: 100000,
isolate: false,
poolOptions: {
threads: {
singleThread: true,
},
},
},
plugins: [tsconfigPaths()],
});