diff --git a/adonis-typings/container.ts b/adonis-typings/container.ts deleted file mode 100644 index 91459a87..00000000 --- a/adonis-typings/container.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -// declare module '@ioc:Adonis/Core/Application' { -// import * as Orm from '@ioc:Adonis/Lucid/Orm' -// import Migrator from '@ioc:Adonis/Lucid/Migrator' -// import { DatabaseContract } from '@ioc:Adonis/Lucid/Database' -// import { FactoryManagerContract } from '@ioc:Adonis/Lucid/Factory' -// import { SchemaConstructorContract } from '@ioc:Adonis/Lucid/Schema' -// import { SeederConstructorContract } from '@ioc:Adonis/Lucid/Seeder' - -// export interface ContainerBindings { -// 'Adonis/Lucid/Database': DatabaseContract -// 'Adonis/Lucid/Factory': FactoryManagerContract -// 'Adonis/Lucid/Orm': typeof Orm -// 'Adonis/Lucid/Migrator': typeof Migrator -// 'Adonis/Lucid/Schema': SchemaConstructorContract -// 'Adonis/Lucid/Seeder': SeederConstructorContract -// } -// } diff --git a/adonis-typings/test_utils.ts b/adonis-typings/test_utils.ts deleted file mode 100644 index 8f8cccb6..00000000 --- a/adonis-typings/test_utils.ts +++ /dev/null @@ -1,21 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -// declare module '@ioc:Adonis/Core/TestUtils' { -// type HookCleanupHandler = () => Promise -// type HookCallback = () => Promise | Promise - -// export interface TestUtilsContract { -// db(connectionName?: string): { -// seed: HookCallback -// migrate: HookCallback -// truncate: HookCallback -// } -// } -// } diff --git a/adonis-typings/validator.ts b/adonis-typings/validator.ts deleted file mode 100644 index c32d7cca..00000000 --- a/adonis-typings/validator.ts +++ /dev/null @@ -1,28 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -// declare module '@ioc:Adonis/Core/Validator' { -// import { Rule } from '@ioc:Adonis/Core/Validator' - -// export type DbRowCheckOptions = { -// table: string -// column: string -// dateFormat?: string -// connection?: string -// caseInsensitive?: boolean -// constraints?: { [key: string]: any } -// where?: { [key: string]: any } -// whereNot?: { [key: string]: any } -// } - -// export interface Rules { -// exists(options: DbRowCheckOptions): Rule -// unique(options: DbRowCheckOptions): Rule -// } -// } diff --git a/commands/MakeFactory.ts b/commands/MakeFactory.ts deleted file mode 100644 index 609e9a85..00000000 --- a/commands/MakeFactory.ts +++ /dev/null @@ -1,97 +0,0 @@ -/* - * @adonisjs/assembler - * - * (c) AdonisJS - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { join } from 'path' -import { args, BaseCommand, flags } from '@adonisjs/core/build/standalone' - -/** - * Command to make a new Factory - */ -export default class MakeFactory extends BaseCommand { - public static commandName = 'make:factory' - public static description = 'Make a new factory' - - /** - * Name of the model to be used in the factory - */ - @args.string({ description: 'The name of the model' }) - public model: string - - /** - * Import path to the model used in the factory - */ - @flags.string({ description: 'The path to the model' }) - public modelPath: string - - @flags.boolean({ - description: 'Create the factory with the exact name as provided', - alias: 'e', - }) - public exact: boolean - - /** - * Generate model import path used in the factory - */ - private generateModelImportPath() { - let base = this.application.rcFile.namespaces.models || 'App/Models' - if (!base.endsWith('/')) { - base += '/' - } - - let importPath = this.model - if (this.modelPath) { - importPath = this.modelPath - } else if (importPath.endsWith('Factory')) { - importPath = importPath.replace(/Factory$/, '') - } - - if (importPath.startsWith(base)) { - return importPath - } - - return base + importPath - } - - /** - * Path to the factories directory - */ - protected getDestinationPath() { - const base = this.application.rcFile.directories.database || 'database' - return join(base, 'factories') - } - - /** - * Passed down to the stub template - */ - protected templateData() { - return { - model: this.model, - modelImportPath: this.generateModelImportPath(), - toModelName: () => { - return function (model: string, render: any) { - return render(model).split('/').pop() - } - }, - } - } - - public async run() { - const stub = join(__dirname, '..', 'templates', 'factory.txt') - - this.generator - .addFile(this.model, { pattern: 'pascalcase', form: 'singular', suffix: 'Factory' }) - .stub(stub) - .useMustache() - .destinationDir(this.getDestinationPath()) - .appRoot(this.application.appRoot) - .apply(this.templateData()) - - await this.generator.run() - } -} diff --git a/commands/MakeMigration.ts b/commands/MakeMigration.ts deleted file mode 100644 index 43d9e107..00000000 --- a/commands/MakeMigration.ts +++ /dev/null @@ -1,157 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { join } from 'path' -import { string } from '@poppinss/utils/build/helpers' -import { BaseCommand, args, flags } from '@adonisjs/core/build/standalone' - -export default class MakeMigration extends BaseCommand { - public static commandName = 'make:migration' - public static description = 'Make a new migration file' - public static settings = { - loadApp: true, - } - - /** - * The name of the migration file. We use this to create the migration - * file and generate the table name - */ - @args.string({ description: 'Name of the migration file' }) - public name: string - - /** - * Choose a custom pre-defined connection. Otherwise, we use the - * default connection - */ - @flags.string({ - description: 'The connection flag is used to lookup the directory for the migration file', - }) - public connection: string - - /** - * Pre select migration directory. If this is defined, we will ignore the paths - * defined inside the config. - */ - @flags.string({ description: 'Pre-select a migration directory' }) - public folder: string - - /** - * Custom table name for creating a new table - */ - @flags.string({ description: 'Define the table name for creating a new table' }) - public create: string - - /** - * Custom table name for altering an existing table - */ - @flags.string({ description: 'Define the table name for altering an existing table' }) - public table: string - - /** - * Not a valid connection - */ - private printNotAValidConnection(connection: string) { - this.logger.error( - `"${connection}" is not a valid connection name. Double check "config/database" file` - ) - } - - /** - * Returns the directory for creating the migration file - */ - private async getDirectory(migrationPaths?: string[]): Promise { - if (this.folder) { - return this.folder - } - - let directories = migrationPaths?.length ? migrationPaths : ['database/migrations'] - if (directories.length === 1) { - return directories[0] - } - - return this.prompt.choice('Select the migrations folder', directories, { name: 'folder' }) - } - - /** - * Execute command - */ - public async run(): Promise { - const db = this.application.container.use('Adonis/Lucid/Database') - this.connection = this.connection || db.primaryConnectionName - const connection = db.getRawConnection(this.connection || db.primaryConnectionName) - - /** - * Invalid database connection - */ - if (!connection) { - this.printNotAValidConnection(this.connection) - this.exitCode = 1 - return - } - - /** - * Not allowed together, hence we must notify the user about the same - */ - if (this.table && this.create) { - this.logger.warning('--table and --create cannot be used together. Ignoring --create') - } - - /** - * The folder for creating the schema file - */ - const folder = await this.getDirectory((connection.config.migrations || {}).paths) - - /** - * Using the user defined table name or an empty string. We can attempt to - * build the table name from the migration file name, but let's do that - * later. - */ - const tableName = this.table || this.create || '' - - /** - * Template stub - */ - const stub = join( - __dirname, - '..', - 'templates', - this.table ? 'migration-alter.txt' : 'migration-make.txt' - ) - - /** - * Prepend timestamp to keep schema files in the order they - * have been created - */ - const prefix = `${new Date().getTime()}_` - - this.generator - .addFile(this.name, { pattern: 'snakecase', form: 'plural', prefix }) - .stub(stub) - .destinationDir(folder) - .appRoot(this.application.cliCwd || this.application.appRoot) - .useMustache() - .apply({ - toClassName() { - return function (filename: string, render: (text: string) => string) { - const migrationClassName = string.camelCase( - tableName || render(filename).replace(prefix, '') - ) - return `${migrationClassName.charAt(0).toUpperCase()}${migrationClassName.slice(1)}` - } - }, - toTableName() { - return function (filename: string, render: (text: string) => string) { - return tableName || string.snakeCase(render(filename).replace(prefix, '')) - } - }, - }) - - await this.generator.run() - } -} diff --git a/commands/MakeSeeder.ts b/commands/MakeSeeder.ts deleted file mode 100644 index 223ff47a..00000000 --- a/commands/MakeSeeder.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { join } from 'path' -import { BaseCommand, args } from '@adonisjs/core/build/standalone' - -export default class MakeSeeder extends BaseCommand { - public static commandName = 'make:seeder' - public static description = 'Make a new Seeder file' - - /** - * The name of the seeder file. - */ - @args.string({ description: 'Name of the seeder class' }) - public name: string - - /** - * Execute command - */ - public async run(): Promise { - const stub = join(__dirname, '..', 'templates', 'seeder.txt') - - const path = this.application.rcFile.directories.seeds - - this.generator - .addFile(this.name, { pattern: 'pascalcase', form: 'singular' }) - .stub(stub) - .destinationDir(path || 'database/Seeders') - .useMustache() - .appRoot(this.application.cliCwd || this.application.appRoot) - - await this.generator.run() - } -} diff --git a/commands/DbSeed.ts b/commands/db_seed.ts similarity index 84% rename from commands/DbSeed.ts rename to commands/db_seed.ts index f326b13e..8693fe8b 100644 --- a/commands/DbSeed.ts +++ b/commands/db_seed.ts @@ -8,21 +8,21 @@ */ import slash from 'slash' -import { extname } from 'path' -import { FileNode } from '@ioc:Adonis/Lucid/Database' -import { SeederFileNode } from '@ioc:Adonis/Lucid/Seeder' -import { BaseCommand, flags } from '@adonisjs/core/build/standalone' +import { extname } from 'node:path' +import { BaseCommand, flags } from '@adonisjs/core/ace' -import type { SeedsRunner } from '../src/SeedsRunner' +import { FileNode } from '../src/types/database.js' +import { SeederFileNode } from '../src/types/seeder.js' +import type { SeedsRunner } from '../src/seeders/runner.js' export default class DbSeed extends BaseCommand { - public static commandName = 'db:seed' - public static description = 'Execute database seeders' - public static settings = { + static commandName = 'db:seed' + static description = 'Execute database seeders' + static settings = { loadApp: true, } - private seeder: SeedsRunner + private declare seeder: SeedsRunner /** * Track if one or more seeders have failed @@ -34,32 +34,35 @@ export default class DbSeed extends BaseCommand { * default connection */ @flags.string({ description: 'Define a custom database connection for the seeders', alias: 'c' }) - public connection: string + declare connection: string /** * Interactive mode allows selecting seeder files */ @flags.boolean({ description: 'Run seeders in interactive mode', alias: 'i' }) - public interactive: boolean + declare interactive: boolean /** * Define a custom set of seeder files. Interactive and files together ignores * the interactive mode. */ - @flags.array({ description: 'Define a custom set of seeders files names to run', alias: 'f' }) - public files: string[] = [] + @flags.array({ + description: 'Define a custom set of seeders files names to run', + alias: 'f', + }) + declare files: string[] /** * Display migrations result in one compact single-line output */ @flags.boolean({ description: 'A compact single-line output' }) - public compactOutput: boolean = false + declare compactOutput: boolean /** * Print log message to the console */ private printLogMessage(file: SeederFileNode) { - const colors = this['colors'] + const colors = this.colors let color: keyof typeof colors = 'gray' let message: string = '' @@ -86,9 +89,9 @@ export default class DbSeed extends BaseCommand { break } - console.log(`${colors[color]('❯')} ${colors[color](message)} ${file.file.name}`) + this.logger.log(`${colors[color]('❯')} ${colors[color](message)} ${file.file.name}`) if (prefix) { - console.log(` ${colors[color](prefix)}`) + this.logger.log(` ${colors[color](prefix)}`) } } @@ -121,7 +124,7 @@ export default class DbSeed extends BaseCommand { * "--files" flag */ private async getCherryPickedFiles(seedersFiles: FileNode[]): Promise { - if (this.files.length) { + if (this.files && this.files.length) { return this.files.map((file) => { const fileExt = extname(file) return (fileExt ? file.replace(fileExt, '') : file).replace(/^\.\/|^\.\\\\/, '') @@ -142,9 +145,9 @@ export default class DbSeed extends BaseCommand { * Instantiate seeders runner */ private async instantiateSeeder() { - const db = this.application.container.use('Adonis/Lucid/Database') - const { SeedsRunner } = await import('../src/SeedsRunner') - this.seeder = new SeedsRunner(db, this.application, this.connection) + const db = await this.app.container.make('lucid.db') + const { SeedsRunner } = await import('../src/seeders/runner.js') + this.seeder = new SeedsRunner(db, this.app, this.connection) } /** @@ -216,7 +219,7 @@ export default class DbSeed extends BaseCommand { * process here */ private async runAsSubCommand() { - const db = this.application.container.use('Adonis/Lucid/Database') + const db = await this.app.container.make('lucid.db') this.connection = this.connection || db.primaryConnectionName /** @@ -262,7 +265,7 @@ export default class DbSeed extends BaseCommand { /** * Handle command */ - public async run(): Promise { + async run(): Promise { if (this.isMain) { await this.runAsMain() } else { @@ -274,7 +277,7 @@ export default class DbSeed extends BaseCommand { * Lifecycle method invoked by ace after the "run" * method. */ - public async completed() { + async completed() { if (this.seeder && this.isMain) { await this.seeder.close() } diff --git a/commands/DbTruncate.ts b/commands/db_truncate.ts similarity index 79% rename from commands/DbTruncate.ts rename to commands/db_truncate.ts index 62799b0a..4a0211cd 100644 --- a/commands/DbTruncate.ts +++ b/commands/db_truncate.ts @@ -7,13 +7,13 @@ * file that was distributed with this source code. */ -import { BaseCommand, flags } from '@adonisjs/core/build/standalone' -import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' +import { BaseCommand, flags } from '@adonisjs/core/ace' +import { QueryClientContract } from '../src/types/database.js' export default class DbTruncate extends BaseCommand { - public static commandName = 'db:truncate' - public static description = 'Truncate all tables in database' - public static settings = { + static commandName = 'db:truncate' + static description = 'Truncate all tables in database' + static settings = { loadApp: true, } @@ -22,13 +22,13 @@ export default class DbTruncate extends BaseCommand { * default connection */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Force command execution in production */ @flags.boolean({ description: 'Explicitly force command to run in production' }) - public force: boolean + declare force: boolean /** * Not a valid connection @@ -43,13 +43,6 @@ export default class DbTruncate extends BaseCommand { * Prompts to take consent when truncating the database in production */ private async takeProductionConstent(): Promise { - /** - * Do not prompt when CLI is not interactive - */ - if (!this.isInteractive) { - return false - } - const question = 'You are in production environment. Want to continue truncating the database?' try { return await this.prompt.confirm(question) @@ -74,7 +67,7 @@ export default class DbTruncate extends BaseCommand { * process inside this method */ private async runAsSubCommand() { - const db = this.application.container.use('Adonis/Lucid/Database') + const db = await this.app.container.make('lucid.db') this.connection = this.connection || db.primaryConnectionName const connection = db.connection(this.connection || db.primaryConnectionName) @@ -82,7 +75,7 @@ export default class DbTruncate extends BaseCommand { * Continue with clearing the database when not in production * or force flag is passed */ - let continueTruncate = !this.application.inProduction || this.force + let continueTruncate = !this.app.inProduction || this.force if (!continueTruncate) { continueTruncate = await this.takeProductionConstent() } @@ -119,7 +112,7 @@ export default class DbTruncate extends BaseCommand { /** * Handle command */ - public async run(): Promise { + async run(): Promise { if (this.isMain) { await this.runAsMain() } else { @@ -131,9 +124,10 @@ export default class DbTruncate extends BaseCommand { * Lifecycle method invoked by ace after the "run" * method. */ - public async completed() { + async completed() { if (this.isMain) { - await this.application.container.use('Adonis/Lucid/Database').manager.closeAll(true) + const db = await this.app.container.make('lucid.db') + await db.manager.closeAll(true) } } } diff --git a/commands/DbWipe.ts b/commands/db_wipe.ts similarity index 82% rename from commands/DbWipe.ts rename to commands/db_wipe.ts index 71a5132e..5aa727c1 100644 --- a/commands/DbWipe.ts +++ b/commands/db_wipe.ts @@ -7,13 +7,13 @@ * file that was distributed with this source code. */ -import { BaseCommand, flags } from '@adonisjs/core/build/standalone' -import { QueryClientContract } from '@ioc:Adonis/Lucid/Database' +import { BaseCommand, flags } from '@adonisjs/core/ace' +import { QueryClientContract } from '../src/types/database.js' export default class DbWipe extends BaseCommand { - public static commandName = 'db:wipe' - public static description = 'Drop all tables, views and types in database' - public static settings = { + static commandName = 'db:wipe' + static description = 'Drop all tables, views and types in database' + static settings = { loadApp: true, } @@ -22,25 +22,25 @@ export default class DbWipe extends BaseCommand { * default connection */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Drop all views in database */ @flags.boolean({ description: 'Drop all views' }) - public dropViews: boolean + declare dropViews: boolean /** * Drop all types in database */ @flags.boolean({ description: 'Drop all custom types (Postgres only)' }) - public dropTypes: boolean + declare dropTypes: boolean /** * Force command execution in production */ @flags.boolean({ description: 'Explicitly force command to run in production' }) - public force: boolean + declare force: boolean /** * Not a valid connection @@ -55,13 +55,6 @@ export default class DbWipe extends BaseCommand { * Prompts to take consent when wiping the database in production */ private async takeProductionConstent(): Promise { - /** - * Do not prompt when CLI is not interactive - */ - if (!this.isInteractive) { - return false - } - const question = 'You are in production environment. Want to continue wiping the database?' try { return await this.prompt.confirm(question) @@ -115,7 +108,7 @@ export default class DbWipe extends BaseCommand { * process inside this method */ private async runAsSubCommand() { - const db = this.application.container.use('Adonis/Lucid/Database') + const db = await this.app.container.make('lucid.db') this.connection = this.connection || db.primaryConnectionName const connection = db.connection(this.connection || db.primaryConnectionName) @@ -123,7 +116,7 @@ export default class DbWipe extends BaseCommand { * Continue with clearing the database when not in production * or force flag is passed */ - let continueWipe = !this.application.inProduction || this.force + let continueWipe = !this.app.inProduction || this.force if (!continueWipe) { continueWipe = await this.takeProductionConstent() } @@ -162,7 +155,7 @@ export default class DbWipe extends BaseCommand { /** * Handle command */ - public async run(): Promise { + async run(): Promise { if (this.isMain) { await this.runAsMain() } else { @@ -174,9 +167,10 @@ export default class DbWipe extends BaseCommand { * Lifecycle method invoked by ace after the "run" * method. */ - public async completed() { + async completed() { if (this.isMain) { - await this.application.container.use('Adonis/Lucid/Database').manager.closeAll(true) + const db = await this.app.container.make('lucid.db') + await db.manager.closeAll(true) } } } diff --git a/commands/make_factory.ts b/commands/make_factory.ts new file mode 100644 index 00000000..51f8edf8 --- /dev/null +++ b/commands/make_factory.ts @@ -0,0 +1,38 @@ +/* + * @adonisjs/assembler + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { stubsRoot } from '../stubs/main.js' +import { args, BaseCommand } from '@adonisjs/core/ace' + +/** + * Command to make a new Factory + */ +export default class MakeFactory extends BaseCommand { + static commandName = 'make:factory' + static description = 'Make a new factory' + + static options = { + allowUnknownFlags: true, + } + + /** + * Name of the model to be used in the factory + */ + @args.string({ description: 'Model name for which to create the factory' }) + declare model: string + + async run() { + const codemods = await this.createCodemods() + await codemods.makeUsingStub(stubsRoot, 'make/factory/main.stub', { + flags: this.parsed.flags, + entity: this.app.generators.createEntity(this.model), + model: this.app.generators.createEntity(this.model), + }) + } +} diff --git a/commands/make_migration.ts b/commands/make_migration.ts new file mode 100644 index 00000000..a2235849 --- /dev/null +++ b/commands/make_migration.ts @@ -0,0 +1,131 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { stubsRoot } from '../stubs/main.js' +import { args, BaseCommand, flags } from '@adonisjs/core/ace' + +export default class MakeMigration extends BaseCommand { + static commandName = 'make:migration' + static description = 'Make a new migration file' + static settings = { + loadApp: true, + allowUnknownFlags: true, + } + + /** + * The name of the migration file. We use this to create the migration + * file and generate the table name + */ + @args.string({ description: 'Name of the migration file' }) + declare name: string + + /** + * Choose a custom pre-defined connection. Otherwise, we use the + * default connection + */ + @flags.string({ + description: 'Select database connection for which to create the migration', + }) + declare connection: string + + /** + * Pre select migration directory. If this is defined, we will ignore the paths + * defined inside the config. + */ + @flags.string({ description: 'Select migration directory (if multiple sources are configured)' }) + declare folder: string + + /** + * Custom table name for creating a new table + */ + @flags.boolean({ description: 'Create a new default (Default action)' }) + declare create: boolean + + /** + * Custom table name for altering an existing table + */ + @flags.boolean({ description: 'Alter an existing table' }) + declare alter: boolean + + /** + * Not a valid connection + */ + private printNotAValidConnection(connection: string) { + this.logger.error( + `"${connection}" is not a valid connection name. Double check "config/database" file` + ) + } + + /** + * Returns the directory for creating the migration file + */ + private async getDirectory(migrationPaths?: string[]): Promise { + if (this.folder) { + return this.folder + } + + let directories = migrationPaths?.length ? migrationPaths : ['database/migrations'] + if (directories.length === 1) { + return directories[0] + } + + return this.prompt.choice('Select the migrations folder', directories, { name: 'folder' }) + } + + /** + * Execute command + */ + async run(): Promise { + const db = await this.app.container.make('lucid.db') + this.connection = this.connection || db.primaryConnectionName + const connection = db.getRawConnection(this.connection || db.primaryConnectionName) + + /** + * Invalid database connection + */ + if (!connection) { + this.printNotAValidConnection(this.connection) + this.exitCode = 1 + return + } + + /** + * Not allowed together, hence we must notify the user about the same + */ + if (this.alter && this.create) { + this.logger.warning('--alter and --create cannot be used together. Ignoring --create') + } + + /** + * Entity to create + */ + const entity = this.app.generators.createEntity(this.name) + + /** + * The folder for creating the schema file + */ + const folder = await this.getDirectory((connection.config.migrations || {}).paths) + + const prefix = new Date().getTime() + const action = this.alter ? 'alter' : 'create' + const tableName = this.app.generators.tableName(entity.name) + const fileName = `${prefix}_${action}_${tableName}_table` + + const codemods = await this.createCodemods() + await codemods.makeUsingStub(stubsRoot, `make/migration/${action}.stub`, { + entity, + flags: this.parsed.flags, + migration: { + tableName, + folder, + fileName, + }, + }) + } +} diff --git a/commands/MakeModel.ts b/commands/make_model.ts similarity index 67% rename from commands/MakeModel.ts rename to commands/make_model.ts index 1f2746dd..3f41fe52 100644 --- a/commands/MakeModel.ts +++ b/commands/make_model.ts @@ -7,13 +7,13 @@ * file that was distributed with this source code. */ -import { join } from 'path' -import { BaseCommand, args, flags } from '@adonisjs/core/build/standalone' +import { BaseCommand, args, flags } from '@adonisjs/core/ace' +import { stubsRoot } from '../stubs/main.js' export default class MakeModel extends BaseCommand { - public static commandName = 'make:model' - public static description = 'Make a new Lucid model' - public static settings = { + static commandName = 'make:model' + static description = 'Make a new Lucid model' + static settings = { loadApp: true, } @@ -21,7 +21,7 @@ export default class MakeModel extends BaseCommand { * The name of the model file. */ @args.string({ description: 'Name of the model class' }) - public name: string + declare name: string /** * Defines if we generate the migration for the model. @@ -31,7 +31,7 @@ export default class MakeModel extends BaseCommand { alias: 'm', description: 'Generate the migration for the model', }) - public migration: boolean + declare migration: boolean /** * Defines if we generate the controller for the model. @@ -41,7 +41,7 @@ export default class MakeModel extends BaseCommand { alias: 'c', description: 'Generate the controller for the model', }) - public controller: boolean + declare controller: boolean /** * Defines if we generate the factory for the model. @@ -51,13 +51,13 @@ export default class MakeModel extends BaseCommand { alias: 'f', description: 'Generate a factory for the model', }) - public factory: boolean + declare factory: boolean /** * Run migrations */ private async runMakeMigration() { - if (!this.migration) { + if (!this.migration || this.exitCode) { return } @@ -70,7 +70,7 @@ export default class MakeModel extends BaseCommand { * Make controller */ private async runMakeController() { - if (!this.controller) { + if (!this.controller || this.exitCode) { return } @@ -83,7 +83,7 @@ export default class MakeModel extends BaseCommand { * Make factory */ private async runMakeFactory() { - if (!this.factory) { + if (!this.factory || this.exitCode) { return } @@ -95,24 +95,14 @@ export default class MakeModel extends BaseCommand { /** * Execute command */ - public async run(): Promise { - const stub = join(__dirname, '..', 'templates', 'model.txt') - const path = this.application.resolveNamespaceDirectory('models') - - this.generator - .addFile(this.name, { pattern: 'pascalcase', form: 'singular' }) - .stub(stub) - .destinationDir(path || 'app/Models') - .useMustache() - .appRoot(this.application.cliCwd || this.application.appRoot) - - await this.generator.run() + async run(): Promise { + const codemods = await this.createCodemods() + await codemods.makeUsingStub(stubsRoot, 'make/model/main.stub', { + flags: this.parsed.flags, + entity: this.app.generators.createEntity(this.name), + }) await this.runMakeMigration() - if (this.exitCode) { - return - } - await this.runMakeController() await this.runMakeFactory() } diff --git a/commands/make_seeder.ts b/commands/make_seeder.ts new file mode 100644 index 00000000..57a36b6b --- /dev/null +++ b/commands/make_seeder.ts @@ -0,0 +1,33 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { BaseCommand, args } from '@adonisjs/core/ace' +import { stubsRoot } from '../stubs/main.js' + +export default class MakeSeeder extends BaseCommand { + static commandName = 'make:seeder' + static description = 'Make a new Seeder file' + + /** + * The name of the seeder file. + */ + @args.string({ description: 'Name of the seeder class' }) + declare name: string + + /** + * Execute command + */ + async run(): Promise { + const codemods = await this.createCodemods() + await codemods.makeUsingStub(stubsRoot, 'make/seeder/main.stub', { + flags: this.parsed.flags, + entity: this.app.generators.createEntity(this.name), + }) + } +} diff --git a/commands/Migration/Base.ts b/commands/migration/base.ts similarity index 84% rename from commands/Migration/Base.ts rename to commands/migration/base.ts index a144598c..89deb26e 100644 --- a/commands/Migration/Base.ts +++ b/commands/migration/base.ts @@ -8,11 +8,12 @@ */ import prettyHrTime from 'pretty-hrtime' -import { BaseCommand } from '@adonisjs/core/build/standalone' -import { MigratedFileNode, MigratorContract } from '@ioc:Adonis/Lucid/Migrator' +import { BaseCommand } from '@adonisjs/core/ace' -import { getDDLMethod } from '../../src/utils' -import { prettyPrint } from '../../src/Helpers/prettyPrint' +import { getDDLMethod } from '../../src/utils/index.js' +import type { MigrationRunner } from '../../src/migration/runner.js' +import { prettyPrint } from '../../src/helpers/pretty_print.js' +import { MigratedFileNode } from '../../src/types/migrator.js' /** * Base class to execute migrations and print logs @@ -36,13 +37,6 @@ export default abstract class MigrationsBase extends BaseCommand { * Prompts to take consent for running migrations in production */ protected async takeProductionConstent(): Promise { - /** - * Do not prompt when CLI is not interactive - */ - if (!this.isInteractive) { - return false - } - const question = 'You are in production environment. Want to continue running migrations?' try { return await this.prompt.confirm(question) @@ -75,8 +69,8 @@ export default abstract class MigrationsBase extends BaseCommand { * Pretty print sql queries of a file */ private prettyPrintSql(file: MigratedFileNode, connectionName: string) { - console.log(this.logger.colors.gray(`------------- ${file.file.name} -------------`)) - console.log() + this.logger.log(this.colors.gray(`------------- ${file.file.name} -------------`)) + this.logger.log('') file.queries.map((sql) => { prettyPrint({ connection: connectionName, @@ -85,24 +79,24 @@ export default abstract class MigrationsBase extends BaseCommand { method: getDDLMethod(sql), bindings: [], }) - console.log() + this.logger.log('') }) - console.log(this.logger.colors.gray('------------- END -------------')) + this.logger.log(this.colors.gray('------------- END -------------')) } /** * Log final status with verbose output */ - private logVerboseFinalStatus(migrator: MigratorContract, duration?: [number, number]) { + private logVerboseFinalStatus(migrator: MigrationRunner, duration?: [number, number]) { switch (migrator.status) { case 'completed': const completionMessage = migrator.direction === 'up' ? 'Migrated in' : 'Reverted in' - console.log(`\n${completionMessage} ${this.colors.cyan(prettyHrTime(duration))}`) + this.logger.log(`\n${completionMessage} ${this.colors.cyan(prettyHrTime(duration!))}`) break case 'skipped': const message = migrator.direction === 'up' ? 'Already up to date' : 'Already at latest batch' - console.log(this.colors.cyan(message)) + this.logger.log(this.colors.cyan(message)) break case 'error': this.logger.fatal(migrator.error!) @@ -116,7 +110,7 @@ export default abstract class MigrationsBase extends BaseCommand { */ private logCompactFinalStatus( processedFiles: Set, - migrator: MigratorContract, + migrator: MigrationRunner, duration?: [number, number] ) { let output = '' @@ -126,7 +120,7 @@ export default abstract class MigrationsBase extends BaseCommand { switch (migrator.status) { case 'completed': message = `❯ ${isUp ? 'Executed' : 'Reverted'} ${processedFiles.size} migrations` - output = this.colors.grey(message + ` (${prettyHrTime(duration)})`) + output = this.colors.grey(message + ` (${prettyHrTime(duration!)})`) break @@ -141,8 +135,8 @@ export default abstract class MigrationsBase extends BaseCommand { ).length message = `❯ Executed ${processedFiles.size} migrations, 1 error, ${skippedMigrations} skipped` - console.log(this.colors.red(message)) - console.log('\n' + this.colors.red(migrator.error!.message)) + this.logger.log(this.colors.red(message)) + this.logger.log('\n' + this.colors.red(migrator.error!.message)) this.exitCode = 1 break } @@ -153,7 +147,7 @@ export default abstract class MigrationsBase extends BaseCommand { /** * Runs the migrations using the migrator */ - protected async runMigrations(migrator: MigratorContract, connectionName: string): Promise { + protected async runMigrations(migrator: MigrationRunner, connectionName: string): Promise { /** * Pretty print SQL in dry run and return early */ diff --git a/commands/Migration/Fresh.ts b/commands/migration/fresh.ts similarity index 86% rename from commands/Migration/Fresh.ts rename to commands/migration/fresh.ts index 1c47baca..3fec73b7 100644 --- a/commands/Migration/Fresh.ts +++ b/commands/migration/fresh.ts @@ -7,16 +7,16 @@ * file that was distributed with this source code. */ -import { flags, BaseCommand } from '@adonisjs/core/build/standalone' +import { flags, BaseCommand } from '@adonisjs/core/ace' /** * This command reset the database by rolling back to batch 0 and then * re-run all migrations. */ export default class Refresh extends BaseCommand { - public static commandName = 'migration:fresh' - public static description = 'Drop all tables and re-migrate the database' - public static settings = { + static commandName = 'migration:fresh' + static description = 'Drop all tables and re-migrate the database' + static settings = { loadApp: true, } @@ -24,37 +24,37 @@ export default class Refresh extends BaseCommand { * Custom connection for running migrations. */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Force command execution in production */ @flags.boolean({ description: 'Explicitly force command to run in production' }) - public force: boolean + declare force: boolean /** * Run seeders */ @flags.boolean({ description: 'Run seeders' }) - public seed: boolean + declare seed: boolean /** * Drop all views in database */ @flags.boolean({ description: 'Drop all views' }) - public dropViews: boolean + declare dropViews: boolean /** * Drop all types in database */ @flags.boolean({ description: 'Drop all custom types (Postgres only)' }) - public dropTypes: boolean + declare dropTypes: boolean /** * Disable advisory locks */ @flags.boolean({ description: 'Disable locks acquired to run migrations safely' }) - public disableLocks: boolean + declare disableLocks: boolean /** * Converting command properties to arguments @@ -127,7 +127,7 @@ export default class Refresh extends BaseCommand { /** * Handle command */ - public async run(): Promise { + async run(): Promise { await this.runDbWipe() if (this.exitCode) { return diff --git a/commands/Migration/Refresh.ts b/commands/migration/refresh.ts similarity index 86% rename from commands/Migration/Refresh.ts rename to commands/migration/refresh.ts index 28d852cd..f996c5fb 100644 --- a/commands/Migration/Refresh.ts +++ b/commands/migration/refresh.ts @@ -7,16 +7,16 @@ * file that was distributed with this source code. */ -import { flags, BaseCommand } from '@adonisjs/core/build/standalone' +import { flags, BaseCommand } from '@adonisjs/core/ace' /** * This command reset the database by rolling back to batch 0 and then * re-run all migrations. */ export default class Refresh extends BaseCommand { - public static commandName = 'migration:refresh' - public static description = 'Rollback and migrate database' - public static settings = { + static commandName = 'migration:refresh' + static description = 'Rollback and migrate database' + static settings = { loadApp: true, } @@ -24,31 +24,31 @@ export default class Refresh extends BaseCommand { * Custom connection for running migrations. */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Force command execution in production */ @flags.boolean({ description: 'Explicitly force command to run in production' }) - public force: boolean + declare force: boolean /** * Perform dry run */ @flags.boolean({ description: 'Do not run actual queries. Instead view the SQL output' }) - public dryRun: boolean + declare dryRun: boolean /** * Run seeders */ @flags.boolean({ description: 'Run seeders' }) - public seed: boolean + declare seed: boolean /** * Disable advisory locks */ @flags.boolean({ description: 'Disable locks acquired to run migrations safely' }) - public disableLocks: boolean + declare disableLocks: boolean /** * Converting command properties to arguments @@ -109,7 +109,7 @@ export default class Refresh extends BaseCommand { /** * Handle command */ - public async run(): Promise { + async run(): Promise { await this.resetMigrations() if (this.exitCode) { return diff --git a/commands/Migration/Reset.ts b/commands/migration/reset.ts similarity index 81% rename from commands/Migration/Reset.ts rename to commands/migration/reset.ts index 09d5a90e..2599e023 100644 --- a/commands/Migration/Reset.ts +++ b/commands/migration/reset.ts @@ -7,16 +7,16 @@ * file that was distributed with this source code. */ -import { BaseCommand, flags } from '@adonisjs/core/build/standalone' +import { BaseCommand, flags } from '@adonisjs/core/ace' /** * This command resets the database by rolling back to batch 0. Same * as calling "migration:rollback --batch=0" */ export default class Reset extends BaseCommand { - public static commandName = 'migration:reset' - public static description = 'Rollback all migrations' - public static settings = { + static commandName = 'migration:reset' + static description = 'Rollback all migrations' + static settings = { loadApp: true, } @@ -24,25 +24,25 @@ export default class Reset extends BaseCommand { * Custom connection for running migrations. */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Force command execution in production */ @flags.boolean({ description: 'Explicitly force command to run in production' }) - public force: boolean + declare force: boolean /** * Perform dry run */ @flags.boolean({ description: 'Do not run actual queries. Instead view the SQL output' }) - public dryRun: boolean + declare dryRun: boolean /** * Disable advisory locks */ @flags.boolean({ description: 'Disable locks acquired to run migrations safely' }) - public disableLocks: boolean + declare disableLocks: boolean /** * Converting command properties to arguments @@ -71,7 +71,7 @@ export default class Reset extends BaseCommand { /** * Handle command */ - public async run(): Promise { + async run(): Promise { const rollback = await this.kernel.exec('migration:rollback', this.getArgs()) this.exitCode = rollback.exitCode this.error = rollback.error diff --git a/commands/Migration/Rollback.ts b/commands/migration/rollback.ts similarity index 71% rename from commands/Migration/Rollback.ts rename to commands/migration/rollback.ts index f06f630e..9e373acf 100644 --- a/commands/Migration/Rollback.ts +++ b/commands/migration/rollback.ts @@ -7,41 +7,41 @@ * file that was distributed with this source code. */ -import { flags } from '@adonisjs/core/build/standalone' -import { MigratorContract } from '@ioc:Adonis/Lucid/Migrator' +import { flags } from '@adonisjs/core/ace' -import MigrationsBase from './Base' +import MigrationsBase from './base.js' +import { MigrationRunner } from '../../src/migration/runner.js' /** * The command is meant to migrate the database by executing migrations * in `down` direction. */ export default class Migrate extends MigrationsBase { - public static commandName = 'migration:rollback' - public static description = 'Rollback migrations to a specific batch number' - public static settings = { + static commandName = 'migration:rollback' + static description = 'Rollback migrations to a specific batch number' + static settings = { loadApp: true, } - private migrator: MigratorContract + private migrator?: MigrationRunner /** * Custom connection for running migrations. */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Force run migrations in production */ @flags.boolean({ description: 'Explictly force to run migrations in production' }) - public force: boolean + declare force: boolean /** * Perform dry run */ @flags.boolean({ description: 'Do not run actual queries. Instead view the SQL output' }) - public dryRun: boolean + declare dryRun: boolean /** * Define custom batch, instead of rolling back to the latest batch @@ -49,28 +49,27 @@ export default class Migrate extends MigrationsBase { @flags.number({ description: 'Define custom batch number for rollback. Use 0 to rollback to initial state', }) - public batch: number + declare batch: number /** * Display migrations result in one compact single-line output */ @flags.boolean({ description: 'A compact single-line output' }) - public compactOutput: boolean = false + declare compactOutput: boolean /** * Disable advisory locks */ @flags.boolean({ description: 'Disable locks acquired to run migrations safely' }) - public disableLocks: boolean + declare disableLocks: boolean /** * Instantiating the migrator instance */ - private instantiateMigrator() { - const db = this.application.container.use('Adonis/Lucid/Database') - const Migrator = this.application.container.resolveBinding('Adonis/Lucid/Migrator') + private async instantiateMigrator() { + const db = await this.app.container.make('lucid.db') - this.migrator = new Migrator(db, this.application, { + this.migrator = new MigrationRunner(db, this.app, { direction: 'down', connectionName: this.connection, batch: this.batch, @@ -84,14 +83,14 @@ export default class Migrate extends MigrationsBase { * process inside this method */ private async runAsSubCommand() { - const db = this.application.container.use('Adonis/Lucid/Database') + const db = await this.app.container.make('lucid.db') this.connection = this.connection || db.primaryConnectionName /** * Continue with migrations when not in prod or force flag * is passed */ - let continueMigrations = !this.application.inProduction || this.force + let continueMigrations = !this.app.inProduction || this.force if (!continueMigrations) { continueMigrations = await this.takeProductionConstent() } @@ -112,8 +111,8 @@ export default class Migrate extends MigrationsBase { return } - this.instantiateMigrator() - await this.runMigrations(this.migrator, this.connection) + await this.instantiateMigrator() + await this.runMigrations(this.migrator!, this.connection) } /** @@ -129,7 +128,7 @@ export default class Migrate extends MigrationsBase { /** * Handle command */ - public async run(): Promise { + async run(): Promise { if (this.isMain) { await this.runAsMain() } else { @@ -141,7 +140,7 @@ export default class Migrate extends MigrationsBase { * Lifecycle method invoked by ace after the "run" * method. */ - public async completed() { + async completed() { if (this.migrator && this.isMain) { await this.migrator.close() } diff --git a/commands/Migration/Run.ts b/commands/migration/run.ts similarity index 70% rename from commands/Migration/Run.ts rename to commands/migration/run.ts index b7366523..7366140c 100644 --- a/commands/Migration/Run.ts +++ b/commands/migration/run.ts @@ -7,61 +7,60 @@ * file that was distributed with this source code. */ -import { flags } from '@adonisjs/core/build/standalone' -import { MigratorContract } from '@ioc:Adonis/Lucid/Migrator' -import MigrationsBase from './Base' +import { flags } from '@adonisjs/core/ace' +import MigrationsBase from './base.js' +import { MigrationRunner } from '../../src/migration/runner.js' /** * The command is meant to migrate the database by executing migrations * in `up` direction. */ export default class Migrate extends MigrationsBase { - public static commandName = 'migration:run' - public static description = 'Migrate database by running pending migrations' - public static settings = { + static commandName = 'migration:run' + static description = 'Migrate database by running pending migrations' + static settings = { loadApp: true, } - private migrator: MigratorContract + private migrator?: MigrationRunner /** * Custom connection for running migrations. */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Force run migrations in production */ @flags.boolean({ description: 'Explicitly force to run migrations in production' }) - public force: boolean + declare force: boolean /** * Perform dry run */ @flags.boolean({ description: 'Do not run actual queries. Instead view the SQL output' }) - public dryRun: boolean + declare dryRun: boolean /** * Display migrations result in one compact single-line output */ @flags.boolean({ description: 'A compact single-line output' }) - public compactOutput: boolean = false + compactOutput: boolean = false /** * Disable advisory locks */ @flags.boolean({ description: 'Disable locks acquired to run migrations safely' }) - public disableLocks: boolean + declare disableLocks: boolean /** * Instantiating the migrator instance */ - private instantiateMigrator() { - const db = this.application.container.use('Adonis/Lucid/Database') - const Migrator = this.application.container.resolveBinding('Adonis/Lucid/Migrator') + private async instantiateMigrator() { + const db = await this.app.container.make('lucid.db') - this.migrator = new Migrator(db, this.application, { + this.migrator = new MigrationRunner(db, this.app, { direction: 'up', connectionName: this.connection, dryRun: this.dryRun, @@ -74,14 +73,14 @@ export default class Migrate extends MigrationsBase { * process inside this method */ private async runAsSubCommand() { - const db = this.application.container.use('Adonis/Lucid/Database') + const db = await this.app.container.make('lucid.db') this.connection = this.connection || db.primaryConnectionName /** * Continue with migrations when not in prod or force flag * is passed */ - let continueMigrations = !this.application.inProduction || this.force + let continueMigrations = !this.app.inProduction || this.force if (!continueMigrations) { continueMigrations = await this.takeProductionConstent() } @@ -102,8 +101,8 @@ export default class Migrate extends MigrationsBase { return } - this.instantiateMigrator() - await this.runMigrations(this.migrator, this.connection) + await this.instantiateMigrator() + await this.runMigrations(this.migrator!, this.connection) } /** @@ -119,7 +118,7 @@ export default class Migrate extends MigrationsBase { /** * Handle command */ - public async run(): Promise { + async run(): Promise { if (this.isMain) { await this.runAsMain() } else { @@ -131,7 +130,7 @@ export default class Migrate extends MigrationsBase { * Lifecycle method invoked by ace after the "run" * method. */ - public async completed() { + async completed() { if (this.migrator && this.isMain) { await this.migrator.close() } diff --git a/commands/Migration/Status.ts b/commands/migration/status.ts similarity index 76% rename from commands/Migration/Status.ts rename to commands/migration/status.ts index 4cfe0a1b..2f16f7d0 100644 --- a/commands/Migration/Status.ts +++ b/commands/migration/status.ts @@ -7,27 +7,28 @@ * file that was distributed with this source code. */ -import { flags, BaseCommand } from '@adonisjs/core/build/standalone' -import { MigrationListNode, MigratorContract } from '@ioc:Adonis/Lucid/Migrator' +import { flags, BaseCommand } from '@adonisjs/core/ace' +import { MigrationListNode } from '../../src/types/migrator.js' +import { MigrationRunner } from '../../src/migration/runner.js' /** * The command is meant to migrate the database by execute migrations * in `up` direction. */ export default class Status extends BaseCommand { - public static commandName = 'migration:status' - public static description = 'View migrations status' - public static settings = { + static commandName = 'migration:status' + static description = 'View migrations status' + static settings = { loadApp: true, } - private migrator: MigratorContract + private migrator?: MigrationRunner /** * Define custom connection */ @flags.string({ description: 'Define a custom database connection', alias: 'c' }) - public connection: string + declare connection: string /** * Not a valid connection @@ -55,11 +56,10 @@ export default class Status extends BaseCommand { /** * Instantiating the migrator instance */ - private instantiateMigrator() { - const db = this.application.container.use('Adonis/Lucid/Database') - const Migrator = this.application.container.resolveBinding('Adonis/Lucid/Migrator') + private async instantiateMigrator() { + const db = await this.app.container.make('lucid.db') - this.migrator = new Migrator(db, this.application, { + this.migrator = new MigrationRunner(db, this.app, { direction: 'up', connectionName: this.connection, }) @@ -92,7 +92,7 @@ export default class Status extends BaseCommand { * process inside this method */ private async runAsSubCommand() { - const db = this.application.container.use('Adonis/Lucid/Database') + const db = await this.app.container.make('lucid.db') this.connection = this.connection || db.primaryConnectionName /** @@ -104,8 +104,8 @@ export default class Status extends BaseCommand { return } - this.instantiateMigrator() - this.renderList(await this.migrator.getList()) + await this.instantiateMigrator() + this.renderList(await this.migrator!.getList()) } /** @@ -121,7 +121,7 @@ export default class Status extends BaseCommand { /** * Handle command */ - public async run(): Promise { + async run(): Promise { if (this.isMain) { await this.runAsMain() } else { @@ -133,7 +133,7 @@ export default class Status extends BaseCommand { * Lifecycle method invoked by ace after the "run" * method. */ - public async completed() { + async completed() { if (this.migrator && this.isMain) { await this.migrator.close() } diff --git a/example/index.ts b/example/index.ts index 5270c4c6..ddb852d9 100644 --- a/example/index.ts +++ b/example/index.ts @@ -1,9 +1,9 @@ import { DateTime } from 'luxon' import { BaseModel } from '../src/orm/base_model/index.js' import { column, hasOne } from '../src/orm/decorators/index.js' -import { HasOne } from '../adonis-typings/relations.js' +import { HasOne } from '../src/types/relations.js' import { scope } from '../src/helpers/scope.js' -import { ModelQueryBuilderContract } from '../adonis-typings/model.js' +import { ModelQueryBuilderContract } from '../src/types/model.js' // import Factory from '@ioc:Adonis/Lucid/Factory' enum ProfileTypes { diff --git a/package.json b/package.json index 3cde9e64..6aee925e 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,15 @@ "node": ">=18.16.0" }, "type": "module", + "exports": { + "./schema": "./build/src/schema/main.js", + "./factories": "./build/src/factories/main.js", + "./database": "./build/src/database/main.js", + "./orm": "./build/src/orm/main.js", + "./seeders": "./build/src/seeders/main.js", + "./services/*": "./build/services/*.js", + "./types/*": "./build/types/*.js" + }, "scripts": { "pretest": "npm run lint", "test:better_sqlite": "DB=better_sqlite node --enable-source-maps --loader=ts-node/esm ./bin/test.js", diff --git a/providers/DatabaseProvider.ts b/providers/DatabaseProvider.ts deleted file mode 100644 index f5b8f402..00000000 --- a/providers/DatabaseProvider.ts +++ /dev/null @@ -1,199 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -/** - * Database service provider - */ -export default class DatabaseServiceProvider { - constructor(protected app: ApplicationContract) {} - public static needsApplication = true - - /** - * Register the database binding - */ - private registerDatabase() { - this.app.container.singleton('Adonis/Lucid/Database', () => { - const config = this.app.container.resolveBinding('Adonis/Core/Config').get('database', {}) - const Logger = this.app.container.resolveBinding('Adonis/Core/Logger') - const Profiler = this.app.container.resolveBinding('Adonis/Core/Profiler') - const Emitter = this.app.container.resolveBinding('Adonis/Core/Event') - - const { Database } = require('../src/Database') - return new Database(config, Logger, Profiler, Emitter) - }) - } - - /** - * Registers ORM - */ - private registerOrm() { - this.app.container.singleton('Adonis/Lucid/Orm', () => { - const { Adapter } = require('../src/Orm/Adapter') - const { scope } = require('../src/Helpers/scope') - const decorators = require('../src/Orm/Decorators') - const { BaseModel } = require('../src/Orm/BaseModel') - const { ModelPaginator } = require('../src/Orm/Paginator') - const { SnakeCaseNamingStrategy } = require('../src/Orm/NamingStrategies/SnakeCase') - - /** - * Attaching adapter to the base model. Each model is allowed to define - * a different adapter. - */ - BaseModel.$adapter = new Adapter(this.app.container.resolveBinding('Adonis/Lucid/Database')) - BaseModel.$container = this.app.container - - return { - BaseModel, - ModelPaginator, - SnakeCaseNamingStrategy, - scope, - ...decorators, - } - }) - } - - /** - * Registers schema class - */ - private registerSchema() { - this.app.container.singleton('Adonis/Lucid/Schema', () => { - const { Schema } = require('../src/Schema') - return Schema - }) - } - - /** - * Registers schema class - */ - private registerFactory() { - this.app.container.singleton('Adonis/Lucid/Factory', () => { - const { FactoryManager } = require('../src/Factory') - return new FactoryManager() - }) - } - - /** - * Registers schema class - */ - private registerBaseSeeder() { - this.app.container.singleton('Adonis/Lucid/Seeder', () => { - const { BaseSeeder } = require('../src/BaseSeeder') - return BaseSeeder - }) - } - - /** - * Registers the health checker - */ - private registerHealthChecker() { - /** - * Do not register health checks in the repl environment - */ - if (this.app.environment === 'repl') { - return - } - - this.app.container.withBindings( - ['Adonis/Core/HealthCheck', 'Adonis/Lucid/Database'], - (HealthCheck, Db) => { - if (Db.hasHealthChecksEnabled) { - HealthCheck.addChecker('lucid', 'Adonis/Lucid/Database') - } - } - ) - } - - /** - * Register the migrator used for database migration - */ - private registerMigrator() { - this.app.container.bind('Adonis/Lucid/Migrator', () => { - const { Migrator } = require('../src/Migrator') - return Migrator - }) - } - - /** - * Extends the validator by defining validation rules - */ - private defineValidationRules() { - /** - * Do not register validation rules in the "repl" environment - */ - if (this.app.environment === 'repl') { - return - } - - this.app.container.withBindings( - ['Adonis/Core/Validator', 'Adonis/Lucid/Database', 'Adonis/Core/Logger'], - (Validator, Db, Logger) => { - const { extendValidator } = require('../src/Bindings/Validator') - extendValidator(Validator.validator, Db, Logger) - } - ) - } - - /** - * Defines REPL bindings - */ - private defineReplBindings() { - if (this.app.environment !== 'repl') { - return - } - - this.app.container.withBindings(['Adonis/Addons/Repl'], (Repl) => { - const { defineReplBindings } = require('../src/Bindings/Repl') - defineReplBindings(this.app, Repl) - }) - } - - /** - * Define test utilities for database - */ - private defineTestUtils() { - this.app.container.withBindings( - ['Adonis/Core/TestUtils', 'Adonis/Core/Ace'], - (testUtils, ace) => { - const { defineTestUtils } = require('../src/Bindings/TestUtils') - return new defineTestUtils(testUtils, ace) - } - ) - } - - /** - * Called when registering providers - */ - public register(): void { - this.registerDatabase() - this.registerOrm() - this.registerSchema() - this.registerFactory() - this.registerBaseSeeder() - this.registerMigrator() - } - - /** - * Called when all bindings are in place - */ - public boot(): void { - this.registerHealthChecker() - this.defineValidationRules() - this.defineReplBindings() - this.defineTestUtils() - } - - /** - * Gracefully close connections during shutdown - */ - public async shutdown() { - await this.app.container.resolveBinding('Adonis/Lucid/Database').manager.closeAll() - } -} diff --git a/providers/database_provider.ts b/providers/database_provider.ts new file mode 100644 index 00000000..7f096e16 --- /dev/null +++ b/providers/database_provider.ts @@ -0,0 +1,43 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import type { ApplicationService } from '@adonisjs/core/types' + +import { Database } from '../src/database/main.js' +import { QueryClient } from '../src/query_client/index.js' +import type { DatabaseConfig } from '../src/types/database.js' + +declare module '@adonisjs/core/types' { + export interface ContainerBindings { + 'lucid.db': Database + } +} + +/** + * Database service provider + */ +export default class DatabaseServiceProvider { + constructor(protected app: ApplicationService) {} + + register() { + this.app.container.singleton(Database, async (resolver) => { + const config = this.app.config.get('database') + const emitter = await resolver.make('emitter') + const logger = await resolver.make('logger') + return new Database(config, logger, emitter) + }) + + this.app.container.singleton(QueryClient, async (resolver) => { + const db = await resolver.make('lucid.db') + return db.connection() as QueryClient + }) + + this.app.container.alias('lucid.db', Database) + } +} diff --git a/services/db.ts b/services/db.ts new file mode 100644 index 00000000..87769955 --- /dev/null +++ b/services/db.ts @@ -0,0 +1,23 @@ +/* + * @adonisjs/lucid + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import app from '@adonisjs/core/services/app' +import { Database } from '../src/database/main.js' + +let db: Database + +/** + * Returns a singleton instance of the Database class from the + * container + */ +await app.booted(async () => { + db = await app.container.make(Database) +}) + +export { db as default } diff --git a/src/connection/index.ts b/src/connection/index.ts index b3fa9e68..6ccce980 100644 --- a/src/connection/index.ts +++ b/src/connection/index.ts @@ -15,7 +15,7 @@ import { patchKnex } from 'knex-dynamic-connection' import type { Logger } from '@adonisjs/core/logger' // @ts-expect-error import { resolveClientNameWithAliases } from 'knex/lib/util/helpers.js' -import { ConnectionConfig, ConnectionContract, ReportNode } from '../../adonis-typings/database.js' +import { ConnectionConfig, ConnectionContract, ReportNode } from '../types/database.js' import { Logger as ConnectionLogger } from './logger.js' diff --git a/src/connection/manager.ts b/src/connection/manager.ts index 88bde2f8..42a68238 100644 --- a/src/connection/manager.ts +++ b/src/connection/manager.ts @@ -17,7 +17,7 @@ import { ConnectionConfig, ConnectionContract, ConnectionManagerContract, -} from '../../adonis-typings/database.js' +} from '../types/database.js' import { Connection } from './index.js' diff --git a/src/database/index.ts b/src/database/main.ts similarity index 93% rename from src/database/index.ts rename to src/database/main.ts index 59c55ce3..bf7a5d38 100644 --- a/src/database/index.ts +++ b/src/database/main.ts @@ -7,8 +7,8 @@ * file that was distributed with this source code. */ -import { Exception } from '@poppinss/utils' import Macroable from '@poppinss/macroable' +import { Exception } from '@poppinss/utils' import type { Emitter } from '@adonisjs/core/events' import type { Logger } from '@adonisjs/core/logger' @@ -19,8 +19,9 @@ import { DatabaseClientOptions, TransactionClientContract, ConnectionManagerContract, -} from '../../adonis-typings/database.js' +} from '../types/database.js' +import { LucidModel } from '../types/model.js' import { QueryClient } from '../query_client/index.js' import { RawBuilder } from './static_builder/raw.js' import { prettyPrint } from '../helpers/pretty_print.js' @@ -29,20 +30,14 @@ import { InsertQueryBuilder } from './query_builder/insert.js' import { ReferenceBuilder } from './static_builder/reference.js' import { SimplePaginator } from './paginator/simple_paginator.js' import { DatabaseQueryBuilder } from './query_builder/database.js' -import { ModelQueryBuilder } from '../orm/query_builder/index.js' -import { LucidModel } from '../../adonis-typings/model.js' + +export { DatabaseQueryBuilder, InsertQueryBuilder, SimplePaginator, QueryClient } /** * Database class exposes the API to manage multiple connections and obtain an instance * of query/transaction clients. */ export class Database extends Macroable { - /** - * Reference to self constructor. TypeScript sucks with "this.constructor" - * https://github.com/microsoft/TypeScript/issues/4586 - */ - Database = Database - /** * Reference to connections manager */ @@ -53,15 +48,6 @@ export class Database extends Macroable { */ primaryConnectionName: string - /** - * Reference to query builders. We expose them, so that they can be - * extended from outside using macros. - */ - DatabaseQueryBuilder = DatabaseQueryBuilder - InsertQueryBuilder = InsertQueryBuilder - ModelQueryBuilder = ModelQueryBuilder - SimplePaginator = SimplePaginator - /** * A store of global transactions */ diff --git a/src/database/paginator/simple_paginator.ts b/src/database/paginator/simple_paginator.ts index e313aaae..72afda9c 100644 --- a/src/database/paginator/simple_paginator.ts +++ b/src/database/paginator/simple_paginator.ts @@ -8,10 +8,7 @@ */ import { stringify } from 'qs' -import { - SimplePaginatorContract, - SimplePaginatorMetaKeys, -} from '../../../adonis-typings/querybuilder.js' +import { SimplePaginatorContract, SimplePaginatorMetaKeys } from '../../types/querybuilder.js' import { SnakeCaseNamingStrategy } from '../../Orm/naming_strategies/snake_case.js' /** diff --git a/src/database/query_builder/chainable.ts b/src/database/query_builder/chainable.ts index b709f11e..1743e623 100644 --- a/src/database/query_builder/chainable.ts +++ b/src/database/query_builder/chainable.ts @@ -10,7 +10,7 @@ import { Knex } from 'knex' import Macroable from '@poppinss/macroable' import { Exception } from '@poppinss/utils' -import { ChainableContract, DBQueryCallback } from '../../../adonis-typings/querybuilder.js' +import { ChainableContract, DBQueryCallback } from '../../types/querybuilder.js' import { isObject } from '../../utils/index.js' import { RawQueryBuilder } from './raw.js' diff --git a/src/database/query_builder/database.ts b/src/database/query_builder/database.ts index 7276871c..1dc477d5 100644 --- a/src/database/query_builder/database.ts +++ b/src/database/query_builder/database.ts @@ -13,11 +13,8 @@ import { DialectContract, QueryClientContract, TransactionClientContract, -} from '../../../adonis-typings/database.js' -import { - DBQueryCallback, - DatabaseQueryBuilderContract, -} from '../../../adonis-typings/querybuilder.js' +} from '../../types/database.js' +import { DBQueryCallback, DatabaseQueryBuilderContract } from '../../types/querybuilder.js' import { Chainable } from './chainable.js' import { QueryRunner } from '../../query_runner/index.js' diff --git a/src/database/query_builder/insert.ts b/src/database/query_builder/insert.ts index f9b28750..2aa7bd5a 100644 --- a/src/database/query_builder/insert.ts +++ b/src/database/query_builder/insert.ts @@ -10,8 +10,8 @@ import { Knex } from 'knex' import Macroable from '@poppinss/macroable' -import { InsertQueryBuilderContract } from '../../../adonis-typings/querybuilder.js' -import { QueryClientContract, TransactionClientContract } from '../../../adonis-typings/database.js' +import { InsertQueryBuilderContract } from '../../types/querybuilder.js' +import { QueryClientContract, TransactionClientContract } from '../../types/database.js' import { RawQueryBuilder } from './raw.js' import { RawBuilder } from '../static_builder/raw.js' diff --git a/src/database/query_builder/raw.ts b/src/database/query_builder/raw.ts index 026d4aab..813b07e6 100644 --- a/src/database/query_builder/raw.ts +++ b/src/database/query_builder/raw.ts @@ -10,8 +10,8 @@ import { Knex } from 'knex' import { QueryRunner } from '../../query_runner/index.js' -import { RawQueryBuilderContract } from '../../../adonis-typings/querybuilder.js' -import { QueryClientContract, TransactionClientContract } from '../../../adonis-typings/database.js' +import { RawQueryBuilderContract } from '../../types/querybuilder.js' +import { QueryClientContract, TransactionClientContract } from '../../types/database.js' /** * Exposes the API to execute raw queries diff --git a/src/database/static_builder/raw.ts b/src/database/static_builder/raw.ts index fcde0fbb..88107034 100644 --- a/src/database/static_builder/raw.ts +++ b/src/database/static_builder/raw.ts @@ -8,7 +8,7 @@ */ import { Knex } from 'knex' -import { RawBuilderContract } from '../../../adonis-typings/querybuilder.js' +import { RawBuilderContract } from '../../types/querybuilder.js' /** * Exposes the API to construct raw queries. If you want to execute diff --git a/src/database/static_builder/reference.ts b/src/database/static_builder/reference.ts index 52e875ca..31458df0 100644 --- a/src/database/static_builder/reference.ts +++ b/src/database/static_builder/reference.ts @@ -8,7 +8,7 @@ */ import { Knex } from 'knex' -import { ReferenceBuilderContract } from '../../../adonis-typings/querybuilder.js' +import { ReferenceBuilderContract } from '../../types/querybuilder.js' /** * Reference builder to create SQL reference values diff --git a/src/dialects/base_sqlite.ts b/src/dialects/base_sqlite.ts index 5a6d806d..cdbd567c 100644 --- a/src/dialects/base_sqlite.ts +++ b/src/dialects/base_sqlite.ts @@ -7,11 +7,7 @@ * file that was distributed with this source code. */ -import type { - DialectContract, - QueryClientContract, - SharedConfigNode, -} from '../../adonis-typings/database.js' +import type { DialectContract, QueryClientContract, SharedConfigNode } from '../types/database.js' export abstract class BaseSqliteDialect implements DialectContract { abstract readonly name: 'sqlite3' | 'better-sqlite3' diff --git a/src/dialects/better_sqlite.ts b/src/dialects/better_sqlite.ts index 6525886b..05543aa9 100644 --- a/src/dialects/better_sqlite.ts +++ b/src/dialects/better_sqlite.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { DialectContract } from '../../adonis-typings/database.js' +import { DialectContract } from '../types/database.js' import { BaseSqliteDialect } from './base_sqlite.js' export class BetterSqliteDialect extends BaseSqliteDialect implements DialectContract { diff --git a/src/dialects/index.ts b/src/dialects/index.ts index e30fc5cb..87e24426 100644 --- a/src/dialects/index.ts +++ b/src/dialects/index.ts @@ -14,11 +14,7 @@ import { SqliteDialect } from './sqlite.js' import { OracleDialect } from './oracle.js' import { RedshiftDialect } from './red_shift.js' import { BetterSqliteDialect } from './better_sqlite.js' -import { - DialectContract, - QueryClientContract, - SharedConfigNode, -} from '../../adonis-typings/database.js' +import { DialectContract, QueryClientContract, SharedConfigNode } from '../types/database.js' export const dialects: { [key: string]: { diff --git a/src/dialects/mssql.ts b/src/dialects/mssql.ts index 3cbd90d2..f5588883 100644 --- a/src/dialects/mssql.ts +++ b/src/dialects/mssql.ts @@ -8,11 +8,7 @@ */ import { RawBuilder } from '../database/static_builder/raw.js' -import { - DialectContract, - SharedConfigNode, - QueryClientContract, -} from '../../adonis-typings/database.js' +import { DialectContract, SharedConfigNode, QueryClientContract } from '../types/database.js' export class MssqlDialect implements DialectContract { readonly name = 'mssql' diff --git a/src/dialects/mysql.ts b/src/dialects/mysql.ts index 0e4daf63..72738609 100644 --- a/src/dialects/mysql.ts +++ b/src/dialects/mysql.ts @@ -8,11 +8,7 @@ */ import { RawBuilder } from '../database/static_builder/raw.js' -import { - DialectContract, - SharedConfigNode, - QueryClientContract, -} from '../../adonis-typings/database.js' +import { DialectContract, SharedConfigNode, QueryClientContract } from '../types/database.js' export class MysqlDialect implements DialectContract { readonly name = 'mysql' diff --git a/src/dialects/oracle.ts b/src/dialects/oracle.ts index ee3d1213..196e42c4 100644 --- a/src/dialects/oracle.ts +++ b/src/dialects/oracle.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { DialectContract, QueryClientContract } from '../../adonis-typings/database.js' +import { DialectContract, QueryClientContract } from '../types/database.js' export class OracleDialect implements DialectContract { readonly name = 'oracledb' diff --git a/src/dialects/pg.ts b/src/dialects/pg.ts index 4505484c..dde80f6e 100644 --- a/src/dialects/pg.ts +++ b/src/dialects/pg.ts @@ -7,11 +7,7 @@ * file that was distributed with this source code. */ -import { - DialectContract, - SharedConfigNode, - QueryClientContract, -} from '../../adonis-typings/database.js' +import { DialectContract, SharedConfigNode, QueryClientContract } from '../types/database.js' export class PgDialect implements DialectContract { readonly name = 'postgres' diff --git a/src/dialects/red_shift.ts b/src/dialects/red_shift.ts index 59c0d425..bd8ed2f2 100644 --- a/src/dialects/red_shift.ts +++ b/src/dialects/red_shift.ts @@ -7,11 +7,7 @@ * file that was distributed with this source code. */ -import { - DialectContract, - SharedConfigNode, - QueryClientContract, -} from '../../adonis-typings/database.js' +import { DialectContract, SharedConfigNode, QueryClientContract } from '../types/database.js' export class RedshiftDialect implements DialectContract { readonly name = 'redshift' diff --git a/src/dialects/sqlite.ts b/src/dialects/sqlite.ts index 367ea372..acef5031 100644 --- a/src/dialects/sqlite.ts +++ b/src/dialects/sqlite.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { DialectContract } from '../../adonis-typings/database.js' +import { DialectContract } from '../types/database.js' import { BaseSqliteDialect } from './base_sqlite.js' export class SqliteDialect extends BaseSqliteDialect implements DialectContract { diff --git a/src/factory/factory_builder.ts b/src/factories/factory_builder.ts similarity index 98% rename from src/factory/factory_builder.ts rename to src/factories/factory_builder.ts index ec7d12d6..9a77a10c 100644 --- a/src/factory/factory_builder.ts +++ b/src/factories/factory_builder.ts @@ -7,19 +7,14 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../adonis-typings/database.js' -import { - LucidRow, - LucidModel, - ModelAdapterOptions, - ModelObject, -} from '../../adonis-typings/model.js' +import { QueryClientContract } from '../types/database.js' +import { LucidRow, LucidModel, ModelAdapterOptions, ModelObject } from '../types/model.js' import { FactoryModelContract, FactoryContextContract, FactoryBuilderContract, FactoryRelationContract, -} from '../../adonis-typings/factory.js' +} from '../types/factory.js' import { FactoryModel } from './factory_model.js' import { FactoryContext } from './factory_context.js' diff --git a/src/factory/factory_context.ts b/src/factories/factory_context.ts similarity index 74% rename from src/factory/factory_context.ts rename to src/factories/factory_context.ts index 42fc6412..e1cbd36f 100644 --- a/src/factory/factory_context.ts +++ b/src/factories/factory_context.ts @@ -8,8 +8,8 @@ */ import { faker } from '@faker-js/faker' -import { FactoryContextContract } from '../../adonis-typings/factory.js' -import { TransactionClientContract } from '../../adonis-typings/database.js' +import { FactoryContextContract } from '../types/factory.js' +import { TransactionClientContract } from '../types/database.js' export class FactoryContext implements FactoryContextContract { faker = faker diff --git a/src/factory/factory_model.ts b/src/factories/factory_model.ts similarity index 97% rename from src/factory/factory_model.ts rename to src/factories/factory_model.ts index 83d39bae..9d35ca7d 100644 --- a/src/factory/factory_model.ts +++ b/src/factories/factory_model.ts @@ -8,8 +8,8 @@ */ import Hooks from '@poppinss/hooks' -import { LucidModel, ModelAdapterOptions } from '../../adonis-typings/model.js' -import { ExtractModelRelations, RelationshipsContract } from '../../adonis-typings/relations.js' +import { LucidModel, ModelAdapterOptions } from '../types/model.js' +import { ExtractModelRelations, RelationshipsContract } from '../types/relations.js' import { EventsList, @@ -22,9 +22,9 @@ import { FactoryRelationContract, FactoryBuilderQueryContract, FactoryBuilderContract, -} from '../../adonis-typings/factory.js' +} from '../types/factory.js' -import { FactoryManager } from './index.js' +import { FactoryManager } from './main.js' import { HasOne } from './relations/has_one.js' import { HasMany } from './relations/has_many.js' import { FactoryBuilder } from './factory_builder.js' diff --git a/src/factory/index.ts b/src/factories/main.ts similarity index 81% rename from src/factory/index.ts rename to src/factories/main.ts index fad645a8..73eb44ee 100644 --- a/src/factory/index.ts +++ b/src/factories/main.ts @@ -7,12 +7,8 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow } from '../../adonis-typings/model.js' -import { - DefineCallback, - FactoryModelContract, - StubIdCallback, -} from '../../adonis-typings/factory.js' +import { LucidModel, LucidRow } from '../types/model.js' +import { DefineCallback, FactoryModelContract, StubIdCallback } from '../types/factory.js' import { FactoryModel } from './factory_model.js' /** @@ -46,3 +42,6 @@ export class FactoryManager { this.stubIdCallback = callback } } + +const factory = new FactoryManager() +export default factory diff --git a/src/factory/relations/base.ts b/src/factories/relations/base.ts similarity index 92% rename from src/factory/relations/base.ts rename to src/factories/relations/base.ts index da4760c6..9f3c4429 100644 --- a/src/factory/relations/base.ts +++ b/src/factories/relations/base.ts @@ -7,14 +7,14 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow } from '../../../adonis-typings/model.js' +import { LucidModel, LucidRow } from '../../types/model.js' import { RelationCallback, FactoryModelContract, FactoryContextContract, FactoryBuilderQueryContract, FactoryRelationContract, -} from '../../../adonis-typings/factory.js' +} from '../../types/factory.js' /** * Base relation to be extended by other factory relations diff --git a/src/factory/relations/belongs_to.ts b/src/factories/relations/belongs_to.ts similarity index 87% rename from src/factory/relations/belongs_to.ts rename to src/factories/relations/belongs_to.ts index ffdfcd49..25da1672 100644 --- a/src/factory/relations/belongs_to.ts +++ b/src/factories/relations/belongs_to.ts @@ -7,14 +7,14 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow } from '../../../adonis-typings/model.js' -import { BelongsToRelationContract } from '../../../adonis-typings/relations.js' +import { LucidModel, LucidRow } from '../../types/model.js' +import { BelongsToRelationContract } from '../../types/relations.js' import { RelationCallback, FactoryModelContract, FactoryRelationContract, FactoryBuilderQueryContract, -} from '../../../adonis-typings/factory.js' +} from '../../types/factory.js' import { BaseRelation } from './base.js' diff --git a/src/factory/relations/has_many.ts b/src/factories/relations/has_many.ts similarity index 90% rename from src/factory/relations/has_many.ts rename to src/factories/relations/has_many.ts index e411e2e4..a47f5067 100644 --- a/src/factory/relations/has_many.ts +++ b/src/factories/relations/has_many.ts @@ -7,14 +7,14 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow } from '../../../adonis-typings/model.js' -import { HasManyRelationContract } from '../../../adonis-typings/relations.js' +import { LucidModel, LucidRow } from '../../types/model.js' +import { HasManyRelationContract } from '../../types/relations.js' import { RelationCallback, FactoryModelContract, FactoryRelationContract, FactoryBuilderQueryContract, -} from '../../../adonis-typings/factory.js' +} from '../../types/factory.js' import { BaseRelation } from './base.js' diff --git a/src/factory/relations/has_one.ts b/src/factories/relations/has_one.ts similarity index 89% rename from src/factory/relations/has_one.ts rename to src/factories/relations/has_one.ts index 7b057d5a..26ece5d4 100644 --- a/src/factory/relations/has_one.ts +++ b/src/factories/relations/has_one.ts @@ -7,14 +7,14 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow } from '../../../adonis-typings/model.js' -import { HasOneRelationContract } from '../../../adonis-typings/relations.js' +import { LucidModel, LucidRow } from '../../types/model.js' +import { HasOneRelationContract } from '../../types/relations.js' import { RelationCallback, FactoryModelContract, FactoryRelationContract, FactoryBuilderQueryContract, -} from '../../../adonis-typings/factory.js' +} from '../../types/factory.js' import { BaseRelation } from './base.js' diff --git a/src/factory/relations/many_to_many.ts b/src/factories/relations/many_to_many.ts similarity index 91% rename from src/factory/relations/many_to_many.ts rename to src/factories/relations/many_to_many.ts index a72e0354..75279b37 100644 --- a/src/factory/relations/many_to_many.ts +++ b/src/factories/relations/many_to_many.ts @@ -7,15 +7,15 @@ * file that was distributed with this source code. */ -import { LucidModel, LucidRow, ModelObject } from '../../../adonis-typings/model.js' -import { ManyToManyRelationContract } from '../../../adonis-typings/relations.js' +import { LucidModel, LucidRow, ModelObject } from '../../types/model.js' +import { ManyToManyRelationContract } from '../../types/relations.js' import { RelationCallback, FactoryModelContract, FactoryRelationContract, FactoryBuilderQueryContract, -} from '../../../adonis-typings/factory.js' +} from '../../types/factory.js' import { BaseRelation } from './base.js' diff --git a/src/helpers/pretty_print.ts b/src/helpers/pretty_print.ts index 7afb9540..d7c00068 100644 --- a/src/helpers/pretty_print.ts +++ b/src/helpers/pretty_print.ts @@ -12,7 +12,7 @@ import igniculus from 'igniculus' import kleur from 'kleur' import { inspect } from 'node:util' import hrTime from 'pretty-hrtime' -import { DbQueryEventNode } from '../../adonis-typings/database.js' +import { DbQueryEventNode } from '../types/database.js' const illuminate = igniculus({ comments: { fg: 'gray' }, diff --git a/src/migrator/index.ts b/src/migration/runner.ts similarity index 98% rename from src/migrator/index.ts rename to src/migration/runner.ts index 4ed4a092..8775ce53 100644 --- a/src/migrator/index.ts +++ b/src/migration/runner.ts @@ -10,12 +10,7 @@ import slash from 'slash' import { EventEmitter } from 'node:events' import { Exception } from '@poppinss/utils' - -import { - MigratorOptions, - MigratedFileNode, - MigrationListNode, -} from '../../adonis-typings/migrator.js' +import { MigratorOptions, MigratedFileNode, MigrationListNode } from '../types/migrator.js' import { FileNode, @@ -23,18 +18,18 @@ import { QueryClientContract, SharedConfigNode, TransactionClientContract, -} from '../../adonis-typings/database.js' +} from '../types/database.js' -import { MigrationSource } from './migration_source.js' -import { Database } from '../database/index.js' +import { MigrationSource } from './source.js' +import { Database } from '../database/main.js' import { Application } from '@adonisjs/core/app' -import { Schema } from '../schema/index.js' +import { Schema } from '../schema/main.js' /** * Migrator exposes the API to execute migrations using the schema files * for a given connection at a time. */ -export class Migrator extends EventEmitter { +export class MigrationRunner extends EventEmitter { private client: QueryClientContract private config: SharedConfigNode diff --git a/src/migrator/migration_source.ts b/src/migration/source.ts similarity index 95% rename from src/migrator/migration_source.ts rename to src/migration/source.ts index bf81b6f1..7e03a136 100644 --- a/src/migrator/migration_source.ts +++ b/src/migration/source.ts @@ -9,7 +9,7 @@ import type { Application } from '@adonisjs/core/app' import { sourceFiles } from '../utils/index.js' -import { SharedConfigNode, FileNode } from '../../adonis-typings/database.js' +import { SharedConfigNode, FileNode } from '../types/database.js' /** * Migration source exposes the API to read the migration files diff --git a/src/orm/adapter/index.ts b/src/orm/adapter/index.ts index 0a543659..edb4cb46 100644 --- a/src/orm/adapter/index.ts +++ b/src/orm/adapter/index.ts @@ -8,14 +8,9 @@ */ import { Exception } from '@poppinss/utils' -import { - LucidRow, - LucidModel, - AdapterContract, - ModelAdapterOptions, -} from '../../../adonis-typings/model.js' +import { LucidRow, LucidModel, AdapterContract, ModelAdapterOptions } from '../../types/model.js' import { isObject } from '../../utils/index.js' -import type { Database } from '../../database/index.js' +import type { Database } from '../../database/main.js' /** * Adapter exposes the API to make database queries and constructor diff --git a/src/orm/base_model/index.ts b/src/orm/base_model/index.ts index 29cafd01..c62a2733 100644 --- a/src/orm/base_model/index.ts +++ b/src/orm/base_model/index.ts @@ -13,7 +13,7 @@ import Hooks from '@poppinss/hooks' import lodash from '@poppinss/utils/lodash' import type { Container } from '@adonisjs/core/container' import { Exception, defineStaticProperty } from '@poppinss/utils' -import { QueryClientContract, TransactionClientContract } from '../../../adonis-typings/database.js' +import { QueryClientContract, TransactionClientContract } from '../../types/database.js' import { LucidRow, @@ -37,7 +37,7 @@ import { ModelPaginatorContract, QueryScopeCallback, QueryScope, -} from '../../../adonis-typings/model.js' +} from '../../types/model.js' import { ModelRelations, @@ -45,7 +45,7 @@ import { RelationshipsContract, ThroughRelationOptions, ManyToManyRelationOptions, -} from '../../../adonis-typings/relations.js' +} from '../../types/relations.js' import { ModelKeys } from '../model_keys/index.js' import { Preloader } from '../preloader/index.js' diff --git a/src/orm/base_model/proxy_handler.ts b/src/orm/base_model/proxy_handler.ts index eb71f671..cfdcf3f9 100644 --- a/src/orm/base_model/proxy_handler.ts +++ b/src/orm/base_model/proxy_handler.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { LucidModel } from '../../../adonis-typings/model.js' +import { LucidModel } from '../../types/model.js' /** * A proxy trap to add support for custom getters and setters diff --git a/src/orm/decorators/date.ts b/src/orm/decorators/date.ts index 08fc6a32..b498730f 100644 --- a/src/orm/decorators/date.ts +++ b/src/orm/decorators/date.ts @@ -9,7 +9,7 @@ import { DateTime } from 'luxon' import { Exception } from '@poppinss/utils' -import { LucidRow, LucidModel, DateColumnDecorator } from '../../../adonis-typings/model.js' +import { LucidRow, LucidModel, DateColumnDecorator } from '../../types/model.js' /** * The method to prepare the date column before persisting it's diff --git a/src/orm/decorators/date_time.ts b/src/orm/decorators/date_time.ts index 2feabce4..8181cdc8 100644 --- a/src/orm/decorators/date_time.ts +++ b/src/orm/decorators/date_time.ts @@ -9,7 +9,7 @@ import { DateTime } from 'luxon' import { Exception } from '@poppinss/utils' -import { LucidRow, LucidModel, DateTimeColumnDecorator } from '../../../adonis-typings/model.js' +import { LucidRow, LucidModel, DateTimeColumnDecorator } from '../../types/model.js' /** * The method to prepare the datetime column before persisting it's diff --git a/src/orm/decorators/index.ts b/src/orm/decorators/index.ts index fb55847d..ac11b2ad 100644 --- a/src/orm/decorators/index.ts +++ b/src/orm/decorators/index.ts @@ -14,7 +14,7 @@ import { ComputedDecorator, DateColumnDecorator, DateTimeColumnDecorator, -} from '../../../adonis-typings/model.js' +} from '../../types/model.js' import { HasOneDecorator, @@ -22,7 +22,7 @@ import { BelongsToDecorator, ManyToManyDecorator, HasManyThroughDecorator, -} from '../../../adonis-typings/relations.js' +} from '../../types/relations.js' import { dateColumn } from './date.js' import { dateTimeColumn } from './date_time.js' diff --git a/src/orm/main.ts b/src/orm/main.ts new file mode 100644 index 00000000..37519609 --- /dev/null +++ b/src/orm/main.ts @@ -0,0 +1,15 @@ +/* + * @adonisjs/lucid + * + * (c) AdoniJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +export * from './decorators/index.js' +export * from './decorators/date.js' +export * from './decorators/date_time.js' +export { BaseModel, scope } from './base_model/index.js' +export { ModelQueryBuilder } from './query_builder/index.js' +export { SnakeCaseNamingStrategy } from './naming_strategies/snake_case.js' diff --git a/src/orm/model_keys/index.ts b/src/orm/model_keys/index.ts index 94dcb20b..ad17c382 100644 --- a/src/orm/model_keys/index.ts +++ b/src/orm/model_keys/index.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { ModelKeysContract, ModelObject } from '../../../adonis-typings/model.js' +import { ModelKeysContract, ModelObject } from '../../types/model.js' /** * Exposes the API to collect, get and resolve model keys diff --git a/src/orm/naming_strategies/snake_case.ts b/src/orm/naming_strategies/snake_case.ts index f5536636..b8e59345 100644 --- a/src/orm/naming_strategies/snake_case.ts +++ b/src/orm/naming_strategies/snake_case.ts @@ -8,8 +8,8 @@ */ import string from '@poppinss/utils/string' -import { ModelRelations } from '../../../adonis-typings/relations.js' -import { NamingStrategyContract, LucidModel } from '../../../adonis-typings/model.js' +import { ModelRelations } from '../../types/relations.js' +import { NamingStrategyContract, LucidModel } from '../../types/model.js' /** * Uses snake case as the naming strategy for different model properties diff --git a/src/orm/paginator/index.ts b/src/orm/paginator/index.ts index e3f2e68f..6b35a3df 100644 --- a/src/orm/paginator/index.ts +++ b/src/orm/paginator/index.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { ModelPaginatorContract, CherryPick } from '../../../adonis-typings/model.js' +import { ModelPaginatorContract, CherryPick } from '../../types/model.js' import { SimplePaginator } from '../../database/paginator/simple_paginator.js' /** diff --git a/src/orm/preloader/index.ts b/src/orm/preloader/index.ts index e386635e..2b8b9391 100644 --- a/src/orm/preloader/index.ts +++ b/src/orm/preloader/index.ts @@ -9,15 +9,15 @@ import { Exception } from '@poppinss/utils' -import { LucidRow, LucidModel, ModelObject } from '../../../adonis-typings/model.js' +import { LucidRow, LucidModel, ModelObject } from '../../types/model.js' import { PreloaderContract, RelationshipsContract, RelationQueryBuilderContract, -} from '../../../adonis-typings/relations.js' +} from '../../types/relations.js' -import { QueryClientContract } from '../../../adonis-typings/database.js' +import { QueryClientContract } from '../../types/database.js' /** * Exposes the API to define and preload relationships in reference to diff --git a/src/orm/query_builder/index.ts b/src/orm/query_builder/index.ts index 04d120ad..a8dd50b0 100644 --- a/src/orm/query_builder/index.ts +++ b/src/orm/query_builder/index.ts @@ -16,21 +16,21 @@ import { ModelObject, ModelAdapterOptions, ModelQueryBuilderContract, -} from '../../../adonis-typings/model.js' +} from '../../types/model.js' import { PreloaderContract, RelationshipsContract, RelationQueryBuilderContract, -} from '../../../adonis-typings/relations.js' +} from '../../types/relations.js' import { DialectContract, QueryClientContract, TransactionClientContract, -} from '../../../adonis-typings/database.js' +} from '../../types/database.js' -import { DBQueryCallback, Dictionary, OneOrMany } from '../../../adonis-typings/querybuilder.js' +import { DBQueryCallback, Dictionary, OneOrMany } from '../../types/querybuilder.js' import { isObject } from '../../utils/index.js' import { Preloader } from '../preloader/index.js' diff --git a/src/orm/relations/aggregates_loader/lazy_load.ts b/src/orm/relations/aggregates_loader/lazy_load.ts index 46b2b49e..b8492fba 100644 --- a/src/orm/relations/aggregates_loader/lazy_load.ts +++ b/src/orm/relations/aggregates_loader/lazy_load.ts @@ -12,7 +12,7 @@ import { LucidModel, ModelQueryBuilderContract, LazyLoadAggregatesContract, -} from '../../../../adonis-typings/model.js' +} from '../../../types/model.js' /** * An implementation for lazy loading model relationship aggregates diff --git a/src/orm/relations/base/query_builder.ts b/src/orm/relations/base/query_builder.ts index dc6fa834..f4b0e5e6 100644 --- a/src/orm/relations/base/query_builder.ts +++ b/src/orm/relations/base/query_builder.ts @@ -8,17 +8,10 @@ */ import { Knex } from 'knex' -import { DBQueryCallback } from '../../../../adonis-typings/querybuilder.js' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { - LucidRow, - LucidModel, - ModelQueryBuilderContract, -} from '../../../../adonis-typings/model.js' -import { - RelationshipsContract, - RelationQueryBuilderContract, -} from '../../../../adonis-typings/relations.js' +import { DBQueryCallback } from '../../../types/querybuilder.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidRow, LucidModel, ModelQueryBuilderContract } from '../../../types/model.js' +import { RelationshipsContract, RelationQueryBuilderContract } from '../../../types/relations.js' import { ModelQueryBuilder } from '../../query_builder/index.js' /** diff --git a/src/orm/relations/base/sub_query_builder.ts b/src/orm/relations/base/sub_query_builder.ts index 1ba1a4b7..f5b37b6d 100644 --- a/src/orm/relations/base/sub_query_builder.ts +++ b/src/orm/relations/base/sub_query_builder.ts @@ -8,13 +8,10 @@ */ import { Knex } from 'knex' -import { DBQueryCallback } from '../../../../adonis-typings/querybuilder.js' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidModel } from '../../../../adonis-typings/model.js' -import { - RelationSubQueryBuilderContract, - RelationshipsContract, -} from '../../../../adonis-typings/relations.js' +import { DBQueryCallback } from '../../../types/querybuilder.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidModel } from '../../../types/model.js' +import { RelationSubQueryBuilderContract, RelationshipsContract } from '../../../types/relations.js' import { ModelQueryBuilder } from '../../query_builder/index.js' /** diff --git a/src/orm/relations/belongs_to/index.ts b/src/orm/relations/belongs_to/index.ts index aa259142..3bf70bf3 100644 --- a/src/orm/relations/belongs_to/index.ts +++ b/src/orm/relations/belongs_to/index.ts @@ -7,15 +7,15 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' +import { QueryClientContract } from '../../../types/database.js' +import { OneOrMany } from '../../../types/querybuilder.js' -import { LucidRow, LucidModel, ModelObject } from '../../../../adonis-typings/model.js' +import { LucidRow, LucidModel, ModelObject } from '../../../types/model.js' import { RelationOptions, BelongsToRelationContract, BelongsTo as ModelBelongsTo, -} from '../../../../adonis-typings/relations.js' +} from '../../../types/relations.js' import { KeysExtractor } from '../keys_extractor.js' import { BelongsToQueryClient } from './query_client.js' @@ -45,14 +45,14 @@ export class BelongsTo implements BelongsToRelationContract * @note: Available after boot is invoked */ declare localKey: string - declare localKeyColumName: string + declare localKeyColumnName: string /** * Foreign key is reference to the foreign key in the related table * @note: Available after boot is invoked */ declare foreignKey: string - declare foreignKeyColumName: string + declare foreignKeyColumnName: string /** * Reference to the onQuery hook defined by the user @@ -135,13 +135,13 @@ export class HasMany implements HasManyRelationContract * Keys on the parent model */ this.localKey = localKey.attributeName - this.localKeyColumName = localKey.columnName + this.localKeyColumnName = localKey.columnName /** * Keys on the related model */ this.foreignKey = foreignKey.attributeName - this.foreignKeyColumName = foreignKey.columnName + this.foreignKeyColumnName = foreignKey.columnName /** * Booted successfully diff --git a/src/orm/relations/has_many/query_builder.ts b/src/orm/relations/has_many/query_builder.ts index 9045c823..05afa8e1 100644 --- a/src/orm/relations/has_many/query_builder.ts +++ b/src/orm/relations/has_many/query_builder.ts @@ -8,9 +8,9 @@ */ import { Knex } from 'knex' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidRow, LucidModel } from '../../../../adonis-typings/model.js' -import { HasManyQueryBuilderContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidRow, LucidModel } from '../../../types/model.js' +import { HasManyQueryBuilderContract } from '../../../types/relations.js' import { HasMany } from './index.js' import { getValue, unique } from '../../../utils/index.js' @@ -139,7 +139,7 @@ export class HasManyQueryBuilder } const rowName = 'adonis_group_limit_counter' - const partitionBy = `PARTITION BY ${this.relation.foreignKeyColumName}` + const partitionBy = `PARTITION BY ${this.relation.foreignKeyColumnName}` const orderBy = `ORDER BY ${column} ${direction}` /** diff --git a/src/orm/relations/has_many/query_client.ts b/src/orm/relations/has_many/query_client.ts index a52ce9c7..3e790c27 100644 --- a/src/orm/relations/has_many/query_client.ts +++ b/src/orm/relations/has_many/query_client.ts @@ -7,15 +7,10 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' -import { - LucidRow, - LucidModel, - ModelObject, - ModelAssignOptions, -} from '../../../../adonis-typings/model.js' -import { HasManyClientContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { OneOrMany } from '../../../types/querybuilder.js' +import { LucidRow, LucidModel, ModelObject, ModelAssignOptions } from '../../../types/model.js' +import { HasManyClientContract } from '../../../types/relations.js' import { HasMany } from './index.js' import { managedTransaction } from '../../../utils/index.js' diff --git a/src/orm/relations/has_many/sub_query_builder.ts b/src/orm/relations/has_many/sub_query_builder.ts index 0e4c6fbc..a65bedaa 100644 --- a/src/orm/relations/has_many/sub_query_builder.ts +++ b/src/orm/relations/has_many/sub_query_builder.ts @@ -8,9 +8,9 @@ */ import { Knex } from 'knex' -import { LucidModel } from '../../../../adonis-typings/model.js' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { RelationSubQueryBuilderContract } from '../../../../adonis-typings/relations.js' +import { LucidModel } from '../../../types/model.js' +import { QueryClientContract } from '../../../types/database.js' +import { RelationSubQueryBuilderContract } from '../../../types/relations.js' import { HasMany } from './index.js' import { BaseSubQueryBuilder } from '../base/sub_query_builder.js' @@ -86,8 +86,8 @@ export class HasManySubQueryBuilder } this.wrapExisting().where( - `${localTable}.${this.relation.localKeyColumName}`, - this.client.ref(`${tablePrefix}.${this.relation.foreignKeyColumName}`) + `${localTable}.${this.relation.localKeyColumnName}`, + this.client.ref(`${tablePrefix}.${this.relation.foreignKeyColumnName}`) ) } } diff --git a/src/orm/relations/has_many_through/index.ts b/src/orm/relations/has_many_through/index.ts index b04c9026..d71510c7 100644 --- a/src/orm/relations/has_many_through/index.ts +++ b/src/orm/relations/has_many_through/index.ts @@ -7,14 +7,14 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' -import { LucidRow, LucidModel } from '../../../../adonis-typings/model.js' +import { QueryClientContract } from '../../../types/database.js' +import { OneOrMany } from '../../../types/querybuilder.js' +import { LucidRow, LucidModel } from '../../../types/model.js' import { ThroughRelationOptions, HasManyThroughRelationContract, HasManyThrough as ModelHasManyThrough, -} from '../../../../adonis-typings/relations.js' +} from '../../../types/relations.js' import { KeysExtractor } from '../keys_extractor.js' import { HasManyThroughClient } from './query_client.js' diff --git a/src/orm/relations/has_many_through/query_builder.ts b/src/orm/relations/has_many_through/query_builder.ts index 8f27d7c5..9b16a422 100644 --- a/src/orm/relations/has_many_through/query_builder.ts +++ b/src/orm/relations/has_many_through/query_builder.ts @@ -8,9 +8,9 @@ */ import { Knex } from 'knex' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidRow, LucidModel } from '../../../../adonis-typings/model.js' -import { HasManyThroughQueryBuilderContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidRow, LucidModel } from '../../../types/model.js' +import { HasManyThroughQueryBuilderContract } from '../../../types/relations.js' import { HasManyThrough } from './index.js' import { getValue, unique } from '../../../utils/index.js' diff --git a/src/orm/relations/has_many_through/query_client.ts b/src/orm/relations/has_many_through/query_client.ts index e03525db..b5b8e14d 100644 --- a/src/orm/relations/has_many_through/query_client.ts +++ b/src/orm/relations/has_many_through/query_client.ts @@ -7,10 +7,10 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' -import { LucidModel, LucidRow } from '../../../../adonis-typings/model.js' -import { HasManyThroughClientContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { OneOrMany } from '../../../types/querybuilder.js' +import { LucidModel, LucidRow } from '../../../types/model.js' +import { HasManyThroughClientContract } from '../../../types/relations.js' import { HasManyThrough } from './index.js' import { HasManyThroughQueryBuilder } from './query_builder.js' diff --git a/src/orm/relations/has_many_through/sub_query_builder.ts b/src/orm/relations/has_many_through/sub_query_builder.ts index 69ddffc2..892ffa0c 100644 --- a/src/orm/relations/has_many_through/sub_query_builder.ts +++ b/src/orm/relations/has_many_through/sub_query_builder.ts @@ -8,9 +8,9 @@ */ import { Knex } from 'knex' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidModel } from '../../../../adonis-typings/model.js' -import { RelationSubQueryBuilderContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidModel } from '../../../types/model.js' +import { RelationSubQueryBuilderContract } from '../../../types/relations.js' import { HasManyThrough } from './index.js' import { BaseSubQueryBuilder } from '../base/sub_query_builder.js' diff --git a/src/orm/relations/has_one/index.ts b/src/orm/relations/has_one/index.ts index cb0ac3bf..23a37a64 100644 --- a/src/orm/relations/has_one/index.ts +++ b/src/orm/relations/has_one/index.ts @@ -7,14 +7,14 @@ * file that was distributed with this source code. */ -import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidRow, LucidModel, ModelObject } from '../../../../adonis-typings/model.js' +import { OneOrMany } from '../../../types/querybuilder.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidRow, LucidModel, ModelObject } from '../../../types/model.js' import { RelationOptions, HasOne as ModelHasOne, HasOneRelationContract, -} from '../../../../adonis-typings/relations.js' +} from '../../../types/relations.js' import { KeysExtractor } from '../keys_extractor.js' import { HasOneQueryClient } from './query_client.js' @@ -34,14 +34,14 @@ export class HasOne implements HasOneRelationContract { * @note: Available after boot is invoked */ declare localKey: string - declare localKeyColumName: string + declare localKeyColumnName: string /** * Foreign key is reference to the foreign key in the related table * @note: Available after boot is invoked */ declare foreignKey: string - declare foreignKeyColumName: string + declare foreignKeyColumnName: string /** * Reference to the onQuery hook defined by the user @@ -111,13 +111,13 @@ export class HasOne implements HasOneRelationContract { * Keys on the parent model */ this.localKey = localKey.attributeName - this.localKeyColumName = localKey.columnName + this.localKeyColumnName = localKey.columnName /** * Keys on the related model */ this.foreignKey = foreignKey.attributeName - this.foreignKeyColumName = foreignKey.columnName + this.foreignKeyColumnName = foreignKey.columnName /** * Booted successfully diff --git a/src/orm/relations/has_one/query_builder.ts b/src/orm/relations/has_one/query_builder.ts index 0b811048..5a10bb57 100644 --- a/src/orm/relations/has_one/query_builder.ts +++ b/src/orm/relations/has_one/query_builder.ts @@ -8,8 +8,8 @@ */ import { Knex } from 'knex' -import { LucidRow } from '../../../../adonis-typings/model.js' -import { QueryClientContract } from '../../../../adonis-typings/database.js' +import { LucidRow } from '../../../types/model.js' +import { QueryClientContract } from '../../../types/database.js' import { HasOne } from './index.js' import { getValue, unique } from '../../../utils/index.js' diff --git a/src/orm/relations/has_one/query_client.ts b/src/orm/relations/has_one/query_client.ts index 6463c08c..8de26b0c 100644 --- a/src/orm/relations/has_one/query_client.ts +++ b/src/orm/relations/has_one/query_client.ts @@ -7,15 +7,10 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' -import { - ModelObject, - LucidModel, - LucidRow, - ModelAssignOptions, -} from '../../../../adonis-typings/model.js' -import { HasOneClientContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { OneOrMany } from '../../../types/querybuilder.js' +import { ModelObject, LucidModel, LucidRow, ModelAssignOptions } from '../../../types/model.js' +import { HasOneClientContract } from '../../../types/relations.js' import { HasOne } from './index.js' import { managedTransaction } from '../../../utils/index.js' diff --git a/src/orm/relations/has_one/sub_query_builder.ts b/src/orm/relations/has_one/sub_query_builder.ts index 2bad0d69..a1f544cc 100644 --- a/src/orm/relations/has_one/sub_query_builder.ts +++ b/src/orm/relations/has_one/sub_query_builder.ts @@ -8,9 +8,9 @@ */ import { Knex } from 'knex' -import { LucidModel } from '../../../../adonis-typings/model.js' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { RelationSubQueryBuilderContract } from '../../../../adonis-typings/relations.js' +import { LucidModel } from '../../../types/model.js' +import { QueryClientContract } from '../../../types/database.js' +import { RelationSubQueryBuilderContract } from '../../../types/relations.js' import { HasOne } from './index.js' import { BaseSubQueryBuilder } from '../base/sub_query_builder.js' @@ -85,8 +85,8 @@ export class HasOneSubQueryBuilder } this.wrapExisting().where( - `${localTable}.${this.relation.localKeyColumName}`, - this.client.ref(`${tablePrefix}.${this.relation.foreignKeyColumName}`) + `${localTable}.${this.relation.localKeyColumnName}`, + this.client.ref(`${tablePrefix}.${this.relation.foreignKeyColumnName}`) ) } } diff --git a/src/orm/relations/keys_extractor.ts b/src/orm/relations/keys_extractor.ts index 6b1e5983..dd7c8203 100644 --- a/src/orm/relations/keys_extractor.ts +++ b/src/orm/relations/keys_extractor.ts @@ -8,7 +8,7 @@ */ import { Exception } from '@poppinss/utils' -import { LucidModel } from '../../../adonis-typings/model.js' +import { LucidModel } from '../../types/model.js' /** * Utility to consistently extract relationship keys from the model diff --git a/src/orm/relations/many_to_many/index.ts b/src/orm/relations/many_to_many/index.ts index 56462c07..d1481f12 100644 --- a/src/orm/relations/many_to_many/index.ts +++ b/src/orm/relations/many_to_many/index.ts @@ -7,13 +7,13 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidRow, LucidModel } from '../../../../adonis-typings/model.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidRow, LucidModel } from '../../../types/model.js' import { ManyToManyRelationOptions, ManyToManyRelationContract, ManyToMany as ModelManyToMany, -} from '../../../../adonis-typings/relations.js' +} from '../../../types/relations.js' import { KeysExtractor } from '../keys_extractor.js' import { ManyToManyQueryClient } from './query_client.js' diff --git a/src/orm/relations/many_to_many/query_builder.ts b/src/orm/relations/many_to_many/query_builder.ts index eed15152..dc05d1dc 100644 --- a/src/orm/relations/many_to_many/query_builder.ts +++ b/src/orm/relations/many_to_many/query_builder.ts @@ -9,9 +9,9 @@ import { Knex } from 'knex' import { DateTime } from 'luxon' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidModel, LucidRow } from '../../../../adonis-typings/model.js' -import { ManyToManyQueryBuilderContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidModel, LucidRow } from '../../../types/model.js' +import { ManyToManyQueryBuilderContract } from '../../../types/relations.js' import { ManyToMany } from './index.js' import { PivotHelpers } from './pivot_helpers.js' diff --git a/src/orm/relations/many_to_many/query_client.ts b/src/orm/relations/many_to_many/query_client.ts index bd9c6794..de214b3a 100644 --- a/src/orm/relations/many_to_many/query_client.ts +++ b/src/orm/relations/many_to_many/query_client.ts @@ -8,18 +8,10 @@ */ import { DateTime } from 'luxon' -import { - LucidModel, - LucidRow, - ModelObject, - ModelAssignOptions, -} from '../../../../adonis-typings/model.js' -import { ManyToManyClientContract } from '../../../../adonis-typings/relations.js' -import { - QueryClientContract, - TransactionClientContract, -} from '../../../../adonis-typings/database.js' -import { OneOrMany } from '../../../../adonis-typings/querybuilder.js' +import { LucidModel, LucidRow, ModelObject, ModelAssignOptions } from '../../../types/model.js' +import { ManyToManyClientContract } from '../../../types/relations.js' +import { QueryClientContract, TransactionClientContract } from '../../../types/database.js' +import { OneOrMany } from '../../../types/querybuilder.js' import { ManyToMany } from './index.js' import { ManyToManyQueryBuilder } from './query_builder.js' diff --git a/src/orm/relations/many_to_many/sub_query_builder.ts b/src/orm/relations/many_to_many/sub_query_builder.ts index 49f71188..62b8811f 100644 --- a/src/orm/relations/many_to_many/sub_query_builder.ts +++ b/src/orm/relations/many_to_many/sub_query_builder.ts @@ -8,9 +8,9 @@ */ import { Knex } from 'knex' -import { QueryClientContract } from '../../../../adonis-typings/database.js' -import { LucidModel } from '../../../../adonis-typings/model.js' -import { ManyToManySubQueryBuilderContract } from '../../../../adonis-typings/relations.js' +import { QueryClientContract } from '../../../types/database.js' +import { LucidModel } from '../../../types/model.js' +import { ManyToManySubQueryBuilderContract } from '../../../types/relations.js' import { ManyToMany } from './index.js' import { PivotHelpers } from './pivot_helpers.js' diff --git a/src/query_client/index.ts b/src/query_client/index.ts index be5eca17..1473f7a9 100644 --- a/src/query_client/index.ts +++ b/src/query_client/index.ts @@ -17,7 +17,7 @@ import { ConnectionContract, QueryClientContract, TransactionClientContract, -} from '../../adonis-typings/database.js' +} from '../types/database.js' import { dialects } from '../dialects/index.js' import { TransactionClient } from '../transaction_client/index.js' @@ -26,11 +26,18 @@ import { RawQueryBuilder } from '../database/query_builder/raw.js' import { InsertQueryBuilder } from '../database/query_builder/insert.js' import { ReferenceBuilder } from '../database/static_builder/reference.js' import { DatabaseQueryBuilder } from '../database/query_builder/database.js' -import { LucidModel, ModelQueryBuilderContract } from '../../adonis-typings/model.js' +import { LucidModel, ModelQueryBuilderContract } from '../types/model.js' import { RawQueryBindings, DatabaseQueryBuilderContract, -} from '../../adonis-typings/querybuilder.js' + InsertQueryBuilderContract, + RawQueryBuilderContract, + RawBuilderContract, + ReferenceBuilderContract, + ChainableContract, + Dictionary, + QueryCallback, +} from '../types/querybuilder.js' import { ModelQueryBuilder } from '../orm/query_builder/index.js' /** @@ -178,12 +185,17 @@ export class QueryClient implements QueryClientContract { * Returns an instance of a transaction. Each transaction will * query and hold a single connection for all queries. */ - async transaction( + transaction( + callback: (trx: TransactionClientContract) => Promise, + options?: { isolationLevel?: IsolationLevels } + ): Promise + transaction(options?: { isolationLevel?: IsolationLevels }): Promise + async transaction( callback?: | { isolationLevel?: IsolationLevels } | ((trx: TransactionClientContract) => Promise), options?: { isolationLevel?: IsolationLevels } - ): Promise { + ): Promise { const trx = await this.getWriteClient().transaction(options) const transaction = new TransactionClient( trx, @@ -250,15 +262,21 @@ export class QueryClient implements QueryClientContract { /** * Returns instance of a query builder for inserting rows */ - insertQuery(): any { + insertQuery(): InsertQueryBuilderContract { return new InsertQueryBuilder(this.getWriteClient().queryBuilder(), this) } /** * Returns instance of raw query builder */ - rawQuery(sql: any, bindings?: any): any { - return new RawQueryBuilder(this.connection.client!.raw(sql, bindings), this) + rawQuery( + sql: string, + bindings?: RawQueryBindings | undefined + ): RawQueryBuilderContract { + return new RawQueryBuilder( + bindings ? this.connection.client!.raw(sql, bindings) : this.connection.client!.raw(sql), + this + ) } /** @@ -266,21 +284,27 @@ export class QueryClient implements QueryClientContract { * cannot be executed. Use `rawQuery`, if you want to execute * queries raw queries. */ - raw(sql: string, bindings?: any) { + raw(sql: string, bindings?: RawQueryBindings | undefined): RawBuilderContract { return new RawBuilder(sql, bindings) } /** * Returns reference builder. */ - ref(reference: string) { + ref(reference: string): ReferenceBuilderContract { return new ReferenceBuilder(reference, this.getReadClient().client) } /** * Returns instance of a query builder and selects the table */ - from(table: any): any { + from( + table: + | string + | Dictionary + | QueryCallback + | ChainableContract + ): DatabaseQueryBuilderContract { return this.query().from(table) } @@ -288,21 +312,21 @@ export class QueryClient implements QueryClientContract { * Returns instance of a query builder and selects the table * for an insert query */ - table(table: any): any { + table(table: string): InsertQueryBuilderContract { return this.insertQuery().table(table) } /** * Get advisory lock on the selected connection */ - getAdvisoryLock(key: string, timeout?: number): any { + getAdvisoryLock(key: string | number, timeout?: number | undefined): Promise { return this.dialect.getAdvisoryLock(key, timeout) } /** * Release advisory lock */ - releaseAdvisoryLock(key: string): any { + releaseAdvisoryLock(key: string | number): Promise { return this.dialect.releaseAdvisoryLock(key) } } diff --git a/src/query_reporter/index.ts b/src/query_reporter/index.ts index 691236bb..658fe184 100644 --- a/src/query_reporter/index.ts +++ b/src/query_reporter/index.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { QueryClientContract, TransactionClientContract } from '../../adonis-typings/database.js' +import { QueryClientContract, TransactionClientContract } from '../types/database.js' /** * Used for reporting queries using the profiler and the event diff --git a/src/query_runner/index.ts b/src/query_runner/index.ts index c771ebf1..8b96e550 100644 --- a/src/query_runner/index.ts +++ b/src/query_runner/index.ts @@ -10,7 +10,7 @@ import { Knex } from 'knex' import { Exception } from '@poppinss/utils' import { QueryReporter } from '../query_reporter/index.js' -import { QueryClientContract, TransactionClientContract } from '../../adonis-typings/database.js' +import { QueryClientContract, TransactionClientContract } from '../types/database.js' /** * Query runner exposes the API for executing knex query builder by using the diff --git a/src/schema/index.ts b/src/schema/main.ts similarity index 94% rename from src/schema/index.ts rename to src/schema/main.ts index caf94a7f..23632114 100644 --- a/src/schema/index.ts +++ b/src/schema/main.ts @@ -7,13 +7,13 @@ * file that was distributed with this source code. */ -import { Knex } from 'knex' +import type { Knex } from 'knex' import { Exception } from '@poppinss/utils' import { getDDLMethod } from '../utils/index.js' import { QueryReporter } from '../query_reporter/index.js' -import { DeferCallback } from '../../adonis-typings/schema.js' -import { QueryClientContract } from '../../adonis-typings/database.js' -import { RawQueryBindings } from '../../adonis-typings/querybuilder.js' +import type { DeferCallback } from '../types/schema.js' +import type { QueryClientContract } from '../types/database.js' +import type { RawQueryBindings } from '../types/querybuilder.js' /** * Exposes the API to define table schema using deferred database diff --git a/src/base_seeder/index.ts b/src/seeders/base_seeder.ts similarity index 82% rename from src/base_seeder/index.ts rename to src/seeders/base_seeder.ts index 52b1cab9..8bbf297c 100644 --- a/src/base_seeder/index.ts +++ b/src/seeders/base_seeder.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -import { QueryClientContract } from '../../adonis-typings/database.js' +import { QueryClientContract } from '../types/database.js' export class BaseSeeder { static environment: string[] diff --git a/src/seeders/main.ts b/src/seeders/main.ts new file mode 100644 index 00000000..3ee51065 --- /dev/null +++ b/src/seeders/main.ts @@ -0,0 +1,10 @@ +/* + * @adonisjs/lucid + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +export { BaseSeeder } from './base_seeder.js' diff --git a/src/seeders_runner/index.ts b/src/seeders/runner.ts similarity index 91% rename from src/seeders_runner/index.ts rename to src/seeders/runner.ts index 95a429a6..d7c100a1 100644 --- a/src/seeders_runner/index.ts +++ b/src/seeders/runner.ts @@ -8,11 +8,11 @@ */ import { Application } from '@adonisjs/core/app' -import { FileNode, QueryClientContract, SharedConfigNode } from '../../adonis-typings/database.js' -import { SeederConstructorContract, SeederFileNode } from '../../adonis-typings/seeder.js' +import { FileNode, QueryClientContract, SharedConfigNode } from '../types/database.js' +import { SeederConstructorContract, SeederFileNode } from '../types/seeder.js' -import { SeedersSource } from './seeders_source.js' -import { Database } from '../database/index.js' +import { SeedersSource } from './source.js' +import { Database } from '../database/main.js' /** * Seeds Runner exposes the API to traverse seeders and execute them diff --git a/src/seeders_runner/seeders_source.ts b/src/seeders/source.ts similarity index 95% rename from src/seeders_runner/seeders_source.ts rename to src/seeders/source.ts index be2c0c05..9d1d33d2 100644 --- a/src/seeders_runner/seeders_source.ts +++ b/src/seeders/source.ts @@ -9,7 +9,7 @@ import { Application } from '@adonisjs/core/app' -import { FileNode, SharedConfigNode } from '../../adonis-typings/database.js' +import { FileNode, SharedConfigNode } from '../types/database.js' import { sourceFiles } from '../utils/index.js' /** diff --git a/src/transaction_client/index.ts b/src/transaction_client/index.ts index 837804e2..81ae6965 100644 --- a/src/transaction_client/index.ts +++ b/src/transaction_client/index.ts @@ -11,11 +11,7 @@ import { Knex } from 'knex' import Hooks from '@poppinss/hooks' import { EventEmitter } from 'node:events' import type { Emitter } from '@adonisjs/core/events' -import { - IsolationLevels, - DialectContract, - TransactionClientContract, -} from '../../adonis-typings/database.js' +import { IsolationLevels, DialectContract, TransactionClientContract } from '../types/database.js' import { ModelQueryBuilder } from '../orm/query_builder/index.js' import { RawBuilder } from '../database/static_builder/raw.js' @@ -23,7 +19,7 @@ import { RawQueryBuilder } from '../database/query_builder/raw.js' import { InsertQueryBuilder } from '../database/query_builder/insert.js' import { ReferenceBuilder } from '../database/static_builder/reference.js' import { DatabaseQueryBuilder } from '../database/query_builder/database.js' -import { LucidModel, ModelQueryBuilderContract } from '../../adonis-typings/model.js' +import { LucidModel, ModelQueryBuilderContract } from '../types/model.js' /** * Transaction uses a dedicated connection from the connection pool diff --git a/adonis-typings/database.ts b/src/types/database.ts similarity index 100% rename from adonis-typings/database.ts rename to src/types/database.ts diff --git a/adonis-typings/events.ts b/src/types/events.ts similarity index 100% rename from adonis-typings/events.ts rename to src/types/events.ts diff --git a/adonis-typings/factory.ts b/src/types/factory.ts similarity index 100% rename from adonis-typings/factory.ts rename to src/types/factory.ts diff --git a/adonis-typings/migrator.ts b/src/types/migrator.ts similarity index 100% rename from adonis-typings/migrator.ts rename to src/types/migrator.ts diff --git a/adonis-typings/model.ts b/src/types/model.ts similarity index 100% rename from adonis-typings/model.ts rename to src/types/model.ts diff --git a/adonis-typings/querybuilder.ts b/src/types/querybuilder.ts similarity index 100% rename from adonis-typings/querybuilder.ts rename to src/types/querybuilder.ts diff --git a/adonis-typings/relations.ts b/src/types/relations.ts similarity index 99% rename from adonis-typings/relations.ts rename to src/types/relations.ts index cd73937c..49f2ebcb 100644 --- a/adonis-typings/relations.ts +++ b/src/types/relations.ts @@ -282,11 +282,6 @@ export interface BaseRelationContract< readonly booted: boolean readonly model: ParentModel - foreignKey: string - foreignKeyColumnName: string - localKey: string - localKeyColumnName: string - relatedModel(): RelatedModel boot(): void clone(parent: LucidModel): this @@ -317,6 +312,8 @@ export interface HasOneRelationContract< readonly type: 'hasOne' readonly localKey: string readonly foreignKey: string + foreignKeyColumnName: string + localKeyColumnName: string /** * Set related model as a relationship on the parent model. @@ -365,6 +362,8 @@ export interface HasManyRelationContract< readonly type: 'hasMany' readonly localKey: string readonly foreignKey: string + foreignKeyColumnName: string + localKeyColumnName: string /** * Set related models as a relationship on the parent model @@ -416,6 +415,8 @@ export interface BelongsToRelationContract< readonly type: 'belongsTo' readonly localKey: string readonly foreignKey: string + foreignKeyColumnName: string + localKeyColumnName: string /** * Set related model as a relationship on the parent model @@ -538,6 +539,8 @@ export interface HasManyThroughRelationContract< readonly throughForeignKey: string throughLocalKeyColumnName: string throughForeignKeyColumnName: string + foreignKeyColumnName: string + localKeyColumnName: string /** * Set related models as a relationship on the parent model diff --git a/adonis-typings/schema.ts b/src/types/schema.ts similarity index 100% rename from adonis-typings/schema.ts rename to src/types/schema.ts diff --git a/adonis-typings/seeder.ts b/src/types/seeder.ts similarity index 100% rename from adonis-typings/seeder.ts rename to src/types/seeder.ts diff --git a/src/utils/index.ts b/src/utils/index.ts index bda238eb..0aad5a02 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -10,13 +10,9 @@ import slash from 'slash' import { join, extname } from 'node:path' import { Exception, fsReadAll, isScriptFile } from '@poppinss/utils' -import { RelationshipsContract } from '../../adonis-typings/relations.js' -import { LucidRow, ModelObject, CherryPickFields } from '../../adonis-typings/model.js' -import { - FileNode, - QueryClientContract, - TransactionClientContract, -} from '../../adonis-typings/database.js' +import { RelationshipsContract } from '../types/relations.js' +import { LucidRow, ModelObject, CherryPickFields } from '../types/model.js' +import { FileNode, QueryClientContract, TransactionClientContract } from '../types/database.js' import { fileURLToPath, pathToFileURL } from 'node:url' /** diff --git a/templates/database.txt b/stubs/database.txt similarity index 100% rename from templates/database.txt rename to stubs/database.txt diff --git a/stubs/factories/index.txt b/stubs/factories/index.txt new file mode 100644 index 00000000..25f391a2 --- /dev/null +++ b/stubs/factories/index.txt @@ -0,0 +1 @@ +import factory from '@adonisjs/lucid/factories' diff --git a/stubs/main.ts b/stubs/main.ts new file mode 100644 index 00000000..17bd1342 --- /dev/null +++ b/stubs/main.ts @@ -0,0 +1,12 @@ +/* + * @adonisjs/lucid + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { getDirname } from '@poppinss/utils' + +export const stubsRoot = getDirname(import.meta.url) diff --git a/stubs/make/factory/main.stub b/stubs/make/factory/main.stub new file mode 100644 index 00000000..fe2522b8 --- /dev/null +++ b/stubs/make/factory/main.stub @@ -0,0 +1,16 @@ +{{#var factoryName = generators.factoryName(entity.name)}} +{{#var factoryFileName = generators.factoryFileName(entity.name)}} +{{#var modelName = generators.modelName(model.name)}} +{{#var modelFileName = generators.modelFileName(model.name)}} +{{#var modelImportPath = generators.importPath('#models', model.path, modelFileName.replace(/\.ts$/, ''))}} +--- +to: {{ app.factoriesPath(entity.path, factoryFileName) }} +--- +import factory from '@adonisjs/lucid/factories' +import {{ modelName }} from '{{ modelImportPath }}' + +export const {{ factoryName }} = factory + .define({{ modelName }}, ({ faker }) => { + return {} + }) + .build() diff --git a/stubs/make/migration/alter.stub b/stubs/make/migration/alter.stub new file mode 100644 index 00000000..34120a3b --- /dev/null +++ b/stubs/make/migration/alter.stub @@ -0,0 +1,17 @@ +--- +to: {{ app.makePath(migration.folder, entity.path, migration.fileName) }} +--- +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = '{{ migration.tableName }}' + + async up () { + this.schema.alterTable(this.tableName, (table) => { + }) + } + + async down () { + this.schema.alterTable(this.tableName) + } +} diff --git a/templates/migration-make.txt b/stubs/make/migration/create.stub similarity index 63% rename from templates/migration-make.txt rename to stubs/make/migration/create.stub index 29b468d8..b57f2390 100644 --- a/templates/migration-make.txt +++ b/stubs/make/migration/create.stub @@ -1,9 +1,12 @@ -import BaseSchema from '@ioc:Adonis/Lucid/Schema' +--- +to: {{ app.makePath(migration.folder, entity.path, migration.fileName) }} +--- +import { BaseSchema } from '@adonisjs/lucid/schema' export default class extends BaseSchema { - protected tableName = '{{#toTableName}}{{ filename }}{{/toTableName}}' + protected tableName = '{{ migration.tableName }}' - public async up () { + async up () { this.schema.createTable(this.tableName, (table) => { table.increments('id') @@ -15,7 +18,7 @@ export default class extends BaseSchema { }) } - public async down () { + async down () { this.schema.dropTable(this.tableName) } } diff --git a/stubs/make/model/main.stub b/stubs/make/model/main.stub new file mode 100644 index 00000000..b994560d --- /dev/null +++ b/stubs/make/model/main.stub @@ -0,0 +1,18 @@ +{{#var modelName = generators.modelName(entity.name)}} +{{#var modelFileName = generators.modelFileName(entity.name)}} +--- +to: {{ app.modelsPath(entity.path, modelFileName) }} +--- +import { DateTime } from 'luxon' +import { BaseModel, column } from '@adonisjs/lucid/orm' + +export default class {{ modelName }} extends BaseModel { + @column({ isPrimary: true }) + declare id: number + + @column.dateTime({ autoCreate: true }) + declare createdAt: DateTime + + @column.dateTime({ autoCreate: true, autoUpdate: true }) + declare updatedAt: DateTime +} diff --git a/stubs/make/seeder/main.stub b/stubs/make/seeder/main.stub new file mode 100644 index 00000000..1be66bba --- /dev/null +++ b/stubs/make/seeder/main.stub @@ -0,0 +1,11 @@ +{{#var seederFileName = generators.seederFileName(entity.name)}} +--- +to: {{ app.seedersPath(entity.path, seederFileName) }} +--- +import { BaseSeeder } from '@adonisjs/lucid/seeders' + +export default class extends BaseSeeder { + async run () { + // Write your database queries inside the run method + } +} diff --git a/templates/seeder.txt b/stubs/seeder.txt similarity index 100% rename from templates/seeder.txt rename to stubs/seeder.txt diff --git a/templates/factories/index.txt b/templates/factories/index.txt deleted file mode 100644 index de08b6b6..00000000 --- a/templates/factories/index.txt +++ /dev/null @@ -1 +0,0 @@ -// import Factory from '@ioc:Adonis/Lucid/Factory' diff --git a/templates/factory.txt b/templates/factory.txt deleted file mode 100644 index a17e7630..00000000 --- a/templates/factory.txt +++ /dev/null @@ -1,8 +0,0 @@ -import {{#toModelName}}{{{ model }}}{{/toModelName}} from '{{{ modelImportPath }}}' -import Factory from '@ioc:Adonis/Lucid/Factory' - -export default Factory.define({{#toModelName}}{{{ model }}}{{/toModelName}}, ({ faker }) => { - return { - // - } -}).build() diff --git a/templates/migration-alter.txt b/templates/migration-alter.txt deleted file mode 100644 index acf62567..00000000 --- a/templates/migration-alter.txt +++ /dev/null @@ -1,15 +0,0 @@ -import BaseSchema from '@ioc:Adonis/Lucid/Schema' - -export default class extends BaseSchema { - protected tableName = '{{#toTableName}}{{ filename }}{{/toTableName}}' - - public async up () { - this.schema.alterTable(this.tableName, (table) => { - }) - } - - public async down () { - this.schema.alterTable(this.tableName, (table) => { - }) - } -} diff --git a/templates/model.txt b/templates/model.txt deleted file mode 100644 index d74542ea..00000000 --- a/templates/model.txt +++ /dev/null @@ -1,13 +0,0 @@ -import { DateTime } from 'luxon' -import { BaseModel, column } from '@ioc:Adonis/Lucid/Orm' - -export default class {{ filename }} extends BaseModel { - @column({ isPrimary: true }) - public id: number - - @column.dateTime({ autoCreate: true }) - public createdAt: DateTime - - @column.dateTime({ autoCreate: true, autoUpdate: true }) - public updatedAt: DateTime -} diff --git a/test-helpers/index.ts b/test-helpers/index.ts index 7e492e7d..a1406e15 100644 --- a/test-helpers/index.ts +++ b/test-helpers/index.ts @@ -16,32 +16,26 @@ import { Logger } from '@adonisjs/core/logger' import { Emitter } from '@adonisjs/core/events' import { AppFactory } from '@adonisjs/core/factories/app' -import { - ConnectionConfig, - ConnectionContract, - QueryClientContract, -} from '../adonis-typings/database.js' +import { ConnectionConfig, ConnectionContract, DatabaseConfig, QueryClientContract } from '../src/types/database.js' import { RawQueryBuilderContract, InsertQueryBuilderContract, DatabaseQueryBuilderContract, -} from '../adonis-typings/querybuilder.js' +} from '../src/types/querybuilder.js' -import { MigratorOptions } from '../adonis-typings/migrator.js' -import { LucidRow, LucidModel, AdapterContract } from '../adonis-typings/model.js' +import { MigratorOptions } from '../src/types/migrator.js' +import { LucidRow, LucidModel, AdapterContract } from '../src/types/model.js' import { fileURLToPath } from 'node:url' -// import { QueryClient } from '../src/QueryClient/index.js' -import { DefineCallback, FactoryModelContract } from '../adonis-typings/factory.js' import { QueryClient } from '../src/query_client/index.js' -import { Database } from '../src/database/index.js' +import { Database } from '../src/database/main.js' import { DatabaseQueryBuilder } from '../src/database/query_builder/database.js' import { RawQueryBuilder } from '../src/database/query_builder/raw.js' import { InsertQueryBuilder } from '../src/database/query_builder/insert.js' -import { Migrator } from '../src/migrator/index.js' +import { MigrationRunner } from '../src/migration/runner.js' import { Application } from '@adonisjs/core/app' -import { Schema } from '../src/schema/index.js' +import { Schema } from '../src/schema/main.js' import { BaseModel } from '../src/orm/base_model/index.js' import { Adapter } from '../src/orm/adapter/index.js' @@ -405,8 +399,8 @@ export function getInsertBuilder(client: QueryClientContract) { /** * Returns the database instance */ -export function getDb(eventEmitter?: Emitter) { - const config = { +export function getDb(eventEmitter?: Emitter, config?: DatabaseConfig) { + const defaultConfig = { connection: 'primary', connections: { primary: getConfig(), @@ -414,7 +408,7 @@ export function getDb(eventEmitter?: Emitter) { }, } - const db = new Database(config, logger, eventEmitter || createEmitter()) + const db = new Database(config || defaultConfig, logger, eventEmitter || createEmitter()) const test = getActiveTest() test?.cleanup(() => { return db.manager.closeAll() @@ -538,7 +532,7 @@ export class FakeAdapter implements AdapterContract { export function mapToObj(collection: Map): T { let obj = {} as T collection.forEach((value, key) => { - obj[key] = value + ;(obj as any)[key] = value }) return obj } @@ -554,7 +548,7 @@ export function getBaseSchema() { * Returns instance of migrator */ export function getMigrator(db: Database, application: Application, config: MigratorOptions) { - return new Migrator(db, application, config) + return new MigrationRunner(db, application, config) } /** @@ -590,58 +584,6 @@ export function getPosts(count: number, userId: number) { }) } -/** - * Setup application - */ -export async function setupApplication( - dbConfig?: any, - additionalProviders?: string[], - environment: 'web' | 'repl' | 'test' = 'test' -) { - await fs.add('.env', '') - await fs.add( - 'config/app.ts', - ` - export const appKey = 'averylong32charsrandomsecretkey', - export const http = { - cookie: {}, - trustProxy: () => true, - } - ` - ) - - await fs.add( - 'config/database.ts', - ` - const dbConfig = ${JSON.stringify(dbConfig, null, 2)} - export default dbConfig - ` - ) - - const app = new Application(fs.basePath, environment, { - aliases: { - App: './app', - }, - providers: ['@adonisjs/core', '@adonisjs/repl'].concat(additionalProviders || []), - }) - - await app.setup() - await app.registerProviders() - await app.bootProviders() - - if (process.env.DEBUG) { - app.container.use('Adonis/Core/Event').on('db:query', (query) => { - console.log({ - model: query.model, - sql: query.sql, - bindings: query.bindings, - }) - }) - } - - return app -} - export async function setupReplicaDb(connection: Knex, datatoInsert: { username: string }[]) { const hasUsersTable = await connection.schema.hasTable('replica_users') if (!hasUsersTable) { diff --git a/test/bindings/validator.spec.ts b/test/bindings/validator.spec.ts index e5365500..154cc5ca 100644 --- a/test/bindings/validator.spec.ts +++ b/test/bindings/validator.spec.ts @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ -/// +/// import { test } from '@japa/runner' import { rules } from '@adonisjs/validator/build/src/Rules' diff --git a/test/commands/db-wipe.spec.ts b/test/commands/db-wipe.spec.ts deleted file mode 100644 index 51769055..00000000 --- a/test/commands/db-wipe.spec.ts +++ /dev/null @@ -1,68 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/// - -import 'reflect-metadata' -import { test } from '@japa/runner' -import Migrate from '../../commands/Migration/Run' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import DbWipe from '../../commands/DbWipe' -import { Migrator } from '../../src/Migrator' -import { fs, setup, cleanup, getDb, setupApplication } from '../../test-helpers' - -let app: ApplicationContract -let db: ReturnType - -test.group('db:wipe and migrate:fresh', (group) => { - group.each.setup(async () => { - app = await setupApplication() - return () => fs.cleanup() - }) - - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) - app.container.bind('Adonis/Lucid/Migrator', () => Migrator) - await setup() - - return async () => { - await cleanup() - await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users']) - await db.manager.closeAll() - } - }) - - test('db:wipe should drop all tables', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', - ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { - public async up () { - this.schema.createTable('schema_users', (table) => { - table.increments() - }) - } - } - ` - ) - - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate, DbWipe]) - - await kernel.exec('migration:run', []) - assert.isAbove((await db.connection().getAllTables(['public'])).length, 0) - - await kernel.exec('db:wipe', []) - assert.lengthOf(await db.connection().getAllTables(['public']), 0) - }) -}) diff --git a/test/commands/db-seed.spec.ts b/test/commands/db_seed.spec.ts similarity index 50% rename from test/commands/db-seed.spec.ts rename to test/commands/db_seed.spec.ts index 3f591fa5..eb5db1d3 100644 --- a/test/commands/db-seed.spec.ts +++ b/test/commands/db_seed.spec.ts @@ -7,57 +7,50 @@ * file that was distributed with this source code. */ -/// - import 'reflect-metadata' import { test } from '@japa/runner' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import DbSeed from '../../commands/DbSeed' -import { fs, setup, cleanup, getDb, setupApplication } from '../../test-helpers' +import { AceFactory } from '@adonisjs/core/factories' -let app: ApplicationContract -let db: ReturnType +import DbSeed from '../../commands/db_seed.js' +import { setup, cleanup, getDb } from '../../test-helpers/index.js' test.group('DbSeed', (group) => { group.each.setup(async () => { - app = await setupApplication() - return () => fs.cleanup() - }) - - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) await setup() return async () => { await cleanup() await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users', 'schema_accounts']) - await db.manager.closeAll(true) } }) - test('run seeders', async ({ assert }) => { - await fs.add( + test('run seeders', async ({ fs, assert }) => { + await fs.create( 'database/seeders/user.ts', `export default class UserSeeder { - public async run () { + async run () { process.env.EXEC_USER_SEEDER = 'true' } }` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([DbSeed]) - await kernel.exec('db:seed', []) + const ace = await new AceFactory().make(fs.baseUrl, { + importer: () => {}, + }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => getDb()) + ace.ui.switchMode('raw') + + const command = await ace.create(DbSeed, []) + await command.exec() + command.assertLog('green(❯) green(completed) database/seeders/user') assert.equal(process.env.EXEC_USER_SEEDER, 'true') delete process.env.EXEC_USER_SEEDER }) - test('cherry pick files', async ({ assert }) => { - await fs.add( + test('cherry pick files using the --files flag', async ({ fs, assert }) => { + await fs.create( 'database/seeders/user.ts', `export default class UserSeeder { public async run () { @@ -66,7 +59,7 @@ test.group('DbSeed', (group) => { }` ) - await fs.add( + await fs.create( 'database/seeders/post.ts', `export default class PostSeeder { public async run () { @@ -75,31 +68,44 @@ test.group('DbSeed', (group) => { }` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([DbSeed]) - await kernel.exec('db:seed', ['--files', './database/seeders/post.ts']) + const ace = await new AceFactory().make(fs.baseUrl, { + importer: () => {}, + }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => getDb()) + ace.ui.switchMode('raw') + + const command = await ace.create(DbSeed, ['--files', './database/seeders/post.ts']) + await command.exec() + + assert.deepEqual(command.logger.getLogs(), [ + { + message: 'green(❯) green(completed) database/seeders/post', + stream: 'stdout', + }, + ]) assert.isUndefined(process.env.EXEC_USER_SEEDER) assert.equal(process.env.EXEC_POST_SEEDER, 'true') delete process.env.EXEC_POST_SEEDER }) - test('run seeders with compact output', async ({ assert }) => { - await fs.add( + test('run seeders with compact output', async ({ fs }) => { + await fs.create( 'database/seeders/user.ts', `export default class UserSeeder { public async run () {} }` ) - await fs.add( + await fs.create( 'database/seeders/client.ts', `export default class ClientSeeder { public async run () {} }` ) - await fs.add( + await fs.create( 'database/seeders/post.ts', `export default class PostSeeder { public static developmentOnly = true @@ -108,14 +114,16 @@ test.group('DbSeed', (group) => { }` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([DbSeed]) + const ace = await new AceFactory().make(fs.baseUrl, { + importer: () => {}, + }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => getDb()) + ace.ui.switchMode('raw') - app.nodeEnvironment = 'production' - const command = await kernel.exec('db:seed', ['--compact-output']) - app.nodeEnvironment = 'test' + const command = await ace.create(DbSeed, ['--compact-output']) + await command.exec() - assert.deepEqual(command.ui.testingRenderer.logs.length, 1) - assert.deepInclude(command.ui.testingRenderer.logs[0].message, 'Executed 2 seeders, 1 ignored') + command.assertLog('grey(❯ Executed 3 seeders)') }) }) diff --git a/test/commands/db-truncate.spec.ts b/test/commands/db_truncate.spec.ts similarity index 65% rename from test/commands/db-truncate.spec.ts rename to test/commands/db_truncate.spec.ts index eb90f081..d7d31df5 100644 --- a/test/commands/db-truncate.spec.ts +++ b/test/commands/db_truncate.spec.ts @@ -8,41 +8,34 @@ */ import { test } from '@japa/runner' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' -import { fs, setup, cleanup, getDb, setupApplication } from '../../test-helpers' -import DbTruncate from '../../commands/DbTruncate' +import { AceFactory } from '@adonisjs/core/factories' -let app: ApplicationContract -let db: ReturnType +import DbTruncate from '../../commands/db_truncate.js' +import { setup, cleanup, getDb } from '../../test-helpers/index.js' test.group('db:truncate', (group) => { group.each.setup(async () => { - app = await setupApplication() - return () => fs.cleanup() - }) - - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) await setup() return async () => { await cleanup() await cleanup(['adonis_schema', 'adonis_schema_versions']) - await db.manager.closeAll() } }) - test('should truncate all tables', async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([DbTruncate]) + test('should truncate all tables', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') await db.table('users').insert({ username: 'bonjour' }) await db.table('users').insert({ username: 'bonjour2' }) await db.table('friends').insert({ username: 'bonjour' }) - await kernel.exec('db:truncate', []) + const command = await ace.create(DbTruncate, []) + await command.exec() const usersCount = await db.from('users').count('*', 'total') const friendsCount = await db.from('friends').count('*', 'total') @@ -51,9 +44,12 @@ test.group('db:truncate', (group) => { assert.equal(friendsCount[0]['total'], 0) }) - test('should not truncate adonis migrations tables', async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([DbTruncate]) + test('should not truncate adonis migrations tables', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') await db.connection().schema.createTable('adonis_schema', (table) => { table.increments('id') @@ -68,7 +64,8 @@ test.group('db:truncate', (group) => { await db.table('adonis_schema').insert({ name: 'bonjour' }) await db.table('adonis_schema_versions').insert({ name: 'bonjour' }) - await kernel.exec('db:truncate', []) + const command = await ace.create(DbTruncate, []) + await command.exec() const adonisSchemaCount = await db.from('adonis_schema').count('*', 'total') const adonisSchemaVersionsCount = await db.from('adonis_schema_versions').count('*', 'total') diff --git a/test/commands/db_wipe.spec.ts b/test/commands/db_wipe.spec.ts new file mode 100644 index 00000000..7fc61321 --- /dev/null +++ b/test/commands/db_wipe.spec.ts @@ -0,0 +1,60 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import 'reflect-metadata' +import { test } from '@japa/runner' +import { AceFactory } from '@adonisjs/core/factories' + +import DbWipe from '../../commands/db_wipe.js' +import Migrate from '../../commands/migration/run.js' +import { setup, cleanup, getDb } from '../../test-helpers/index.js' + +test.group('db:wipe and migrate:fresh', (group) => { + group.each.setup(async () => { + await setup() + + return async () => { + await cleanup() + await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users']) + } + }) + + test('db:wipe should drop all tables', async ({ fs, assert }) => { + await fs.create( + 'database/migrations/users.ts', + ` + import { Schema } from '../../../../src/Schema' + module.exports = class User extends Schema { + public async up () { + this.schema.createTable('schema_users', (table) => { + table.increments() + }) + } + } + ` + ) + + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + const migrate = await ace.create(Migrate, []) + await migrate.exec() + + const tables = await db.connection().getAllTables(['public']) + assert.isAbove(tables.length, 0) + + const dbWipe = await ace.create(DbWipe, []) + await dbWipe.exec() + + assert.lengthOf(await db.connection().getAllTables(['public']), 0) + }) +}) diff --git a/test/commands/make-factory.spec.ts b/test/commands/make-factory.spec.ts deleted file mode 100644 index 4266e99a..00000000 --- a/test/commands/make-factory.spec.ts +++ /dev/null @@ -1,96 +0,0 @@ -/* - * @adonisjs/assembler - * - * (c) AdonisJS - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -import { test } from '@japa/runner' -import { join } from 'path' -import { Kernel } from '@adonisjs/ace' -import { Filesystem } from '@poppinss/dev-utils' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' -import MakeFactory from '../../commands/MakeFactory' -import { - fs, - toNewlineArray, - setupApplication, - replaceFactoryBindings, -} from '../../test-helpers/index' - -const templates = new Filesystem(join(__dirname, '..', '..', 'templates')) - -test.group('Make Factory', async (group) => { - let app: ApplicationContract - - group.each.setup(async () => { - app = await setupApplication() - return () => fs.cleanup() - }) - - test('generate a factory for {model}') - .with([ - { - argument: 'User', - model: 'User', - finalDestination: 'UserFactory.ts', - finalImportPath: 'App/Models/User', - }, - { - argument: 'Blog/Post', - model: 'Post', - finalDestination: 'Blog/PostFactory.ts', - finalImportPath: 'App/Models/Blog/Post', - }, - ]) - .run(async ({ assert }, set) => { - const factory = new MakeFactory(app, new Kernel(app).mockConsoleOutput()) - - factory.model = set.argument - await factory.run() - - const UserFactory = await fs.get(`database/factories/${set.finalDestination}`) - const factoryTemplate = await templates.get('factory.txt') - - assert.deepEqual( - toNewlineArray(UserFactory), - replaceFactoryBindings(factoryTemplate, set.model, set.finalImportPath) - ) - }) - - test('generate a factory with custom import path') - .with([ - { - argument: 'User', - model: 'User', - modelPath: 'Test/User', - finalDestination: 'UserFactory.ts', - finalImportPath: 'App/Models/Test/User', - }, - { - argument: 'Client', - model: 'Client', - modelPath: 'App/Models/Test/B/Client', - finalDestination: 'ClientFactory.ts', - finalImportPath: 'App/Models/Test/B/Client', - }, - ]) - .run(async ({ assert }, set) => { - const factory = new MakeFactory(app, new Kernel(app).mockConsoleOutput()) - - factory.model = set.model - factory.modelPath = set.modelPath - - await factory.run() - - const UserFactory = await fs.get(`database/factories/${set.finalDestination}`) - const factoryTemplate = await templates.get('factory.txt') - - assert.deepEqual( - toNewlineArray(UserFactory), - replaceFactoryBindings(factoryTemplate, set.model, set.finalImportPath) - ) - }) -}) diff --git a/test/commands/make-migration.spec.ts b/test/commands/make-migration.spec.ts deleted file mode 100644 index 30fbbf05..00000000 --- a/test/commands/make-migration.spec.ts +++ /dev/null @@ -1,198 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/// - -import 'reflect-metadata' -import { join } from 'path' -import { test } from '@japa/runner' -import { Filesystem } from '@poppinss/dev-utils' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import { Database } from '../../src/Database' -import MakeMigration from '../../commands/MakeMigration' -import { - fs, - setup, - getDb, - cleanup, - getConfig, - toNewlineArray, - setupApplication, -} from '../../test-helpers' - -let db: ReturnType -let app: ApplicationContract -const templatesFs = new Filesystem(join(__dirname, '..', '..', 'templates')) - -test.group('MakeMigration', (group) => { - group.each.setup(async () => { - app = await setupApplication() - return () => fs.cleanup() - }) - - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) - await setup() - - return async () => { - await cleanup() - await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users', 'schema_accounts']) - await db.manager.closeAll(true) - } - }) - - test('create migration in the default migrations directory', async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeMigration]) - const makeMigration = await kernel.exec('make:migration', ['user']) - - assert.lengthOf(makeMigration.ui.testingRenderer.logs, 1) - const successLog = makeMigration.ui.testingRenderer.logs[0] - - const userSchema = await fs.get(successLog.message.replace('green(CREATE:)', '').trim()) - const schemaTemplate = await templatesFs.get('migration-make.txt') - - assert.deepEqual( - toNewlineArray(userSchema), - toNewlineArray( - schemaTemplate - .replace('{{#toClassName}}{{ filename }}{{/toClassName}}', 'Users') - .replace('{{#toTableName}}{{ filename }}{{/toTableName}}', 'users') - ) - ) - }) - - test('create migration for alter table', async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeMigration]) - const makeMigration = await kernel.exec('make:migration', ['user', '--table=my_users']) - - assert.lengthOf(makeMigration.ui.testingRenderer.logs, 1) - const successLog = makeMigration.ui.testingRenderer.logs[0] - - const userSchema = await fs.get(successLog.message.replace('green(CREATE:)', '').trim()) - const schemaTemplate = await templatesFs.get('migration-alter.txt') - - assert.deepEqual( - toNewlineArray(userSchema), - toNewlineArray( - schemaTemplate - .replace('{{#toClassName}}{{ filename }}{{/toClassName}}', 'MyUsers') - .replace('{{#toTableName}}{{ filename }}{{/toTableName}}', 'my_users') - ) - ) - }) - - test('create migration for make table with custom table name', async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeMigration]) - const makeMigration = await kernel.exec('make:migration', ['user', '--create=my_users']) - - assert.lengthOf(makeMigration.ui.testingRenderer.logs, 1) - const successLog = makeMigration.ui.testingRenderer.logs[0] - - const userSchema = await fs.get(successLog.message.replace('green(CREATE:)', '').trim()) - const schemaTemplate = await templatesFs.get('migration-make.txt') - - assert.deepEqual( - toNewlineArray(userSchema), - toNewlineArray( - schemaTemplate - .replace('{{#toClassName}}{{ filename }}{{/toClassName}}', 'MyUsers') - .replace('{{#toTableName}}{{ filename }}{{/toTableName}}', 'my_users') - ) - ) - }) - - test('create migration file inside a sub-folder', async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeMigration]) - const makeMigration = await kernel.exec('make:migration', ['profile/users', '--create=users']) - - assert.lengthOf(makeMigration.ui.testingRenderer.logs, 1) - const successLog = makeMigration.ui.testingRenderer.logs[0] - - const userSchema = await fs.get(successLog.message.replace('green(CREATE:)', '').trim()) - const schemaTemplate = await templatesFs.get('migration-make.txt') - - assert.deepEqual( - toNewlineArray(userSchema), - toNewlineArray( - schemaTemplate - .replace('{{#toClassName}}{{ filename }}{{/toClassName}}', 'Users') - .replace('{{#toTableName}}{{ filename }}{{/toTableName}}', 'users') - ) - ) - }) - - test('raise error when defined connection is invalid', async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeMigration]) - const makeMigration = await kernel.exec('make:migration', ['profile/users', '--connection=foo']) - - assert.equal(makeMigration.exitCode, 1) - assert.deepEqual(makeMigration.ui.testingRenderer.logs, [ - { - stream: 'stderr', - message: - '[ red(error) ] "foo" is not a valid connection name. Double check "config/database" file', - }, - ]) - }) - - test('use custom directory when defined') - .setup(() => { - const config = { - connection: 'primary', - connections: { - primary: Object.assign( - { - migrations: { - paths: ['database/a', 'database/b'], - }, - }, - getConfig() - ), - }, - } - - const customDb = new Database( - config, - app.logger, - app.profiler, - app.container.use('Adonis/Core/Event') - ) - - app.container.bind('Adonis/Lucid/Database', () => customDb) - return () => customDb.manager.closeAll() - }) - .run(async ({ assert }) => { - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeMigration]) - const makeMigration = await kernel.exec('make:migration', ['users', '--folder=database/c']) - - const successLog = makeMigration.ui.testingRenderer.logs[0].message - const userSchema = await fs.get(successLog.replace('green(CREATE:)', '').trim()) - const schemaTemplate = await templatesFs.get('migration-make.txt') - - assert.isTrue(successLog.startsWith('green(CREATE:) database/c')) - - assert.deepEqual( - toNewlineArray(userSchema), - toNewlineArray( - schemaTemplate - .replace('{{#toClassName}}{{ filename }}{{/toClassName}}', 'Users') - .replace('{{#toTableName}}{{ filename }}{{/toTableName}}', 'users') - ) - ) - }) -}) diff --git a/test/commands/make-model.spec.ts b/test/commands/make-model.spec.ts deleted file mode 100644 index 94c2764f..00000000 --- a/test/commands/make-model.spec.ts +++ /dev/null @@ -1,61 +0,0 @@ -/* - * @adonisjs/lucid - * - * (c) Harminder Virk - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/// - -import 'reflect-metadata' -import { join } from 'path' -import { test } from '@japa/runner' -import { Filesystem } from '@poppinss/dev-utils' -import { Kernel } from '@adonisjs/core/build/standalone' - -import MakeModel from '../../commands/MakeModel' -import { toNewlineArray, fs, setupApplication } from '../../test-helpers' - -const templatesFs = new Filesystem(join(__dirname, '..', '..', 'templates')) - -test.group('MakeModel', (group) => { - group.each.teardown(async () => { - delete process.env.ADONIS_ACE_CWD - await fs.cleanup() - }) - - test('make a model inside the default directory', async ({ assert }) => { - const app = await setupApplication() - - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeModel]) - await kernel.exec('make:model', ['user']) - - const userModel = await fs.get('app/Models/User.ts') - const schemaTemplate = await templatesFs.get('model.txt') - - assert.deepEqual( - toNewlineArray(userModel), - toNewlineArray(schemaTemplate.replace('{{ filename }}', 'User')) - ) - }) - - test('make a model inside a custom directory', async ({ assert }) => { - const app = await setupApplication() - app.rcFile.namespaces.models = 'App' - - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([MakeModel]) - await kernel.exec('make:model', ['user']) - - const userModel = await fs.get('app/User.ts') - const schemaTemplate = await templatesFs.get('model.txt') - - assert.deepEqual( - toNewlineArray(userModel), - toNewlineArray(schemaTemplate.replace('{{ filename }}', 'User')) - ) - }) -}) diff --git a/test/commands/make_factory.spec.ts b/test/commands/make_factory.spec.ts new file mode 100644 index 00000000..f3cd916e --- /dev/null +++ b/test/commands/make_factory.spec.ts @@ -0,0 +1,42 @@ +/* + * @adonisjs/assembler + * + * (c) AdonisJS + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { test } from '@japa/runner' +import MakeFactory from '../../commands/make_factory.js' +import { AceFactory } from '@adonisjs/core/factories' + +test.group('Make Factory', async () => { + test('generate a factory for {model}') + .with([ + { + model: 'User', + factoryDestination: 'user_factory.ts', + modelImportPath: '#models/user', + }, + { + model: 'blog/Post', + factoryDestination: 'blog/post_factory.ts', + modelImportPath: '#models/blog/post', + }, + ]) + .run(async ({ assert, fs }, set) => { + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeFactory, [set.model]) + await command.exec() + + command.assertLog(`green(DONE:) create database/factories/${set.factoryDestination}`) + await assert.fileContains( + `database/factories/${set.factoryDestination}`, + `import ${set.model.split('/').pop()} from '${set.modelImportPath}'` + ) + }) +}) diff --git a/test/commands/make_migration.spec.ts b/test/commands/make_migration.spec.ts new file mode 100644 index 00000000..93f667e4 --- /dev/null +++ b/test/commands/make_migration.spec.ts @@ -0,0 +1,125 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { test } from '@japa/runner' +import { AceFactory } from '@adonisjs/core/factories' + +import MakeMigration from '../../commands/make_migration.js' +import { setup, getDb, cleanup, getConfig } from '../../test-helpers/index.js' + +function fileNameFromLog(message: string) { + return message + .replace(/green\(DONE\:\)/, '') + .trim() + .replace(/^create/, '') + .trim() +} + +test.group('MakeMigration', (group) => { + group.each.setup(async () => { + await setup() + + return async () => { + await cleanup() + await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users', 'schema_accounts']) + } + }) + + test('create migration in the default migrations directory', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + ace.app.container.singleton('lucid.db', () => db) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeMigration, ['users']) + await command.exec() + const filename = fileNameFromLog(command.logger.getLogs()[0].message) + + command.assertLogMatches(/database\/migrations\/\d+_create_users_table/) + await assert.fileContains(filename, `import { BaseSchema } from '@adonisjs/lucid/schema'`) + await assert.fileContains(filename, `protected tableName = 'users'`) + await assert.fileContains(filename, `this.schema.createTable`) + }) + + test('create migration for alter table', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + ace.app.container.singleton('lucid.db', () => db) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeMigration, ['users', '--alter']) + await command.exec() + const filename = fileNameFromLog(command.logger.getLogs()[0].message) + + command.assertLogMatches(/database\/migrations\/\d+_alter_users_table/) + await assert.fileContains(filename, `import { BaseSchema } from '@adonisjs/lucid/schema'`) + await assert.fileContains(filename, `protected tableName = 'users'`) + await assert.fileContains(filename, `this.schema.alterTable`) + }) + + test('create migration file inside a sub-folder', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + ace.app.container.singleton('lucid.db', () => db) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeMigration, ['invoices/lineItem', '--alter']) + await command.exec() + const filename = fileNameFromLog(command.logger.getLogs()[0].message) + + command.assertLogMatches(/database\/migrations\/invoices\/\d+_alter_line_items_table/) + await assert.fileContains(filename, `import { BaseSchema } from '@adonisjs/lucid/schema'`) + await assert.fileContains(filename, `protected tableName = 'line_items'`) + await assert.fileContains(filename, `this.schema.alterTable`) + }) + + test('print error when using an invalid db connection', async ({ fs }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + ace.app.container.singleton('lucid.db', () => db) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeMigration, ['users', '--connection', 'foo']) + await command.exec() + + command.assertFailed() + command.assertLog( + '[ red(error) ] "foo" is not a valid connection name. Double check "config/database" file', + 'stderr' + ) + }) + + test('pick directory from migration sources').run(async ({ fs }) => { + const db = getDb(undefined, { + connection: 'primary', + connections: { + primary: Object.assign(getConfig(), { + migrations: { + paths: ['database/foo', './database/bar'], + }, + }), + }, + }) + + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + ace.app.container.singleton('lucid.db', () => db) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeMigration, ['users']) + command.prompt.trap('Select the migrations folder').chooseOption(0) + + await command.exec() + command.assertLogMatches(/database\/foo\/\d+_create_users_table/) + }) +}) diff --git a/test/commands/make_model.spec.ts b/test/commands/make_model.spec.ts new file mode 100644 index 00000000..2d97911d --- /dev/null +++ b/test/commands/make_model.spec.ts @@ -0,0 +1,81 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { test } from '@japa/runner' +import { ListLoader } from '@adonisjs/core/ace' +import { AceFactory } from '@adonisjs/core/factories' + +import { getDb } from '../../test-helpers/index.js' +import MakeModel from '../../commands/make_model.js' +import MakeFactory from '../../commands/make_factory.js' +import MakeMigration from '../../commands/make_migration.js' + +test.group('MakeModel', (group) => { + group.each.teardown(async () => { + delete process.env.ADONIS_ACE_CWD + }) + + test('make a model', async ({ fs, assert }) => { + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeModel, ['user']) + await command.exec() + + command.assertLog('green(DONE:) create app/models/user.ts') + await assert.fileContains('app/models/user.ts', 'export default class User extends BaseModel {') + await assert.fileContains( + 'app/models/user.ts', + `import { BaseModel, column } from '@adonisjs/lucid/orm'` + ) + }) + + test('make a model with migration', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + ace.app.container.singleton('lucid.db', () => db) + await ace.app.init() + ace.ui.switchMode('raw') + + ace.addLoader(new ListLoader([MakeMigration])) + + const command = await ace.create(MakeModel, ['user', '--migration']) + await command.exec() + + command.assertLog('green(DONE:) create app/models/user.ts') + command.assertLogMatches(/database\/migrations\/\d+_create_users_table/) + await assert.fileContains('app/models/user.ts', 'export default class User extends BaseModel {') + await assert.fileContains( + 'app/models/user.ts', + `import { BaseModel, column } from '@adonisjs/lucid/orm'` + ) + }) + + test('make a model with factory', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + ace.app.container.singleton('lucid.db', () => db) + await ace.app.init() + ace.ui.switchMode('raw') + + ace.addLoader(new ListLoader([MakeFactory])) + + const command = await ace.create(MakeModel, ['user', '--factory']) + await command.exec() + + command.assertLog('green(DONE:) create app/models/user.ts') + command.assertLog('green(DONE:) create database/factories/user_factory.ts') + await assert.fileContains('app/models/user.ts', 'export default class User extends BaseModel {') + await assert.fileContains( + 'app/models/user.ts', + `import { BaseModel, column } from '@adonisjs/lucid/orm'` + ) + }) +}) diff --git a/test/commands/make_seeder.spec.ts b/test/commands/make_seeder.spec.ts new file mode 100644 index 00000000..c2f69c60 --- /dev/null +++ b/test/commands/make_seeder.spec.ts @@ -0,0 +1,37 @@ +/* + * @adonisjs/lucid + * + * (c) Harminder Virk + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import { test } from '@japa/runner' +import { AceFactory } from '@adonisjs/core/factories' +import MakeSeeder from '../../commands/make_seeder.js' + +test.group('MakeSeeder', (group) => { + group.each.teardown(async () => { + delete process.env.ADONIS_ACE_CWD + }) + + test('make a seeder', async ({ fs, assert }) => { + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.ui.switchMode('raw') + + const command = await ace.create(MakeSeeder, ['user']) + await command.exec() + + command.assertLog('green(DONE:) create database/seeders/user_seeder.ts') + await assert.fileContains( + 'database/seeders/user_seeder.ts', + `import { BaseSeeder } from '@adonisjs/lucid/seeders'` + ) + await assert.fileContains( + 'database/seeders/user_seeder.ts', + `export default class extends BaseSeeder` + ) + }) +}) diff --git a/test/commands/migration/fresh.spec.ts b/test/commands/migration/fresh.spec.ts index 8c9cd31b..67d0e6cb 100644 --- a/test/commands/migration/fresh.spec.ts +++ b/test/commands/migration/fresh.spec.ts @@ -7,48 +7,33 @@ * file that was distributed with this source code. */ -/// - import 'reflect-metadata' import { test } from '@japa/runner' -import Migrate from '../../../commands/Migration/Run' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import DbSeed from '../../../commands/DbSeed' -import DbWipe from '../../../commands/DbWipe' -import { Migrator } from '../../../src/Migrator' -import Fresh from '../../../commands/Migration/Fresh' -import { fs, setup, cleanup, getDb, setupApplication } from '../../../test-helpers' +import { AceFactory } from '@adonisjs/core/factories' -let app: ApplicationContract -let db: ReturnType +import Migrate from '../../../commands/migration/run.js' +import Fresh from '../../../commands/migration/fresh.js' +import { setup, cleanup, getDb } from '../../../test-helpers/index.js' +import { ListLoader } from '@adonisjs/core/ace' +import DbWipe from '../../../commands/db_wipe.js' +import DbSeed from '../../../commands/db_seed.js' test.group('migrate:fresh', (group) => { group.each.setup(async () => { - app = await setupApplication() - return () => fs.cleanup() - }) - - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) - app.container.bind('Adonis/Lucid/Migrator', () => Migrator) await setup() return async () => { await cleanup() await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users']) - await db.manager.closeAll() } }) - test('migration:fresh should drop all tables and run migrations', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('migration:fresh should drop all tables and run migrations', async ({ fs, assert }) => { + await fs.create( + 'database/migrations/fresh_cmd_users.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -58,24 +43,40 @@ test.group('migrate:fresh', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate, Fresh, DbWipe]) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + ace.addLoader(new ListLoader([DbWipe, DbSeed, Migrate])) - await kernel.exec('migration:run', []) - await kernel.exec('migration:fresh', []) + const migrate = await ace.create(Migrate, []) + await migrate.exec() const migrated = await db.connection().from('adonis_schema').select('*') const hasUsersTable = await db.connection().schema.hasTable('schema_users') assert.lengthOf(migrated, 1) assert.isTrue(hasUsersTable) - assert.equal(migrated[0].name, 'database/migrations/users') + assert.equal(migrated[0].name, 'database/migrations/fresh_cmd_users') assert.equal(migrated[0].batch, 1) + + const fresh = await ace.create(Fresh, []) + await fresh.exec() + + const migrated1 = await db.connection().from('adonis_schema').select('*') + const hasUsersTable1 = await db.connection().schema.hasTable('schema_users') + + assert.lengthOf(migrated1, 1) + assert.isTrue(hasUsersTable1) + assert.equal(migrated1[0].name, 'database/migrations/fresh_cmd_users') + assert.equal(migrated1[0].batch, 1) }) - test('migration:fresh --seed should run seeders', async ({ assert }) => { - await fs.add( - 'database/seeders/user.ts', + test('migration:fresh --seed should run seeders', async ({ fs, assert }) => { + await fs.create( + 'database/seeders/fresh_cmd_user.ts', `export default class UserSeeder { public async run () { process.env.EXEC_USER_SEEDER = 'true' @@ -83,11 +84,11 @@ test.group('migrate:fresh', (group) => { }` ) - await fs.add( - 'database/migrations/users.ts', + await fs.create( + 'database/migrations/fresh_cmd_users_v1.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -97,11 +98,19 @@ test.group('migrate:fresh', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate, Fresh, DbSeed, DbWipe]) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + ace.addLoader(new ListLoader([DbWipe, DbSeed, Migrate])) + + const migrate = await ace.create(Migrate, []) + await migrate.exec() - await kernel.exec('migration:run', []) - await kernel.exec('migration:fresh', ['--seed']) + const fresh = await ace.create(Fresh, ['--seed']) + await fresh.exec() assert.equal(process.env.EXEC_USER_SEEDER, 'true') delete process.env.EXEC_USER_SEEDER diff --git a/test/commands/migration/refresh.spec.ts b/test/commands/migration/refresh.spec.ts index afdc82dd..5ffde438 100644 --- a/test/commands/migration/refresh.spec.ts +++ b/test/commands/migration/refresh.spec.ts @@ -7,48 +7,32 @@ * file that was distributed with this source code. */ -/// - import 'reflect-metadata' import { test } from '@japa/runner' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import DbSeed from '../../../commands/DbSeed' -import { Migrator } from '../../../src/Migrator' -import Reset from '../../../commands/Migration/Reset' -import Migrate from '../../../commands/Migration/Run' -import Refresh from '../../../commands/Migration/Refresh' -import Rollback from '../../../commands/Migration/Rollback' -import { fs, setup, cleanup, getDb, setupApplication } from '../../../test-helpers' +import { ListLoader } from '@adonisjs/core/ace' +import { AceFactory } from '@adonisjs/core/factories' -let db: ReturnType -let app: ApplicationContract +import DbSeed from '../../../commands/db_seed.js' +import Reset from '../../../commands/migration/reset.js' +import Migrate from '../../../commands/migration/run.js' +import Refresh from '../../../commands/migration/refresh.js' +import Rollback from '../../../commands/migration/rollback.js' +import { cleanup, getDb } from '../../../test-helpers/index.js' test.group('migration:refresh', (group) => { group.each.setup(async () => { - app = await setupApplication() - await setup() - return () => fs.cleanup() - }) - - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) - app.container.bind('Adonis/Lucid/Migrator', () => Migrator) return async () => { await cleanup() await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users', 'schema_accounts']) - await db.manager.closeAll(true) } }) - test('rollback to batch 0 and migrate database', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('rollback to batch 0 and migrate database', async ({ fs, assert }) => { + await fs.create( + 'database/migrations/refresh_cmd_users.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -62,11 +46,11 @@ test.group('migration:refresh', (group) => { ` ) - await fs.add( - 'database/migrations/posts.ts', + await fs.create( + 'database/migrations/refresh_cmd_posts.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class Account extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class Account extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -80,11 +64,19 @@ test.group('migration:refresh', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate, Rollback, Reset, Refresh]) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + ace.addLoader(new ListLoader([Reset, DbSeed, Migrate, Rollback])) + + const migrate = await ace.create(Migrate, []) + await migrate.exec() - await kernel.exec('migration:run', []) - await kernel.exec('migration:refresh', []) + const refresh = await ace.create(Refresh, []) + await refresh.exec() const migrated = await db.connection().from('adonis_schema').select('*') const hasUsersTable = await db.connection().schema.hasTable('schema_users') @@ -95,9 +87,9 @@ test.group('migration:refresh', (group) => { assert.isTrue(hasAccountsTable) }) - test('run seeders when --seed flag is passed', async ({ assert }) => { - await fs.add( - 'database/seeders/user.ts', + test('run seeders when --seed flag is passed', async ({ fs, assert }) => { + await fs.create( + 'database/seeders/refres_cmd_user.ts', `export default class UserSeeder { public async run () { process.env.EXEC_USER_SEEDER = 'true' @@ -105,11 +97,11 @@ test.group('migration:refresh', (group) => { }` ) - await fs.add( - 'database/migrations/users.ts', + await fs.create( + 'database/migrations/refres_cmd_users_v1.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -123,11 +115,11 @@ test.group('migration:refresh', (group) => { ` ) - await fs.add( + await fs.create( 'database/migrations/posts.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class Account extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class Account extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -141,11 +133,19 @@ test.group('migration:refresh', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate, Rollback, Reset, Refresh, DbSeed]) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + ace.addLoader(new ListLoader([Reset, DbSeed, Migrate, Rollback])) + + const migrate = await ace.create(Migrate, []) + await migrate.exec() - await kernel.exec('migration:run', []) - await kernel.exec('migration:refresh', ['--seed']) + const refresh = await ace.create(Refresh, ['--seed']) + await refresh.exec() assert.equal(process.env.EXEC_USER_SEEDER, 'true') delete process.env.EXEC_USER_SEEDER diff --git a/test/commands/migration/reset.spec.ts b/test/commands/migration/reset.spec.ts index fe405006..ee9f6e97 100644 --- a/test/commands/migration/reset.spec.ts +++ b/test/commands/migration/reset.spec.ts @@ -7,46 +7,32 @@ * file that was distributed with this source code. */ -/// - import 'reflect-metadata' import { test } from '@japa/runner' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import { Migrator } from '../../../src/Migrator' -import Reset from '../../../commands/Migration/Reset' -import Migrate from '../../../commands/Migration/Run' -import Rollback from '../../../commands/Migration/Rollback' -import { fs, setup, cleanup, getDb, setupApplication } from '../../../test-helpers' +import { ListLoader } from '@adonisjs/core/ace' +import { AceFactory } from '@adonisjs/core/factories' -let db: ReturnType -let app: ApplicationContract +import Reset from '../../../commands/migration/reset.js' +import Migrate from '../../../commands/migration/run.js' +import Rollback from '../../../commands/migration/rollback.js' +import { setup, cleanup, getDb } from '../../../test-helpers/index.js' test.group('migration:reset', (group) => { group.each.setup(async () => { - app = await setupApplication() await setup() - return () => fs.cleanup() - }) - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) - app.container.bind('Adonis/Lucid/Migrator', () => Migrator) return async () => { await cleanup() await cleanup(['adonis_schema', 'adonis_schema_versions', 'schema_users', 'schema_accounts']) - await db.manager.closeAll(true) } }) - test('rollback to batch 0', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('rollback to batch 0', async ({ fs, assert }) => { + await fs.create( + 'database/migrations/reset_cmd_users.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -60,11 +46,11 @@ test.group('migration:reset', (group) => { ` ) - await fs.add( - 'database/migrations/posts.ts', + await fs.create( + 'database/migrations/reset_cmd_posts.ts', ` import { Schema } from '../../../../src/Schema' - module.exports = class Account extends Schema { + export default class Account extends Schema { public async up () { this.schema.createTable('schema_accounts', (table) => { table.increments() @@ -78,11 +64,19 @@ test.group('migration:reset', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate, Rollback, Reset]) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + ace.addLoader(new ListLoader([Rollback])) + + const migrate = await ace.create(Migrate, []) + await migrate.exec() - await kernel.exec('migration:run', []) - await kernel.exec('migration:reset', []) + const refresh = await ace.create(Reset, []) + await refresh.exec() const migrated = await db.connection().from('adonis_schema').select('*') const hasUsersTable = await db.connection().schema.hasTable('schema_users') diff --git a/test/commands/migration/run.spec.ts b/test/commands/migration/run.spec.ts index e2b9ef75..c46ed5d2 100644 --- a/test/commands/migration/run.spec.ts +++ b/test/commands/migration/run.spec.ts @@ -7,51 +7,34 @@ * file that was distributed with this source code. */ -/// - import 'reflect-metadata' -import { join } from 'path' import { test } from '@japa/runner' -import { Kernel } from '@adonisjs/core/build/standalone' -import { ApplicationContract } from '@ioc:Adonis/Core/Application' - -import { Migrator } from '../../../src/Migrator' -import Migrate from '../../../commands/Migration/Run' -import { fs, setup, cleanup, getDb, setupApplication } from '../../../test-helpers' +import { AceFactory } from '@adonisjs/core/factories' -let db: ReturnType -let app: ApplicationContract +import Migrate from '../../../commands/migration/run.js' +import { setup, cleanup as cleanupTables, getDb } from '../../../test-helpers/index.js' test.group('migration:run', (group) => { group.each.setup(async () => { - app = await setupApplication() await setup() - return () => fs.cleanup() - }) - - group.each.setup(async () => { - db = getDb(app) - app.container.bind('Adonis/Lucid/Database', () => db) - app.container.bind('Adonis/Lucid/Migrator', () => Migrator) return async () => { - await cleanup() - await cleanup([ + await cleanupTables() + await cleanupTables([ 'adonis_schema', 'adonis_schema_versions', 'schema_users', 'schema_accounts', 'schema_clients', ]) - await db.manager.closeAll(true) } }) - test('run migrations from default directory', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('run migrations from default directory', async ({ fs, assert }) => { + await fs.create( + 'database/migrations/run_cmd_users.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -61,36 +44,44 @@ test.group('migration:run', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate]) - await kernel.exec('migration:run', []) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + const migrate = await ace.create(Migrate, []) + await migrate.exec() const migrated = await db.connection().from('adonis_schema').select('*') const hasUsersTable = await db.connection().schema.hasTable('schema_users') assert.lengthOf(migrated, 1) assert.isTrue(hasUsersTable) - assert.equal(migrated[0].name, 'database/migrations/users') + assert.equal(migrated[0].name, 'database/migrations/run_cmd_users') assert.equal(migrated[0].batch, 1) }) - test('skip migrations when already up to date', async ({ assert }) => { - await fs.fsExtra.ensureDir(join(fs.basePath, 'database/migrations')) + test('skip migrations when already up to date', async ({ fs, assert }) => { + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate]) - await kernel.exec('migration:run', []) + const migrate = await ace.create(Migrate, []) + await migrate.exec() const migrated = await db.connection().from('adonis_schema').select('*') assert.lengthOf(migrated, 0) }) - test('do not execute migrations in dry-run', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('do not execute migrations in dry-run', async ({ fs, assert }) => { + await fs.create( + 'database/migrations/run_cmd_users_v1.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -100,23 +91,31 @@ test.group('migration:run', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate]) - await kernel.exec('migration:run', ['--dry-run']) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + const migrate = await ace.create(Migrate, ['--dry-run']) + await migrate.exec() const migrated = await db.connection().from('adonis_schema').select('*') assert.lengthOf(migrated, 0) }) - test('do not run migrations in production', async ({ assert }) => { + test('do not run migrations in production', async ({ fs, assert, cleanup }) => { assert.plan(1) - app.nodeEnvironment = 'production' + process.env.NODE_ENV = 'production' + cleanup(() => { + delete process.env.NODE_ENV + }) - await fs.add( - 'database/migrations/users.ts', + await fs.create( + 'database/migrations/run_cmd_users_v2.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -126,21 +125,43 @@ test.group('migration:run', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate]).interactive(false) - await kernel.exec('migration:run', []) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { + importer: (filePath) => { + return import(filePath) + }, + }) + + await ace.app.init() + await ace.app.boot() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + const migrate = await ace.create(Migrate, []) + migrate.prompt + .trap('You are in production environment. Want to continue running migrations?') + .reject() + + await migrate.exec() assert.isFalse(await db.connection().schema.hasTable('adonis_schema')) }) - test('run migrations in production when --force flag is passed', async ({ assert }) => { - app.nodeEnvironment = 'production' + test('run migrations in production when --force flag is passed', async ({ + fs, + assert, + cleanup, + }) => { + process.env.NODE_ENV = 'production' + cleanup(() => { + delete process.env.NODE_ENV + }) - await fs.add( - 'database/migrations/users.ts', + await fs.create( + 'database/migrations/run_cmd_users_v3.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -150,25 +171,36 @@ test.group('migration:run', (group) => { ` ) - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate]).interactive(false) - await kernel.exec('migration:run', ['--force']) + const db = getDb() + + const ace = await new AceFactory().make(fs.baseUrl, { + importer: (filePath) => { + return import(filePath) + }, + }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') + + const migrate = await ace.create(Migrate, ['--force']) + await migrate.exec() const migrated = await db.connection().from('adonis_schema').select('*') const hasUsersTable = await db.connection().schema.hasTable('schema_users') assert.lengthOf(migrated, 1) assert.isTrue(hasUsersTable) - assert.equal(migrated[0].name, 'database/migrations/users') + assert.equal(migrated[0].name, 'database/migrations/run_cmd_users_v3') assert.equal(migrated[0].batch, 1) }) - test('run migrations with compact output should display one line', async ({ assert }) => { - await fs.add( - 'database/migrations/users.ts', + test('run migrations with compact output should display one line', async ({ fs }) => { + await fs.create( + 'database/migrations/run_cmd_users_v4.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -178,11 +210,12 @@ test.group('migration:run', (group) => { ` ) - await fs.add( - 'database/migrations/clients.ts', + await fs.create( + 'database/migrations/run_cmd_clients_v4.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class Client extends Schema { + import { Schema } from '../../../../src/schema/index.js' + + export default class Client extends Schema { public async up () { this.schema.createTable('schema_clients', (table) => { table.increments() @@ -192,27 +225,27 @@ test.group('migration:run', (group) => { ` ) - process.env.CLI_UI_IS_TESTING = 'true' - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate]).interactive(false) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') - const command = await kernel.exec('migration:run', ['--compact-output']) - const logs = command.ui.testingRenderer.logs.filter( - (log) => !log.message.includes('Upgrading migrations version from') - ) + const migrate = await ace.create(Migrate, ['--compact-output']) + await migrate.exec() - assert.deepEqual(logs.length, 1) - assert.isTrue(logs[0].message.includes('❯ Executed 2 migrations')) + migrate.assertLogMatches(/grey\(❯ Executed 2 migrations/) }) test('run already migrated migrations with compact output should display one line', async ({ - assert, + fs, }) => { - await fs.add( - 'database/migrations/users.ts', + await fs.create( + 'database/migrations/run_cmd_users_v5.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class User extends Schema { + import { Schema } from '../../../../src/schema/index.js' + + export default class User extends Schema { public async up () { this.schema.createTable('schema_users', (table) => { table.increments() @@ -222,11 +255,12 @@ test.group('migration:run', (group) => { ` ) - await fs.add( - 'database/migrations/clients.ts', + await fs.create( + 'database/migrations/run_cmd_clients_v5.ts', ` - import { Schema } from '../../../../src/Schema' - module.exports = class Client extends Schema { + import { Schema } from '../../../../src/schema/index.js' + + export default class Client extends Schema { public async up () { this.schema.createTable('schema_clients', (table) => { table.increments() @@ -236,17 +270,16 @@ test.group('migration:run', (group) => { ` ) - process.env.CLI_UI_IS_TESTING = 'true' - const kernel = new Kernel(app).mockConsoleOutput() - kernel.register([Migrate]).interactive(false) + const db = getDb() + const ace = await new AceFactory().make(fs.baseUrl, { importer: () => {} }) + await ace.app.init() + ace.app.container.singleton('lucid.db', () => db) + ace.ui.switchMode('raw') - await kernel.exec('migration:run', ['--compact-output']) - const command = await kernel.exec('migration:run', ['--compact-output']) - const logs = command.ui.testingRenderer.logs.filter( - (log) => !log.message.includes('Upgrading migrations version from') - ) + const migrate = await ace.create(Migrate, ['--compact-output']) + await migrate.exec() + await migrate.exec() - assert.deepEqual(logs.length, 1) - assert.isTrue(logs[0].message.includes('❯ Already up to date')) + migrate.assertLogMatches(/grey\(❯ Already up to date/) }) }) diff --git a/test/connection/connection.spec.ts b/test/connection/connection.spec.ts index 36f06551..7d42593d 100644 --- a/test/connection/connection.spec.ts +++ b/test/connection/connection.spec.ts @@ -9,7 +9,7 @@ import { Knex } from 'knex' import { test } from '@japa/runner' -import { MysqlConfig } from '../../adonis-typings/database.js' +import { MysqlConfig } from '../../src/types/database.js' import { Connection } from '../../src/connection/index.js' import { setup, cleanup, getConfig, resetTables, logger } from '../../test-helpers/index.js' diff --git a/test/database/database.spec.ts b/test/database/database.spec.ts index acaf6fad..b3f8084f 100644 --- a/test/database/database.spec.ts +++ b/test/database/database.spec.ts @@ -9,7 +9,7 @@ import { test } from '@japa/runner' -import { Database } from '../../src/database/index.js' +import { Database } from '../../src/database/main.js' import { getConfig, setup, cleanup, logger, createEmitter } from '../../test-helpers/index.js' test.group('Database', (group) => { diff --git a/test/factory/belongs_to.spec.ts b/test/factory/belongs_to.spec.ts index 9456ea05..2b8caf34 100644 --- a/test/factory/belongs_to.spec.ts +++ b/test/factory/belongs_to.spec.ts @@ -8,9 +8,9 @@ */ import { test } from '@japa/runner' -import type { BelongsTo } from '../../adonis-typings/relations.js' +import type { BelongsTo } from '../../src/types/relations.js' -import { FactoryManager } from '../../src/factory/index.js' +import { FactoryManager } from '../../src/factories/main.js' import { column, belongsTo } from '../../src/orm/decorators/index.js' import { diff --git a/test/factory/factory_builder.spec.ts b/test/factory/factory_builder.spec.ts index c668dcd5..1ad34fc6 100644 --- a/test/factory/factory_builder.spec.ts +++ b/test/factory/factory_builder.spec.ts @@ -11,9 +11,9 @@ import { test } from '@japa/runner' import { randomUUID } from 'node:crypto' import { column } from '../../src/orm/decorators/index.js' -import { FactoryManager } from '../../src/factory/index.js' -import { FactoryContext } from '../../src/factory/factory_context.js' -import { FactoryBuilder } from '../../src/factory/factory_builder.js' +import { FactoryManager } from '../../src/factories/main.js' +import { FactoryContext } from '../../src/factories/factory_context.js' +import { FactoryBuilder } from '../../src/factories/factory_builder.js' import { setup, diff --git a/test/factory/factory_model.spec.ts b/test/factory/factory_model.spec.ts index 49558722..7a9bab6e 100644 --- a/test/factory/factory_model.spec.ts +++ b/test/factory/factory_model.spec.ts @@ -9,11 +9,11 @@ import { test } from '@japa/runner' -import { FactoryManager } from '../../src/factory/index.js' -import type { HasOne } from '../../adonis-typings/relations.js' +import { FactoryManager } from '../../src/factories/main.js' +import type { HasOne } from '../../src/types/relations.js' import { column, hasOne } from '../../src/orm/decorators/index.js' -import { FactoryModel } from '../../src/factory/factory_model.js' -import { HasOne as FactoryHasOne } from '../../src/factory/relations/has_one.js' +import { FactoryModel } from '../../src/factories/factory_model.js' +import { HasOne as FactoryHasOne } from '../../src/factories/relations/has_one.js' import { setup, diff --git a/test/factory/has_many.spec.ts b/test/factory/has_many.spec.ts index 130556f0..b604aca4 100644 --- a/test/factory/has_many.spec.ts +++ b/test/factory/has_many.spec.ts @@ -8,9 +8,9 @@ */ import { test } from '@japa/runner' -import type { HasMany } from '../../adonis-typings/relations.js' +import type { HasMany } from '../../src/types/relations.js' -import { FactoryManager } from '../../src/factory/index.js' +import { FactoryManager } from '../../src/factories/main.js' import { column, hasMany } from '../../src/orm/decorators/index.js' import { diff --git a/test/factory/has_one.spec.ts b/test/factory/has_one.spec.ts index 592498ad..74e98b8d 100644 --- a/test/factory/has_one.spec.ts +++ b/test/factory/has_one.spec.ts @@ -8,9 +8,9 @@ */ import { test } from '@japa/runner' -import type { HasOne } from '../../adonis-typings/relations.js' +import type { HasOne } from '../../src/types/relations.js' -import { FactoryManager } from '../../src/factory/index.js' +import { FactoryManager } from '../../src/factories/main.js' import { column, hasOne } from '../../src/orm/decorators/index.js' import { diff --git a/test/factory/many_to_many.spec.ts b/test/factory/many_to_many.spec.ts index d7b800c4..96646cb8 100644 --- a/test/factory/many_to_many.spec.ts +++ b/test/factory/many_to_many.spec.ts @@ -7,9 +7,9 @@ * file that was distributed with this source code. */ import { test } from '@japa/runner' -import type { ManyToMany } from '../../adonis-typings/relations.js' +import type { ManyToMany } from '../../src/types/relations.js' -import { FactoryManager } from '../../src/factory/index.js' +import { FactoryManager } from '../../src/factories/main.js' import { column, manyToMany } from '../../src/orm/decorators/index.js' import { diff --git a/test/migrations/migration_source.spec.ts b/test/migrations/migration_source.spec.ts index ce17057c..7e451bb9 100644 --- a/test/migrations/migration_source.spec.ts +++ b/test/migrations/migration_source.spec.ts @@ -11,7 +11,7 @@ import { join } from 'node:path' import { test } from '@japa/runner' import { AppFactory } from '@adonisjs/core/factories/app' -import { MigrationSource } from '../../src/migrator/migration_source.js' +import { MigrationSource } from '../../src/migration/source.js' import { setup, getDb, resetTables } from '../../test-helpers/index.js' test.group('MigrationSource', (group) => { diff --git a/test/orm/base_model.spec.ts b/test/orm/base_model.spec.ts index 809b0fcf..1b957808 100644 --- a/test/orm/base_model.spec.ts +++ b/test/orm/base_model.spec.ts @@ -13,7 +13,7 @@ import lodash from '@poppinss/utils/lodash' import { AppFactory } from '@adonisjs/core/factories/app' import { ModelQueryBuilder } from '../../src/orm/query_builder/index.js' -import type { HasOne, HasMany, BelongsTo } from '../../adonis-typings/relations.js' +import type { HasOne, HasMany, BelongsTo } from '../../src/types/relations.js' import { column, @@ -50,11 +50,11 @@ import { cleanup as cleanupTables, } from '../../test-helpers/index.js' import { ModelPaginator } from '../../src/orm/paginator/index.js' -import { QueryClientContract } from '../../adonis-typings/database.js' +import { QueryClientContract } from '../../src/types/database.js' import { SimplePaginator } from '../../src/database/paginator/simple_paginator.js' -import { InsertQueryBuilderContract } from '../../adonis-typings/querybuilder.js' +import { InsertQueryBuilderContract } from '../../src/types/querybuilder.js' import { SnakeCaseNamingStrategy } from '../../src/orm/naming_strategies/snake_case.js' -import { ModelQueryBuilderContract, LucidModel, LucidRow } from '../../adonis-typings/model.js' +import { ModelQueryBuilderContract, LucidModel, LucidRow } from '../../src/types/model.js' test.group('Base model | boot', (group) => { group.setup(async () => { diff --git a/test/orm/base_model_options.spec.ts b/test/orm/base_model_options.spec.ts index add1aad0..ca529d24 100644 --- a/test/orm/base_model_options.spec.ts +++ b/test/orm/base_model_options.spec.ts @@ -8,7 +8,7 @@ */ import { test } from '@japa/runner' -import type { HasOne } from '../../adonis-typings/relations.js' +import type { HasOne } from '../../src/types/relations.js' import { column, hasOne } from '../../src/orm/decorators/index.js' import { diff --git a/test/orm/model_belongs_to.spec.ts b/test/orm/model_belongs_to.spec.ts index 722419cb..fab36948 100644 --- a/test/orm/model_belongs_to.spec.ts +++ b/test/orm/model_belongs_to.spec.ts @@ -8,7 +8,7 @@ */ import { test } from '@japa/runner' -import type { BelongsTo } from '../../adonis-typings/relations.js' +import type { BelongsTo } from '../../src/types/relations.js' import { scope } from '../../src/orm/base_model/index.js' import { column, belongsTo } from '../../src/orm/decorators/index.js' diff --git a/test/orm/model_has_many.spec.ts b/test/orm/model_has_many.spec.ts index 83e9a113..0fa44c65 100644 --- a/test/orm/model_has_many.spec.ts +++ b/test/orm/model_has_many.spec.ts @@ -8,7 +8,7 @@ */ import { test } from '@japa/runner' -import type { HasMany } from '../../adonis-typings/relations.js' +import type { HasMany } from '../../src/types/relations.js' import { scope } from '../../src/orm/base_model/index.js' import { column, hasMany } from '../../src/orm/decorators/index.js' diff --git a/test/orm/model_has_many_through.spec.ts b/test/orm/model_has_many_through.spec.ts index 320df360..415b3f27 100644 --- a/test/orm/model_has_many_through.spec.ts +++ b/test/orm/model_has_many_through.spec.ts @@ -8,7 +8,7 @@ */ import { test } from '@japa/runner' -import type { HasManyThrough } from '../../adonis-typings/relations.js' +import type { HasManyThrough } from '../../src/types/relations.js' import { scope } from '../../src/orm/base_model/index.js' import { hasManyThrough, column } from '../../src/orm/decorators/index.js' diff --git a/test/orm/model_has_one.spec.ts b/test/orm/model_has_one.spec.ts index ea40c7a8..a4636227 100644 --- a/test/orm/model_has_one.spec.ts +++ b/test/orm/model_has_one.spec.ts @@ -8,7 +8,7 @@ */ import { test } from '@japa/runner' -import type { HasOne, BelongsTo } from '../../adonis-typings/relations.js' +import type { HasOne, BelongsTo } from '../../src/types/relations.js' import { scope } from '../../src/orm/base_model/index.js' import { column, hasOne, belongsTo } from '../../src/orm/decorators/index.js' diff --git a/test/orm/model_many_to_many.spec.ts b/test/orm/model_many_to_many.spec.ts index 62b6f278..34b0bd1f 100644 --- a/test/orm/model_many_to_many.spec.ts +++ b/test/orm/model_many_to_many.spec.ts @@ -8,7 +8,7 @@ */ import { test } from '@japa/runner' -import type { ManyToMany } from '../../adonis-typings/relations.js' +import type { ManyToMany } from '../../src/types/relations.js' import { scope } from '../../src/orm/base_model/index.js' import { column, manyToMany } from '../../src/orm/decorators/index.js' diff --git a/test/seeders/seeders_runner.spec.ts b/test/seeders/seeders_runner.spec.ts index 13f969d4..7ea13b90 100644 --- a/test/seeders/seeders_runner.spec.ts +++ b/test/seeders/seeders_runner.spec.ts @@ -10,7 +10,7 @@ import { test } from '@japa/runner' import { AppFactory } from '@adonisjs/core/factories/app' -import { SeedsRunner } from '../../src/seeders_runner/index.js' +import { SeedsRunner } from '../../src/seeders/runner.js' import { getDb, setup, cleanup as cleanupTables } from '../../test-helpers/index.js' test.group('Seeds Runner', (group) => { diff --git a/test/seeders/seeders_source.spec.ts b/test/seeders/seeders_source.spec.ts index f2f66891..fa59c343 100644 --- a/test/seeders/seeders_source.spec.ts +++ b/test/seeders/seeders_source.spec.ts @@ -11,7 +11,7 @@ import { join } from 'node:path' import { test } from '@japa/runner' import { AppFactory } from '@adonisjs/core/factories/app' -import { SeedersSource } from '../../src/seeders_runner/seeders_source.js' +import { SeedersSource } from '../../src/seeders/source.js' import { getDb, setup, cleanup } from '../../test-helpers/index.js' test.group('Seeds Source', (group) => { diff --git a/test/utils.spec.ts b/test/utils.spec.ts index 422361da..052da69e 100644 --- a/test/utils.spec.ts +++ b/test/utils.spec.ts @@ -7,10 +7,8 @@ * file that was distributed with this source code. */ -/// - import { test } from '@japa/runner' -import { syncDiff } from '../src/utils' +import { syncDiff } from '../src/utils/index.js' test.group('Utils | syncDiff', () => { test('return ids to be added', ({ assert }) => {