orchid-orm 1.14.4 → 1.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +0 -1
- package/dist/bin.js.map +1 -1
- package/dist/index.d.ts +77 -113
- package/dist/index.js +757 -480
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +759 -482
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/dist/bin.js
CHANGED
|
@@ -110,7 +110,6 @@ const setupPackageJson = async (config) => {
|
|
|
110
110
|
getLatestPackageVersion("dotenv", "dependencies"),
|
|
111
111
|
getLatestPackageVersion("orchid-orm", "dependencies"),
|
|
112
112
|
getLatestPackageVersion("pqb", "dependencies"),
|
|
113
|
-
getLatestPackageVersion("pg", "dependencies"),
|
|
114
113
|
config.addSchemaToZod && getLatestPackageVersion("orchid-orm-schema-to-zod", "dependencies"),
|
|
115
114
|
getLatestPackageVersion("rake-db", "devDependencies"),
|
|
116
115
|
config.addTestFactory && getLatestPackageVersion("orchid-orm-test-factory", "devDependencies"),
|
package/dist/bin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bin.js","sources":["../src/bin/init.ts","../src/bin/bin.ts"],"sourcesContent":["import fs from 'fs/promises';\nimport { resolve, join, relative } from 'path';\nimport https from 'https';\nimport prompts from 'prompts';\n\nexport type InitConfig = {\n path: string;\n hasTsConfig: boolean;\n testDatabase?: boolean;\n addSchemaToZod?: boolean;\n addTestFactory?: boolean;\n demoTables?: boolean;\n timestamp?: 'date' | 'number';\n swc?: boolean;\n};\n\ntype DependencyKind = 'dependencies' | 'devDependencies';\n\nexport const askOrchidORMConfig = async () => {\n let cancelled = false;\n\n const response = await prompts(\n [\n {\n type: 'text',\n name: 'path',\n message: 'Where would you like to install Orchid ORM?',\n initial: process.cwd(),\n },\n {\n type: 'select',\n name: 'timestamp',\n message: 'Preferred type of returned timestamps:',\n choices: [\n {\n title: 'string (as returned from db)',\n },\n {\n title: 'number (epoch)',\n value: 'number',\n },\n {\n title: 'Date object',\n value: 'date',\n },\n ],\n },\n {\n type: 'confirm',\n name: 'testDatabase',\n message: 'Should I add a separate database for tests?',\n },\n {\n type: 'confirm',\n name: 'addSchemaToZod',\n message: 'Are you going to use Zod for validation?',\n },\n {\n type: 'confirm',\n name: 'addTestFactory',\n message: 'Do you want object factories for writing tests?',\n },\n {\n type: 'confirm',\n name: 'demoTables',\n message: 'Should I add demo tables?',\n },\n ],\n {\n onCancel() {\n cancelled = true;\n },\n },\n );\n\n if (cancelled) return;\n\n const tsConfigPath = join(response.path, 'tsconfig.json');\n const hasTsConfig = await readFileSafe(tsConfigPath);\n (response as InitConfig).hasTsConfig = !!hasTsConfig;\n\n if (!hasTsConfig) {\n const res = await prompts(\n [\n {\n type: 'confirm',\n name: 'swc',\n initial: true,\n message: `Let's add fast TS compiler swc?`,\n },\n ],\n {\n onCancel() {\n cancelled = true;\n },\n },\n );\n\n if (cancelled) return;\n\n (response as InitConfig).swc = res.swc;\n }\n\n return response as InitConfig;\n};\n\nexport const initOrchidORM = async (config: InitConfig) => {\n config.path = resolve(config.path);\n const dirPath = join(config.path, 'src', 'db');\n\n await fs.mkdir(dirPath, { recursive: true });\n\n await setupPackageJson(config);\n await setupTSConfig(config);\n await setupEnv(config);\n await setupGitIgnore(config);\n await setupBaseTable(config, dirPath);\n await setupTables(config, dirPath);\n await setupConfig(config, dirPath);\n await setupMainDb(config, dirPath);\n await setupMigrationScript(config, dirPath);\n await createMigrations(config, dirPath);\n await createSeed(config, dirPath);\n\n greet(config);\n};\n\nconst setupPackageJson = async (config: InitConfig) => {\n const pairs = await Promise.all([\n getLatestPackageVersion('dotenv', 'dependencies'),\n getLatestPackageVersion('orchid-orm', 'dependencies'),\n getLatestPackageVersion('pqb', 'dependencies'),\n getLatestPackageVersion('pg', 'dependencies'),\n config.addSchemaToZod &&\n getLatestPackageVersion('orchid-orm-schema-to-zod', 'dependencies'),\n getLatestPackageVersion('rake-db', 'devDependencies'),\n config.addTestFactory &&\n getLatestPackageVersion('orchid-orm-test-factory', 'devDependencies'),\n config.swc && getLatestPackageVersion('@swc/core', 'devDependencies'),\n getLatestPackageVersion('@types/node', 'devDependencies'),\n getLatestPackageVersion('ts-node', 'devDependencies'),\n getLatestPackageVersion('typescript', 'devDependencies'),\n ]);\n\n const deps: Record<string, string> = {};\n const devDeps: Record<string, string> = {};\n for (const item of pairs) {\n if (!item) continue;\n const [key, { version, kind }] = item;\n (kind === 'dependencies' ? deps : devDeps)[key] = version;\n }\n\n const packageJsonPath = join(config.path, 'package.json');\n const content = await readFileSafe(packageJsonPath);\n const json = content ? JSON.parse(content) : {};\n\n if (!json.scripts) json.scripts = {};\n json.scripts.db = 'ts-node src/db/dbScript.ts';\n\n if (!json.dependencies) json.dependencies = {};\n\n for (const key in deps) {\n json.dependencies[key] = deps[key];\n }\n\n if (!json.devDependencies) json.devDependencies = {};\n for (const key in devDeps) {\n json.devDependencies[key] = devDeps[key];\n }\n\n await fs.writeFile(packageJsonPath, JSON.stringify(json, null, ' ') + '\\n');\n};\n\nconst getLatestPackageVersion = (\n name: string,\n kind: DependencyKind,\n): Promise<[string, { version: string; kind: DependencyKind }]> => {\n return new Promise((resolve, reject) => {\n https\n .get(`https://registry.npmjs.org/${name}/latest`, (res) => {\n let data = '';\n res.on('data', (chunk) => (data += chunk));\n res.on('end', () =>\n resolve([name, { version: `^${JSON.parse(data).version}`, kind }]),\n );\n })\n .on('error', reject);\n });\n};\n\nconst readFileSafe = async (path: string) => {\n try {\n return await fs.readFile(path, 'utf-8');\n } catch (err) {\n if ((err as unknown as { code: string }).code === 'ENOENT') {\n return undefined;\n }\n throw err;\n }\n};\n\nconst setupTSConfig = async (config: InitConfig) => {\n if (config.hasTsConfig) return;\n\n const tsConfigPath = join(config.path, 'tsconfig.json');\n await fs.writeFile(\n tsConfigPath,\n `{${\n config.swc\n ? `\n \"ts-node\": {\n \"swc\": true\n },`\n : ''\n }\n \"compilerOptions\": {\n \"strict\": true\n }\n}\n`,\n );\n};\n\nconst setupEnv = async (config: InitConfig) => {\n const envPath = join(config.path, '.env');\n let content = ((await readFileSafe(envPath)) || '').trim();\n let changed = false;\n\n if (!content.match(/^DATABASE_URL=/m)) {\n content += `\\nDATABASE_URL=postgres://user:password@localhost:5432/dbname?ssl=false`;\n changed = true;\n }\n\n if (config.testDatabase && !content.match(/^DATABASE_TEST_URL=/m)) {\n content += `\\nDATABASE_TEST_URL=postgres://user:password@localhost:5432/dbname-test?ssl=false`;\n changed = true;\n }\n\n if (changed) {\n await fs.writeFile(envPath, `${content.trim()}\\n`);\n }\n};\n\nconst setupGitIgnore = async (config: InitConfig) => {\n const gitignorePath = join(config.path, '.gitignore');\n let content = ((await readFileSafe(gitignorePath)) || '').trim();\n let changed = false;\n\n if (!content.match(/^node_modules\\b/m)) {\n content += `\\nnode_modules`;\n changed = true;\n }\n\n if (!content.match(/^.env\\b/m)) {\n content += `\\n.env`;\n changed = true;\n }\n\n if (changed) {\n await fs.writeFile(gitignorePath, `${content.trim()}\\n`);\n }\n};\n\nconst setupBaseTable = async (config: InitConfig, dirPath: string) => {\n const filePath = join(dirPath, 'baseTable.ts');\n\n let content = `import { createBaseTable } from 'orchid-orm';\n\nexport const BaseTable = createBaseTable({\n columnTypes: (t) => ({\n ...t,\n text: (min = 0, max = Infinity) => t.text(min, max),`;\n\n const { timestamp } = config;\n if (timestamp) {\n content += `\n timestamp: <P extends number>(precision?: P) =>\n t.timestamp<P>(precision).${\n timestamp === 'date' ? 'asDate' : 'asNumber'\n }(),`;\n }\n\n content += `\n }),\n});\n`;\n\n await fs.writeFile(filePath, content);\n};\n\nconst setupTables = async (config: InitConfig, dirPath: string) => {\n if (!config.demoTables) return;\n\n const tablesDir = join(dirPath, 'tables');\n await fs.mkdir(tablesDir, { recursive: true });\n\n await fs.writeFile(\n join(tablesDir, 'post.table.ts'),\n `import { TableType } from 'orchid-orm';\nimport { BaseTable } from '../baseTable';\nimport { CommentTable } from './comment.table';\n${\n config.addSchemaToZod\n ? `import { tableToZod } from 'orchid-orm-schema-to-zod';\\n`\n : ''\n}\nexport type Post = TableType<PostTable>;\nexport class PostTable extends BaseTable {\n readonly table = 'post';\n columns = this.setColumns((t) => ({\n id: t.identity().primaryKey(),\n title: t.text(3, 100).unique(),\n text: t.text(20, 10000),\n ...t.timestamps(),\n }));\n\n relations = {\n comments: this.hasMany(() => CommentTable, {\n primaryKey: 'id',\n foreignKey: 'postId',\n }),\n };\n}\n${\n config.addSchemaToZod\n ? `\\nexport const postSchema = tableToZod(PostTable);\\n`\n : ''\n}`,\n );\n\n await fs.writeFile(\n join(tablesDir, 'comment.table.ts'),\n `import { TableType } from 'orchid-orm';\nimport { BaseTable } from '../baseTable';\nimport { PostTable } from './post.table';\n${\n config.addSchemaToZod\n ? `import { tableToZod } from 'orchid-orm-schema-to-zod';\\n`\n : ''\n}\nexport type Comment = TableType<CommentTable>;\nexport class CommentTable extends BaseTable {\n readonly table = 'comment';\n columns = this.setColumns((t) => ({\n id: t.identity().primaryKey(),\n postId: t\n .integer()\n .foreignKey(() => PostTable, 'id')\n .index(),\n text: t.text(5, 1000),\n ...t.timestamps(),\n }));\n\n relations = {\n post: this.belongsTo(() => PostTable, {\n primaryKey: 'id',\n foreignKey: 'postId',\n }),\n };\n}\n${\n config.addSchemaToZod\n ? `\\nexport const commentSchema = tableToZod(CommentTable);\\n`\n : ''\n}`,\n );\n};\n\nconst setupConfig = async (config: InitConfig, dirPath: string) => {\n const configPath = join(dirPath, 'config.ts');\n\n let content = `import 'dotenv/config';\n\nconst database = {\n databaseURL: process.env.DATABASE_URL,\n};\nif (!database.databaseURL) throw new Error('DATABASE_URL is missing in .env');`;\n\n if (config.testDatabase) {\n content += `\n\nconst testDatabase = {\n databaseURL: process.env.DATABASE_TEST_URL,\n};\n\nconst allDatabases = [database];\n\nif (testDatabase.databaseURL) {\n allDatabases.push(testDatabase);\n}`;\n }\n\n content += `\n\nexport const config = {`;\n\n if (config.testDatabase) {\n content += `\n allDatabases,`;\n }\n\n if (config.testDatabase) {\n content += `\n database: process.env.NODE_ENV === 'test' ? testDatabase : database,`;\n } else {\n content += `\n database,`;\n }\n content += `\n};\n`;\n\n await fs.writeFile(configPath, content);\n};\n\nconst setupMainDb = async (config: InitConfig, dirPath: string) => {\n let imports = '';\n let tables = '';\n if (config.demoTables) {\n imports += `\nimport { PostTable } from './tables/post.table';\nimport { CommentTable } from './tables/comment.table';`;\n tables += `\n post: PostTable,\n comment: CommentTable,`;\n }\n\n const dbPath = join(dirPath, 'db.ts');\n await fs.writeFile(\n dbPath,\n `import { orchidORM } from 'orchid-orm';\nimport { config } from './config';${imports}\n\nexport const db = orchidORM(config.database, {${tables}\n});\n`,\n );\n};\n\nconst setupMigrationScript = async (config: InitConfig, dirPath: string) => {\n const filePath = join(dirPath, 'dbScript.ts');\n await fs.writeFile(\n filePath,\n `import { rakeDb } from 'rake-db';\nimport { appCodeUpdater } from 'orchid-orm/codegen';\nimport { config } from './config';\nimport { BaseTable } from './baseTable';\n\nexport const change = rakeDb(${\n config.testDatabase ? 'config.allDatabases' : 'config.database'\n }, {\n baseTable: BaseTable,\n migrationsPath: './migrations',\n appCodeUpdater: appCodeUpdater({\n tablePath: (tableName) => \\`./tables/\\${tableName}.table.ts\\`,\n ormPath: './db.ts',\n }),\n useCodeUpdater: true, // set to false to disable code updater\n commands: {\n async seed() {\n const { seed } = await import('./seed');\n await seed();\n },\n },\n import: (path) => import(path),\n});\n`,\n );\n};\n\nconst createMigrations = async (config: InitConfig, dirPath: string) => {\n const migrationsPath = join(dirPath, 'migrations');\n await fs.mkdir(migrationsPath, { recursive: true });\n\n if (!config.demoTables) return;\n\n const now = new Date();\n\n const postPath = join(\n migrationsPath,\n `${makeFileTimeStamp(now)}_createPost.ts`,\n );\n await fs.writeFile(\n postPath,\n `import { change } from '../dbScript';\n\nchange(async (db) => {\n await db.createTable('post', (t) => ({\n id: t.identity().primaryKey(),\n title: t.text().unique(),\n text: t.text(),\n ...t.timestamps(),\n }));\n});\n`,\n );\n\n now.setTime(now.getTime() + 1000);\n\n const commentPath = join(\n migrationsPath,\n `${makeFileTimeStamp(now)}_createComment.ts`,\n );\n await fs.writeFile(\n commentPath,\n `import { change } from '../dbScript';\n\nchange(async (db) => {\n await db.createTable('comment', (t) => ({\n id: t.identity().primaryKey(),\n postId: t.integer().foreignKey('post', 'id').index(),\n text: t.text(),\n ...t.timestamps(),\n }));\n});\n`,\n );\n};\n\nconst makeFileTimeStamp = (now: Date) => {\n return [\n now.getUTCFullYear(),\n now.getUTCMonth() + 1,\n now.getUTCDate(),\n now.getUTCHours(),\n now.getUTCMinutes(),\n now.getUTCSeconds(),\n ]\n .map((value) => (value < 10 ? `0${value}` : value))\n .join('');\n};\n\nconst createSeed = async (config: InitConfig, dirPath: string) => {\n const filePath = join(dirPath, 'seed.ts');\n\n let content;\n if (config.demoTables) {\n content = `await db.post.findBy({ title: 'Sample post' }).orCreate({\n title: 'Post',\n text: 'This is a text for a sample post. It contains words, spaces, and punctuation.',\n comments: {\n create: [\n {\n text: 'Nice post!',\n },\n {\n text: \\`Too long, didn't read\\`,\n },\n ],\n },\n });`;\n } else {\n content = `// create records here`;\n }\n\n await fs.writeFile(\n filePath,\n `import { db } from './db';\n\nexport const seed = async () => {\n ${content}\n\n await db.$close();\n};\n`,\n );\n};\n\nconst greet = (config: InitConfig) => {\n const relativePath = relative(process.cwd(), config.path);\n\n console.log(`\nThank you for trying Orchid ORM!\n \nTo finish setup,${\n relativePath ? ` cd to the project and` : ''\n } install dependencies:\n${\n relativePath\n ? `\n> cd ${relativePath}`\n : ''\n}\n> npm i\n\nEnter the correct database credentials to the .env file,\nthen create the database:\n\n> npm run db create\n\nAnd run the migrations:\n\n> npm run db migrate\n`);\n};\n","import { askOrchidORMConfig, initOrchidORM } from './init';\n\naskOrchidORMConfig().then((config) => {\n if (config) initOrchidORM(config);\n});\n"],"names":["join","resolve","relative"],"mappings":";;;;;;;;AAkBO,MAAM,qBAAq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I,EAAA,EAAG,OAAO,IAAI,CAAA,CAAA;AAExD,EAAA,OAAA,CAAQ,GAAI,CAAA,CAAA;AAAA;AAAA;AAAA,gBAAA,EAIV,eAAe,CAA2B,sBAAA,CAAA,GAAA,EAAA,CAAA;AAAA,EAG5C,YACI,GAAA,CAAA;AAAA,KAAA,EACC,YACD,CAAA,CAAA,GAAA,EAAA,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAYL,CAAA,CAAA;AACD,CAAA;;AChlBA,kBAAmB,EAAA,CAAE,IAAK,CAAA,CAAC,MAAW,KAAA;AACpC,EAAI,IAAA,MAAA;AAAQ,IAAA,aAAA,CAAc,MAAM,CAAA,CAAA;AAClC,CAAC,CAAA;;"}
|
|
1
|
+
{"version":3,"file":"bin.js","sources":["../src/bin/init.ts","../src/bin/bin.ts"],"sourcesContent":["import fs from 'fs/promises';\nimport { resolve, join, relative } from 'path';\nimport https from 'https';\nimport prompts from 'prompts';\n\nexport type InitConfig = {\n path: string;\n hasTsConfig: boolean;\n testDatabase?: boolean;\n addSchemaToZod?: boolean;\n addTestFactory?: boolean;\n demoTables?: boolean;\n timestamp?: 'date' | 'number';\n swc?: boolean;\n};\n\ntype DependencyKind = 'dependencies' | 'devDependencies';\n\nexport const askOrchidORMConfig = async () => {\n let cancelled = false;\n\n const response = await prompts(\n [\n {\n type: 'text',\n name: 'path',\n message: 'Where would you like to install Orchid ORM?',\n initial: process.cwd(),\n },\n {\n type: 'select',\n name: 'timestamp',\n message: 'Preferred type of returned timestamps:',\n choices: [\n {\n title: 'string (as returned from db)',\n },\n {\n title: 'number (epoch)',\n value: 'number',\n },\n {\n title: 'Date object',\n value: 'date',\n },\n ],\n },\n {\n type: 'confirm',\n name: 'testDatabase',\n message: 'Should I add a separate database for tests?',\n },\n {\n type: 'confirm',\n name: 'addSchemaToZod',\n message: 'Are you going to use Zod for validation?',\n },\n {\n type: 'confirm',\n name: 'addTestFactory',\n message: 'Do you want object factories for writing tests?',\n },\n {\n type: 'confirm',\n name: 'demoTables',\n message: 'Should I add demo tables?',\n },\n ],\n {\n onCancel() {\n cancelled = true;\n },\n },\n );\n\n if (cancelled) return;\n\n const tsConfigPath = join(response.path, 'tsconfig.json');\n const hasTsConfig = await readFileSafe(tsConfigPath);\n (response as InitConfig).hasTsConfig = !!hasTsConfig;\n\n if (!hasTsConfig) {\n const res = await prompts(\n [\n {\n type: 'confirm',\n name: 'swc',\n initial: true,\n message: `Let's add fast TS compiler swc?`,\n },\n ],\n {\n onCancel() {\n cancelled = true;\n },\n },\n );\n\n if (cancelled) return;\n\n (response as InitConfig).swc = res.swc;\n }\n\n return response as InitConfig;\n};\n\nexport const initOrchidORM = async (config: InitConfig) => {\n config.path = resolve(config.path);\n const dirPath = join(config.path, 'src', 'db');\n\n await fs.mkdir(dirPath, { recursive: true });\n\n await setupPackageJson(config);\n await setupTSConfig(config);\n await setupEnv(config);\n await setupGitIgnore(config);\n await setupBaseTable(config, dirPath);\n await setupTables(config, dirPath);\n await setupConfig(config, dirPath);\n await setupMainDb(config, dirPath);\n await setupMigrationScript(config, dirPath);\n await createMigrations(config, dirPath);\n await createSeed(config, dirPath);\n\n greet(config);\n};\n\nconst setupPackageJson = async (config: InitConfig) => {\n const pairs = await Promise.all([\n getLatestPackageVersion('dotenv', 'dependencies'),\n getLatestPackageVersion('orchid-orm', 'dependencies'),\n getLatestPackageVersion('pqb', 'dependencies'),\n config.addSchemaToZod &&\n getLatestPackageVersion('orchid-orm-schema-to-zod', 'dependencies'),\n getLatestPackageVersion('rake-db', 'devDependencies'),\n config.addTestFactory &&\n getLatestPackageVersion('orchid-orm-test-factory', 'devDependencies'),\n config.swc && getLatestPackageVersion('@swc/core', 'devDependencies'),\n getLatestPackageVersion('@types/node', 'devDependencies'),\n getLatestPackageVersion('ts-node', 'devDependencies'),\n getLatestPackageVersion('typescript', 'devDependencies'),\n ]);\n\n const deps: Record<string, string> = {};\n const devDeps: Record<string, string> = {};\n for (const item of pairs) {\n if (!item) continue;\n const [key, { version, kind }] = item;\n (kind === 'dependencies' ? deps : devDeps)[key] = version;\n }\n\n const packageJsonPath = join(config.path, 'package.json');\n const content = await readFileSafe(packageJsonPath);\n const json = content ? JSON.parse(content) : {};\n\n if (!json.scripts) json.scripts = {};\n json.scripts.db = 'ts-node src/db/dbScript.ts';\n\n if (!json.dependencies) json.dependencies = {};\n\n for (const key in deps) {\n json.dependencies[key] = deps[key];\n }\n\n if (!json.devDependencies) json.devDependencies = {};\n for (const key in devDeps) {\n json.devDependencies[key] = devDeps[key];\n }\n\n await fs.writeFile(packageJsonPath, JSON.stringify(json, null, ' ') + '\\n');\n};\n\nconst getLatestPackageVersion = (\n name: string,\n kind: DependencyKind,\n): Promise<[string, { version: string; kind: DependencyKind }]> => {\n return new Promise((resolve, reject) => {\n https\n .get(`https://registry.npmjs.org/${name}/latest`, (res) => {\n let data = '';\n res.on('data', (chunk) => (data += chunk));\n res.on('end', () =>\n resolve([name, { version: `^${JSON.parse(data).version}`, kind }]),\n );\n })\n .on('error', reject);\n });\n};\n\nconst readFileSafe = async (path: string) => {\n try {\n return await fs.readFile(path, 'utf-8');\n } catch (err) {\n if ((err as unknown as { code: string }).code === 'ENOENT') {\n return undefined;\n }\n throw err;\n }\n};\n\nconst setupTSConfig = async (config: InitConfig) => {\n if (config.hasTsConfig) return;\n\n const tsConfigPath = join(config.path, 'tsconfig.json');\n await fs.writeFile(\n tsConfigPath,\n `{${\n config.swc\n ? `\n \"ts-node\": {\n \"swc\": true\n },`\n : ''\n }\n \"compilerOptions\": {\n \"strict\": true\n }\n}\n`,\n );\n};\n\nconst setupEnv = async (config: InitConfig) => {\n const envPath = join(config.path, '.env');\n let content = ((await readFileSafe(envPath)) || '').trim();\n let changed = false;\n\n if (!content.match(/^DATABASE_URL=/m)) {\n content += `\\nDATABASE_URL=postgres://user:password@localhost:5432/dbname?ssl=false`;\n changed = true;\n }\n\n if (config.testDatabase && !content.match(/^DATABASE_TEST_URL=/m)) {\n content += `\\nDATABASE_TEST_URL=postgres://user:password@localhost:5432/dbname-test?ssl=false`;\n changed = true;\n }\n\n if (changed) {\n await fs.writeFile(envPath, `${content.trim()}\\n`);\n }\n};\n\nconst setupGitIgnore = async (config: InitConfig) => {\n const gitignorePath = join(config.path, '.gitignore');\n let content = ((await readFileSafe(gitignorePath)) || '').trim();\n let changed = false;\n\n if (!content.match(/^node_modules\\b/m)) {\n content += `\\nnode_modules`;\n changed = true;\n }\n\n if (!content.match(/^.env\\b/m)) {\n content += `\\n.env`;\n changed = true;\n }\n\n if (changed) {\n await fs.writeFile(gitignorePath, `${content.trim()}\\n`);\n }\n};\n\nconst setupBaseTable = async (config: InitConfig, dirPath: string) => {\n const filePath = join(dirPath, 'baseTable.ts');\n\n let content = `import { createBaseTable } from 'orchid-orm';\n\nexport const BaseTable = createBaseTable({\n columnTypes: (t) => ({\n ...t,\n text: (min = 0, max = Infinity) => t.text(min, max),`;\n\n const { timestamp } = config;\n if (timestamp) {\n content += `\n timestamp: <P extends number>(precision?: P) =>\n t.timestamp<P>(precision).${\n timestamp === 'date' ? 'asDate' : 'asNumber'\n }(),`;\n }\n\n content += `\n }),\n});\n`;\n\n await fs.writeFile(filePath, content);\n};\n\nconst setupTables = async (config: InitConfig, dirPath: string) => {\n if (!config.demoTables) return;\n\n const tablesDir = join(dirPath, 'tables');\n await fs.mkdir(tablesDir, { recursive: true });\n\n await fs.writeFile(\n join(tablesDir, 'post.table.ts'),\n `import { TableType } from 'orchid-orm';\nimport { BaseTable } from '../baseTable';\nimport { CommentTable } from './comment.table';\n${\n config.addSchemaToZod\n ? `import { tableToZod } from 'orchid-orm-schema-to-zod';\\n`\n : ''\n}\nexport type Post = TableType<PostTable>;\nexport class PostTable extends BaseTable {\n readonly table = 'post';\n columns = this.setColumns((t) => ({\n id: t.identity().primaryKey(),\n title: t.text(3, 100).unique(),\n text: t.text(20, 10000),\n ...t.timestamps(),\n }));\n\n relations = {\n comments: this.hasMany(() => CommentTable, {\n primaryKey: 'id',\n foreignKey: 'postId',\n }),\n };\n}\n${\n config.addSchemaToZod\n ? `\\nexport const postSchema = tableToZod(PostTable);\\n`\n : ''\n}`,\n );\n\n await fs.writeFile(\n join(tablesDir, 'comment.table.ts'),\n `import { TableType } from 'orchid-orm';\nimport { BaseTable } from '../baseTable';\nimport { PostTable } from './post.table';\n${\n config.addSchemaToZod\n ? `import { tableToZod } from 'orchid-orm-schema-to-zod';\\n`\n : ''\n}\nexport type Comment = TableType<CommentTable>;\nexport class CommentTable extends BaseTable {\n readonly table = 'comment';\n columns = this.setColumns((t) => ({\n id: t.identity().primaryKey(),\n postId: t\n .integer()\n .foreignKey(() => PostTable, 'id')\n .index(),\n text: t.text(5, 1000),\n ...t.timestamps(),\n }));\n\n relations = {\n post: this.belongsTo(() => PostTable, {\n primaryKey: 'id',\n foreignKey: 'postId',\n }),\n };\n}\n${\n config.addSchemaToZod\n ? `\\nexport const commentSchema = tableToZod(CommentTable);\\n`\n : ''\n}`,\n );\n};\n\nconst setupConfig = async (config: InitConfig, dirPath: string) => {\n const configPath = join(dirPath, 'config.ts');\n\n let content = `import 'dotenv/config';\n\nconst database = {\n databaseURL: process.env.DATABASE_URL,\n};\nif (!database.databaseURL) throw new Error('DATABASE_URL is missing in .env');`;\n\n if (config.testDatabase) {\n content += `\n\nconst testDatabase = {\n databaseURL: process.env.DATABASE_TEST_URL,\n};\n\nconst allDatabases = [database];\n\nif (testDatabase.databaseURL) {\n allDatabases.push(testDatabase);\n}`;\n }\n\n content += `\n\nexport const config = {`;\n\n if (config.testDatabase) {\n content += `\n allDatabases,`;\n }\n\n if (config.testDatabase) {\n content += `\n database: process.env.NODE_ENV === 'test' ? testDatabase : database,`;\n } else {\n content += `\n database,`;\n }\n content += `\n};\n`;\n\n await fs.writeFile(configPath, content);\n};\n\nconst setupMainDb = async (config: InitConfig, dirPath: string) => {\n let imports = '';\n let tables = '';\n if (config.demoTables) {\n imports += `\nimport { PostTable } from './tables/post.table';\nimport { CommentTable } from './tables/comment.table';`;\n tables += `\n post: PostTable,\n comment: CommentTable,`;\n }\n\n const dbPath = join(dirPath, 'db.ts');\n await fs.writeFile(\n dbPath,\n `import { orchidORM } from 'orchid-orm';\nimport { config } from './config';${imports}\n\nexport const db = orchidORM(config.database, {${tables}\n});\n`,\n );\n};\n\nconst setupMigrationScript = async (config: InitConfig, dirPath: string) => {\n const filePath = join(dirPath, 'dbScript.ts');\n await fs.writeFile(\n filePath,\n `import { rakeDb } from 'rake-db';\nimport { appCodeUpdater } from 'orchid-orm/codegen';\nimport { config } from './config';\nimport { BaseTable } from './baseTable';\n\nexport const change = rakeDb(${\n config.testDatabase ? 'config.allDatabases' : 'config.database'\n }, {\n baseTable: BaseTable,\n migrationsPath: './migrations',\n appCodeUpdater: appCodeUpdater({\n tablePath: (tableName) => \\`./tables/\\${tableName}.table.ts\\`,\n ormPath: './db.ts',\n }),\n useCodeUpdater: true, // set to false to disable code updater\n commands: {\n async seed() {\n const { seed } = await import('./seed');\n await seed();\n },\n },\n import: (path) => import(path),\n});\n`,\n );\n};\n\nconst createMigrations = async (config: InitConfig, dirPath: string) => {\n const migrationsPath = join(dirPath, 'migrations');\n await fs.mkdir(migrationsPath, { recursive: true });\n\n if (!config.demoTables) return;\n\n const now = new Date();\n\n const postPath = join(\n migrationsPath,\n `${makeFileTimeStamp(now)}_createPost.ts`,\n );\n await fs.writeFile(\n postPath,\n `import { change } from '../dbScript';\n\nchange(async (db) => {\n await db.createTable('post', (t) => ({\n id: t.identity().primaryKey(),\n title: t.text().unique(),\n text: t.text(),\n ...t.timestamps(),\n }));\n});\n`,\n );\n\n now.setTime(now.getTime() + 1000);\n\n const commentPath = join(\n migrationsPath,\n `${makeFileTimeStamp(now)}_createComment.ts`,\n );\n await fs.writeFile(\n commentPath,\n `import { change } from '../dbScript';\n\nchange(async (db) => {\n await db.createTable('comment', (t) => ({\n id: t.identity().primaryKey(),\n postId: t.integer().foreignKey('post', 'id').index(),\n text: t.text(),\n ...t.timestamps(),\n }));\n});\n`,\n );\n};\n\nconst makeFileTimeStamp = (now: Date) => {\n return [\n now.getUTCFullYear(),\n now.getUTCMonth() + 1,\n now.getUTCDate(),\n now.getUTCHours(),\n now.getUTCMinutes(),\n now.getUTCSeconds(),\n ]\n .map((value) => (value < 10 ? `0${value}` : value))\n .join('');\n};\n\nconst createSeed = async (config: InitConfig, dirPath: string) => {\n const filePath = join(dirPath, 'seed.ts');\n\n let content;\n if (config.demoTables) {\n content = `await db.post.findBy({ title: 'Sample post' }).orCreate({\n title: 'Post',\n text: 'This is a text for a sample post. It contains words, spaces, and punctuation.',\n comments: {\n create: [\n {\n text: 'Nice post!',\n },\n {\n text: \\`Too long, didn't read\\`,\n },\n ],\n },\n });`;\n } else {\n content = `// create records here`;\n }\n\n await fs.writeFile(\n filePath,\n `import { db } from './db';\n\nexport const seed = async () => {\n ${content}\n\n await db.$close();\n};\n`,\n );\n};\n\nconst greet = (config: InitConfig) => {\n const relativePath = relative(process.cwd(), config.path);\n\n console.log(`\nThank you for trying Orchid ORM!\n \nTo finish setup,${\n relativePath ? ` cd to the project and` : ''\n } install dependencies:\n${\n relativePath\n ? `\n> cd ${relativePath}`\n : ''\n}\n> npm i\n\nEnter the correct database credentials to the .env file,\nthen create the database:\n\n> npm run db create\n\nAnd run the migrations:\n\n> npm run db migrate\n`);\n};\n","import { askOrchidORMConfig, initOrchidORM } from './init';\n\naskOrchidORMConfig().then((config) => {\n if (config) initOrchidORM(config);\n});\n"],"names":["join","resolve","relative"],"mappings":";;;;;;;;AAkBO,MAAM,qBAAqB,YAAY;AAC5C,EAAA,IAAI,SAAY,GAAA,KAAA,CAAA;AAEhB,EAAA,MAAM,WAAW,MAAM,OAAA;AAAA,IACrB;AAAA,MACE;AAAA,QACE,IAAM,EAAA,MAAA;AAAA,QACN,IAAM,EAAA,MAAA;AAAA,QACN,OAAS,EAAA,6CAAA;AAAA,QACT,OAAA,EAAS,QAAQ,GAAI,EAAA;AAAA,OAC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AA;AAAA,CAYL,CAAA,CAAA;AACD,CAAA;;AC/kBA,kBAAmB,EAAA,CAAE,IAAK,CAAA,CAAC,MAAW,KAAA;AACpC,EAAI,IAAA,MAAA;AAAQ,IAAA,aAAA,CAAc,MAAM,CAAA,CAAA;AAClC,CAAC,CAAA;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,18 +1,34 @@
|
|
|
1
1
|
import * as pqb from 'pqb';
|
|
2
|
-
import { QueryWithTable, SetQueryTableAlias,
|
|
2
|
+
import { Query, QueryWithTable, SetQueryTableAlias, WhereArg, UpdateData, CreateData, Db, IsolationLevel, TransactionOptions, Adapter, FromArgs, FromResult, AdapterOptions, QueryLogOptions, NoPrimaryKeyOption, RelationConfigBase, RelationQuery, SetQueryReturnsOne, SetQueryReturnsOneOptional, SetQueryReturnsAll, RelationQueryBase, DefaultColumnTypes, QueryData, QueryBase, ColumnsShape, QueryBeforeHook, QueryAfterHook, AfterHook, WhereResult, MergeQuery, SetQueryReturns, QueryReturnType } from 'pqb';
|
|
3
3
|
export { OrchidOrmError, OrchidOrmInternalError, columnTypes, raw, testTransaction } from 'pqb';
|
|
4
4
|
import * as orchid_core from 'orchid-core';
|
|
5
5
|
import { EmptyObject, MaybeArray, ColumnTypesBase, ColumnsShapeBase, ColumnShapeOutput } from 'orchid-core';
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
type RelationCommonOptions<Related extends TableClass = TableClass, Scope extends Query = Query> = {
|
|
8
|
+
scope?: ScopeFn<Related, Scope>;
|
|
9
|
+
required?: boolean;
|
|
10
|
+
};
|
|
11
|
+
type RelationRefsOptions<Column extends PropertyKey = string, Ref extends PropertyKey = string> = {
|
|
12
|
+
columns: Column[];
|
|
13
|
+
references: Ref[];
|
|
14
|
+
};
|
|
15
|
+
type RelationKeysOptions<PK extends PropertyKey = string, FK extends PropertyKey = string> = {
|
|
16
|
+
primaryKey: PK;
|
|
17
|
+
foreignKey: FK;
|
|
18
|
+
};
|
|
19
|
+
type RelationRefsOrKeysOptions<Column extends PropertyKey = string, Ref extends PropertyKey = string, PK extends PropertyKey = string, FK extends PropertyKey = string> = RelationRefsOptions<Column, Ref> | RelationKeysOptions<PK, FK>;
|
|
20
|
+
type RelationThroughOptions<Through extends PropertyKey = string, Source extends PropertyKey = string> = {
|
|
21
|
+
through: Through;
|
|
22
|
+
source: Source;
|
|
23
|
+
};
|
|
24
|
+
type RelationHasOptions<Column extends PropertyKey = string, Ref extends PropertyKey = string> = RelationRefsOrKeysOptions<Column, Ref, Column, Ref>;
|
|
25
|
+
|
|
26
|
+
type BelongsTo = RelationThunkBase & {
|
|
8
27
|
type: 'belongsTo';
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
};
|
|
14
|
-
}
|
|
15
|
-
type BelongsToInfo<T extends Table, Relation extends BelongsTo, K extends string, FK extends string = Relation['options']['foreignKey'], Q extends QueryWithTable = SetQueryTableAlias<DbTable<ReturnType<Relation['fn']>>, K>> = {
|
|
28
|
+
options: BelongsToOptions;
|
|
29
|
+
};
|
|
30
|
+
type BelongsToOptions<Self extends Table = Table, Related extends TableClass = TableClass, Scope extends Query = Query> = RelationCommonOptions<Related, Scope> & RelationRefsOrKeysOptions<keyof Self['columns']['shape'], keyof InstanceType<Related>['columns']['shape'], keyof InstanceType<Related>['columns']['shape'], keyof Self['columns']['shape']>;
|
|
31
|
+
type BelongsToInfo<T extends Table, Relation extends BelongsTo, K extends string, FK extends string = Relation['options'] extends RelationRefsOptions ? Relation['options']['columns'][number] : Relation['options'] extends RelationKeysOptions ? Relation['options']['foreignKey'] : never, Q extends QueryWithTable = SetQueryTableAlias<DbTable<ReturnType<Relation['fn']>>, K>> = {
|
|
16
32
|
table: Q;
|
|
17
33
|
query: Q;
|
|
18
34
|
joinQuery(fromQuery: Query, toQuery: Query): Query;
|
|
@@ -40,26 +56,20 @@ type BelongsToInfo<T extends Table, Relation extends BelongsTo, K extends string
|
|
|
40
56
|
create: CreateData<Q> | (() => CreateData<Q>);
|
|
41
57
|
};
|
|
42
58
|
};
|
|
43
|
-
params:
|
|
59
|
+
params: {
|
|
60
|
+
[K in FK]: T['columns']['shape'][FK]['type'];
|
|
61
|
+
};
|
|
44
62
|
populate: never;
|
|
45
63
|
chainedCreate: false;
|
|
46
64
|
chainedDelete: false;
|
|
47
65
|
};
|
|
48
66
|
|
|
49
|
-
|
|
67
|
+
type HasMany = RelationThunkBase & {
|
|
50
68
|
type: 'hasMany';
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
} | {
|
|
56
|
-
through: string;
|
|
57
|
-
source: string;
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
type HasManyInfo<T extends Table, Relations extends RelationThunks, Relation extends HasMany, K extends string, Populate extends string = Relation['options'] extends {
|
|
61
|
-
foreignKey: string;
|
|
62
|
-
} ? Relation['options']['foreignKey'] : never, TC extends TableClass = ReturnType<Relation['fn']>, Q extends QueryWithTable = SetQueryTableAlias<DbTable<TC>, K>, NestedCreateQuery extends Query = [Populate] extends [never] ? Q : Q & {
|
|
69
|
+
options: HasManyOptions;
|
|
70
|
+
};
|
|
71
|
+
type HasManyOptions<Self extends Table = Table, Related extends TableClass = TableClass, Scope extends Query = Query, Through extends string = string, Source extends string = string> = HasOneOptions<Self, Related, Scope, Through, Source>;
|
|
72
|
+
type HasManyInfo<T extends Table, Relations extends RelationThunks, Relation extends HasMany, K extends string, Populate extends string = Relation['options'] extends RelationRefsOptions ? Relation['options']['references'][number] : Relation['options'] extends RelationKeysOptions ? Relation['options']['foreignKey'] : never, TC extends TableClass = ReturnType<Relation['fn']>, Q extends QueryWithTable = SetQueryTableAlias<DbTable<TC>, K>, NestedCreateQuery extends Query = Relation['options'] extends RelationThroughOptions ? Q : Q & {
|
|
63
73
|
meta: {
|
|
64
74
|
defaults: Record<Populate, true>;
|
|
65
75
|
};
|
|
@@ -70,9 +80,7 @@ type HasManyInfo<T extends Table, Relations extends RelationThunks, Relation ext
|
|
|
70
80
|
one: false;
|
|
71
81
|
required: Relation['options']['required'] extends true ? true : false;
|
|
72
82
|
omitForeignKeyInCreate: never;
|
|
73
|
-
dataForCreate: Relation['options'] extends {
|
|
74
|
-
through: string;
|
|
75
|
-
} ? EmptyObject : RelationToManyDataForCreate<{
|
|
83
|
+
dataForCreate: Relation['options'] extends RelationThroughOptions ? EmptyObject : RelationToManyDataForCreate<{
|
|
76
84
|
nestedCreateQuery: NestedCreateQuery;
|
|
77
85
|
table: Q;
|
|
78
86
|
}>;
|
|
@@ -88,32 +96,20 @@ type HasManyInfo<T extends Table, Relations extends RelationThunks, Relation ext
|
|
|
88
96
|
set?: MaybeArray<WhereArg<Q>>;
|
|
89
97
|
create?: CreateData<NestedCreateQuery>[];
|
|
90
98
|
};
|
|
91
|
-
params: Relation['options'] extends {
|
|
92
|
-
|
|
93
|
-
} ? Record<Relation['options']['primaryKey'], T['columns']['shape'][Relation['options']['primaryKey']]['type']> : Relation['options'] extends
|
|
94
|
-
through: string;
|
|
95
|
-
} ? RelationConfig<T, Relations, Relations[Relation['options']['through']]>['params'] : never;
|
|
99
|
+
params: Relation['options'] extends RelationRefsOptions ? {
|
|
100
|
+
[K in Relation['options']['columns'][number]]: T['columns']['shape'][K]['type'];
|
|
101
|
+
} : Relation['options'] extends RelationKeysOptions ? Record<Relation['options']['primaryKey'], T['columns']['shape'][Relation['options']['primaryKey']]['type']> : Relation['options'] extends RelationThroughOptions ? RelationConfig<T, Relations, Relations[Relation['options']['through']]>['params'] : never;
|
|
96
102
|
populate: Populate;
|
|
97
|
-
chainedCreate: Relation['options'] extends
|
|
98
|
-
primaryKey: string;
|
|
99
|
-
} ? true : false;
|
|
103
|
+
chainedCreate: Relation['options'] extends RelationThroughOptions ? false : true;
|
|
100
104
|
chainedDelete: true;
|
|
101
105
|
};
|
|
102
106
|
|
|
103
|
-
|
|
107
|
+
type HasOne = RelationThunkBase & {
|
|
104
108
|
type: 'hasOne';
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
} | {
|
|
110
|
-
through: string;
|
|
111
|
-
source: string;
|
|
112
|
-
});
|
|
113
|
-
}
|
|
114
|
-
type HasOneInfo<T extends Table, Relations extends RelationThunks, Relation extends HasOne, K extends string, Populate extends string = Relation['options'] extends {
|
|
115
|
-
foreignKey: string;
|
|
116
|
-
} ? Relation['options']['foreignKey'] : never, TC extends TableClass = ReturnType<Relation['fn']>, Q extends QueryWithTable = SetQueryTableAlias<DbTable<TC>, K>, NestedCreateQuery extends Query = [Populate] extends [never] ? Q : Q & {
|
|
109
|
+
options: HasOneOptions;
|
|
110
|
+
};
|
|
111
|
+
type HasOneOptions<Self extends Table = Table, Related extends TableClass = TableClass, Scope extends Query = Query, Through extends string = string, Source extends string = string> = RelationCommonOptions<Related, Scope> & (RelationHasOptions<keyof Self['columns']['shape'], keyof InstanceType<Related>['columns']['shape']> | RelationThroughOptions<Through, Source>);
|
|
112
|
+
type HasOneInfo<T extends Table, Relations extends RelationThunks, Relation extends HasOne, K extends string, Populate extends string = Relation['options'] extends RelationRefsOptions ? Relation['options']['references'][number] : Relation['options'] extends RelationKeysOptions ? Relation['options']['foreignKey'] : never, TC extends TableClass = ReturnType<Relation['fn']>, Q extends QueryWithTable = SetQueryTableAlias<DbTable<TC>, K>, NestedCreateQuery extends Query = Relation['options'] extends RelationThroughOptions ? Q : Q & {
|
|
117
113
|
meta: {
|
|
118
114
|
defaults: Record<Populate, true>;
|
|
119
115
|
};
|
|
@@ -124,9 +120,7 @@ type HasOneInfo<T extends Table, Relations extends RelationThunks, Relation exte
|
|
|
124
120
|
one: true;
|
|
125
121
|
required: Relation['options']['required'] extends true ? true : false;
|
|
126
122
|
omitForeignKeyInCreate: never;
|
|
127
|
-
dataForCreate: Relation['options'] extends {
|
|
128
|
-
through: string;
|
|
129
|
-
} ? EmptyObject : RelationToOneDataForCreate<{
|
|
123
|
+
dataForCreate: Relation['options'] extends RelationThroughOptions ? EmptyObject : RelationToOneDataForCreate<{
|
|
130
124
|
nestedCreateQuery: NestedCreateQuery;
|
|
131
125
|
table: Q;
|
|
132
126
|
}>;
|
|
@@ -147,15 +141,11 @@ type HasOneInfo<T extends Table, Relations extends RelationThunks, Relation exte
|
|
|
147
141
|
} | {
|
|
148
142
|
create: CreateData<NestedCreateQuery>;
|
|
149
143
|
};
|
|
150
|
-
params: Relation['options'] extends {
|
|
151
|
-
|
|
152
|
-
} ? Record<Relation['options']['primaryKey'], T['columns']['shape'][Relation['options']['primaryKey']]['type']> : Relation['options'] extends
|
|
153
|
-
through: string;
|
|
154
|
-
} ? RelationConfig<T, Relations, Relations[Relation['options']['through']]>['params'] : never;
|
|
144
|
+
params: Relation['options'] extends RelationRefsOptions ? {
|
|
145
|
+
[K in Relation['options']['columns'][number]]: T['columns']['shape'][K]['type'];
|
|
146
|
+
} : Relation['options'] extends RelationKeysOptions ? Record<Relation['options']['primaryKey'], T['columns']['shape'][Relation['options']['primaryKey']]['type']> : Relation['options'] extends RelationThroughOptions ? RelationConfig<T, Relations, Relations[Relation['options']['through']]>['params'] : never;
|
|
155
147
|
populate: Populate;
|
|
156
|
-
chainedCreate: Relation['options'] extends
|
|
157
|
-
primaryKey: string;
|
|
158
|
-
} ? true : false;
|
|
148
|
+
chainedCreate: Relation['options'] extends RelationThroughOptions ? false : true;
|
|
159
149
|
chainedDelete: true;
|
|
160
150
|
};
|
|
161
151
|
|
|
@@ -241,17 +231,25 @@ declare const orchidORM: <T extends TableClasses>({ log, logger, autoPreparedSta
|
|
|
241
231
|
noPrimaryKey?: NoPrimaryKeyOption | undefined;
|
|
242
232
|
}, tables: T) => OrchidORM<T>;
|
|
243
233
|
|
|
244
|
-
|
|
234
|
+
type HasAndBelongsToMany = RelationThunkBase & {
|
|
245
235
|
type: 'hasAndBelongsToMany';
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
236
|
+
options: HasAndBelongsToManyOptions;
|
|
237
|
+
};
|
|
238
|
+
type HasAndBelongsToManyOptions<Self extends Table = Table, Related extends TableClass = TableClass, Scope extends Query = Query> = RelationCommonOptions<Related, Scope> & ({
|
|
239
|
+
columns: (keyof Self['columns']['shape'])[];
|
|
240
|
+
references: string[];
|
|
241
|
+
through: {
|
|
242
|
+
table: string;
|
|
243
|
+
columns: string[];
|
|
244
|
+
references: (keyof InstanceType<Related>['columns']['shape'])[];
|
|
253
245
|
};
|
|
254
|
-
}
|
|
246
|
+
} | {
|
|
247
|
+
primaryKey: keyof Self['columns']['shape'];
|
|
248
|
+
foreignKey: string;
|
|
249
|
+
joinTable: string;
|
|
250
|
+
associationPrimaryKey: string;
|
|
251
|
+
associationForeignKey: keyof InstanceType<Related>['columns']['shape'];
|
|
252
|
+
});
|
|
255
253
|
type HasAndBelongsToManyInfo<T extends Table, Relation extends HasAndBelongsToMany, K extends string, TC extends TableClass = ReturnType<Relation['fn']>, Q extends QueryWithTable = SetQueryTableAlias<DbTable<TC>, K>> = {
|
|
256
254
|
table: Q;
|
|
257
255
|
query: Q;
|
|
@@ -274,16 +272,18 @@ type HasAndBelongsToManyInfo<T extends Table, Relation extends HasAndBelongsToMa
|
|
|
274
272
|
create?: CreateData<Q>[];
|
|
275
273
|
};
|
|
276
274
|
dataForUpdateOne: EmptyObject;
|
|
277
|
-
params:
|
|
275
|
+
params: Relation['options'] extends {
|
|
276
|
+
columns: string[];
|
|
277
|
+
} ? {
|
|
278
|
+
[K in Relation['options']['columns'][number]]: T['columns']['shape'][K]['type'];
|
|
279
|
+
} : Relation['options'] extends {
|
|
280
|
+
primaryKey: string;
|
|
281
|
+
} ? Record<Relation['options']['primaryKey'], T['columns']['shape'][Relation['options']['primaryKey']]['type']> : never;
|
|
278
282
|
populate: never;
|
|
279
283
|
chainedCreate: true;
|
|
280
284
|
chainedDelete: true;
|
|
281
285
|
};
|
|
282
286
|
|
|
283
|
-
type RelationCommonOptions = {
|
|
284
|
-
scope?(q: QueryWithTable): QueryWithTable;
|
|
285
|
-
required?: boolean;
|
|
286
|
-
};
|
|
287
287
|
type RelationToOneDataForCreate<Rel extends {
|
|
288
288
|
nestedCreateQuery: Query;
|
|
289
289
|
table: Query;
|
|
@@ -316,7 +316,6 @@ type RelationToManyDataForCreate<Rel extends {
|
|
|
316
316
|
};
|
|
317
317
|
interface RelationThunkBase {
|
|
318
318
|
type: string;
|
|
319
|
-
returns: 'one' | 'many';
|
|
320
319
|
fn(): TableClass;
|
|
321
320
|
options: RelationCommonOptions;
|
|
322
321
|
}
|
|
@@ -647,58 +646,23 @@ declare const createBaseTable: <CT extends Record<string, orchid_core.AnyColumnT
|
|
|
647
646
|
shape: T_13;
|
|
648
647
|
type: ColumnShapeOutput<T_13>;
|
|
649
648
|
};
|
|
650
|
-
belongsTo<Self extends any, Related extends TableClass<Table>, Scope extends Query, Options extends {
|
|
651
|
-
primaryKey: keyof InstanceType<Related>["columns"]["shape"];
|
|
652
|
-
foreignKey: keyof Self["columns"]["shape"];
|
|
653
|
-
scope?: ScopeFn<Related, Scope> | undefined;
|
|
654
|
-
required?: boolean | undefined;
|
|
655
|
-
}>(this: Self, fn: () => Related, options: Options): {
|
|
649
|
+
belongsTo<Self extends any, Related extends TableClass<Table>, Scope extends Query, Options extends BelongsToOptions<Self, Related, Scope>>(this: Self, fn: () => Related, options: Options): {
|
|
656
650
|
type: "belongsTo";
|
|
657
|
-
returns: "one";
|
|
658
651
|
fn: () => Related;
|
|
659
652
|
options: Options;
|
|
660
653
|
};
|
|
661
|
-
hasOne<Self_1 extends any, Related_1 extends TableClass<Table>, Scope_1 extends Query, Through extends string, Source extends string, Options_1 extends ({
|
|
662
|
-
primaryKey: keyof Self_1["columns"]["shape"];
|
|
663
|
-
foreignKey: keyof InstanceType<Related_1>["columns"]["shape"];
|
|
664
|
-
} | {
|
|
665
|
-
through: Through;
|
|
666
|
-
source: Source;
|
|
667
|
-
}) & {
|
|
668
|
-
scope?: ScopeFn<Related_1, Scope_1> | undefined;
|
|
669
|
-
required?: boolean | undefined;
|
|
670
|
-
}>(this: Self_1, fn: () => Related_1, options: Options_1): {
|
|
654
|
+
hasOne<Self_1 extends any, Related_1 extends TableClass<Table>, Scope_1 extends Query, Through extends string, Source extends string, Options_1 extends HasOneOptions<Self_1, Related_1, Scope_1, Through, Source>>(this: Self_1, fn: () => Related_1, options: Options_1): {
|
|
671
655
|
type: "hasOne";
|
|
672
|
-
returns: "one";
|
|
673
656
|
fn: () => Related_1;
|
|
674
657
|
options: Options_1;
|
|
675
658
|
};
|
|
676
|
-
hasMany<Self_2 extends any, Related_2 extends TableClass<Table>, Scope_2 extends Query, Through_1 extends string, Source_1 extends string, Options_2 extends ({
|
|
677
|
-
primaryKey: keyof Self_2["columns"]["shape"];
|
|
678
|
-
foreignKey: keyof InstanceType<Related_2>["columns"]["shape"];
|
|
679
|
-
} | {
|
|
680
|
-
through: Through_1;
|
|
681
|
-
source: Source_1;
|
|
682
|
-
}) & {
|
|
683
|
-
scope?: ScopeFn<Related_2, Scope_2> | undefined;
|
|
684
|
-
required?: boolean | undefined;
|
|
685
|
-
}>(this: Self_2, fn: () => Related_2, options: Options_2): {
|
|
659
|
+
hasMany<Self_2 extends any, Related_2 extends TableClass<Table>, Scope_2 extends Query, Through_1 extends string, Source_1 extends string, Options_2 extends HasManyOptions<Self_2, Related_2, Scope_2, Through_1, Source_1>>(this: Self_2, fn: () => Related_2, options: Options_2): {
|
|
686
660
|
type: "hasMany";
|
|
687
|
-
returns: "many";
|
|
688
661
|
fn: () => Related_2;
|
|
689
662
|
options: Options_2;
|
|
690
663
|
};
|
|
691
|
-
hasAndBelongsToMany<Self_3 extends any, Related_3 extends TableClass<Table>, Scope_3 extends Query, Options_3 extends {
|
|
692
|
-
primaryKey: keyof Self_3["columns"]["shape"];
|
|
693
|
-
associationPrimaryKey: keyof InstanceType<Related_3>["columns"]["shape"];
|
|
694
|
-
foreignKey: string;
|
|
695
|
-
associationForeignKey: string;
|
|
696
|
-
joinTable: string;
|
|
697
|
-
scope?: ScopeFn<Related_3, Scope_3> | undefined;
|
|
698
|
-
required?: boolean | undefined;
|
|
699
|
-
}>(this: Self_3, fn: () => Related_3, options: Options_3): {
|
|
664
|
+
hasAndBelongsToMany<Self_3 extends any, Related_3 extends TableClass<Table>, Scope_3 extends Query, Options_3 extends HasAndBelongsToManyOptions<Self_3, Related_3, Scope_3>>(this: Self_3, fn: () => Related_3, options: Options_3): {
|
|
700
665
|
type: "hasAndBelongsToMany";
|
|
701
|
-
returns: "many";
|
|
702
666
|
fn: () => Related_3;
|
|
703
667
|
options: Options_3;
|
|
704
668
|
};
|
|
@@ -744,4 +708,4 @@ type Repo<T extends Query, Methods extends MethodsBase<T>, Mapped = MapMethods<T
|
|
|
744
708
|
}>(q: Q) => Q & Mapped) & T & Mapped;
|
|
745
709
|
declare const createRepo: <T extends Query, Methods extends MethodsBase<T>>(table: T, methods: Methods) => Repo<T, Methods, MapMethods<T, Methods>>;
|
|
746
710
|
|
|
747
|
-
export { DbTable, MapMethods, MapQueryMethods, MethodsBase, OrchidORM, QueryMethods, Repo, Table, TableClass, TableClasses, TableToDb, TableType, createBaseTable, createRepo, orchidORM };
|
|
711
|
+
export { DbTable, MapMethods, MapQueryMethods, MethodsBase, OrchidORM, QueryMethods, Repo, ScopeFn, Table, TableClass, TableClasses, TableToDb, TableType, createBaseTable, createRepo, orchidORM };
|