This commit is contained in:
Tutur33
2023-11-24 22:35:41 +01:00
parent 3c0b507a93
commit 7644b2a0f7
45165 changed files with 4803356 additions and 3 deletions
+81
View File
@@ -0,0 +1,81 @@
import { BaseCommand } from '@adonisjs/core/build/standalone';
export default class DbSeed extends BaseCommand {
static commandName: string;
static description: string;
static settings: {
loadApp: boolean;
};
private seeder;
/**
* Track if one or more seeders have failed
*/
private hasError;
/**
* Choose a custom pre-defined connection. Otherwise, we use the
* default connection
*/
connection: string;
/**
* Interactive mode allows selecting seeder files
*/
interactive: boolean;
/**
* Define a custom set of seeder files. Interactive and files together ignores
* the interactive mode.
*/
files: string[];
/**
* Display migrations result in one compact single-line output
*/
compactOutput: boolean;
/**
* Print log message to the console
*/
private printLogMessage;
/**
* Not a valid connection
*/
private printNotAValidConnection;
/**
* Print log that the selected seeder file is invalid
*/
private printNotAValidFile;
/**
* Get files cherry picked using either "--interactive" or the
* "--files" flag
*/
private getCherryPickedFiles;
/**
* Instantiate seeders runner
*/
private instantiateSeeder;
/**
* Execute selected seeders
*/
private executedSeeders;
/**
* Print Single-line output when `compact-output` is enabled
*/
private logCompactFinalStatus;
/**
* Run as a subcommand. Never close database connection or exit
* process here
*/
private runAsSubCommand;
/**
* Branching out, so that if required we can implement
* "runAsMain" separately from "runAsSubCommand".
*
* For now, they both are the same
*/
private runAsMain;
/**
* Handle command
*/
run(): Promise<void>;
/**
* Lifecycle method invoked by ace after the "run"
* method.
*/
completed(): Promise<void>;
}
+328
View File
@@ -0,0 +1,328 @@
"use strict";
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const slash_1 = __importDefault(require("slash"));
const path_1 = require("path");
const standalone_1 = require("@adonisjs/core/build/standalone");
class DbSeed extends standalone_1.BaseCommand {
constructor() {
super(...arguments);
Object.defineProperty(this, "seeder", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Track if one or more seeders have failed
*/
Object.defineProperty(this, "hasError", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
/**
* Choose a custom pre-defined connection. Otherwise, we use the
* default connection
*/
Object.defineProperty(this, "connection", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Interactive mode allows selecting seeder files
*/
Object.defineProperty(this, "interactive", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Define a custom set of seeder files. Interactive and files together ignores
* the interactive mode.
*/
Object.defineProperty(this, "files", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
/**
* Display migrations result in one compact single-line output
*/
Object.defineProperty(this, "compactOutput", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
}
/**
* Print log message to the console
*/
printLogMessage(file) {
const colors = this['colors'];
let color = 'gray';
let message = '';
let prefix = '';
switch (file.status) {
case 'pending':
message = 'pending ';
color = 'gray';
break;
case 'failed':
message = 'error ';
prefix = file.error.message;
color = 'red';
break;
case 'ignored':
message = 'ignored ';
prefix = 'Enabled only in development environment';
color = 'dim';
break;
case 'completed':
message = 'completed';
color = 'green';
break;
}
console.log(`${colors[color]('')} ${colors[color](message)} ${file.file.name}`);
if (prefix) {
console.log(` ${colors[color](prefix)}`);
}
}
/**
* Not a valid connection
*/
printNotAValidConnection(connection) {
this.logger.error(`"${connection}" is not a valid connection name. Double check "config/database" file`);
}
/**
* Print log that the selected seeder file is invalid
*/
printNotAValidFile(fileName) {
this.printLogMessage({
file: {
name: fileName,
absPath: fileName,
getSource: () => { },
},
status: 'failed',
error: new Error('Invalid file path. Pass relative path from the application root'),
});
}
/**
* Get files cherry picked using either "--interactive" or the
* "--files" flag
*/
async getCherryPickedFiles(seedersFiles) {
if (this.files.length) {
return this.files.map((file) => {
const fileExt = (0, path_1.extname)(file);
return (fileExt ? file.replace(fileExt, '') : file).replace(/^\.\/|^\.\\\\/, '');
});
}
else if (this.interactive) {
return await this.prompt.multiple('Select files to run', seedersFiles.map((file) => {
return { name: file.name };
}));
}
return seedersFiles.map((file) => file.name);
}
/**
* Instantiate seeders runner
*/
async instantiateSeeder() {
const db = this.application.container.use('Adonis/Lucid/Database');
const { SeedsRunner } = await Promise.resolve().then(() => __importStar(require('../src/SeedsRunner')));
this.seeder = new SeedsRunner(db, this.application, this.connection);
}
/**
* Execute selected seeders
*/
async executedSeeders(selectedSeederFiles, files) {
const seedersResults = [];
for (let fileName of selectedSeederFiles) {
const sourceFile = files.find(({ name }) => (0, slash_1.default)(fileName) === (0, slash_1.default)(name));
if (!sourceFile) {
this.printNotAValidFile(fileName);
this.hasError = true;
return;
}
const response = await this.seeder.run(sourceFile);
if (response.status === 'failed') {
this.hasError = true;
}
if (!this.compactOutput) {
this.printLogMessage(response);
}
seedersResults.push(response);
}
return seedersResults;
}
/**
* Print Single-line output when `compact-output` is enabled
*/
logCompactFinalStatus(seedersResults) {
const countByStatus = seedersResults.reduce((acc, value) => {
acc[value.status] = acc[value.status] + 1;
return acc;
}, { completed: 0, failed: 0, ignored: 0, pending: 0 });
let message = ` Executed ${countByStatus.completed} seeders`;
if (countByStatus.failed) {
message += `, ${countByStatus.failed} failed`;
}
if (countByStatus.ignored) {
message += `, ${countByStatus.ignored} ignored`;
}
const color = countByStatus.failed ? 'red' : 'grey';
this.logger.log(this.colors[color](message));
if (countByStatus.failed > 0) {
const erroredSeeder = seedersResults.find((seeder) => seeder.status === 'failed');
const seederName = this.colors.grey(erroredSeeder.file.name + ':');
const error = this.colors.red(erroredSeeder.error.message);
this.logger.log(`${seederName} ${error}\n`);
}
}
/**
* Run as a subcommand. Never close database connection or exit
* process here
*/
async runAsSubCommand() {
const db = this.application.container.use('Adonis/Lucid/Database');
this.connection = this.connection || db.primaryConnectionName;
/**
* Invalid database connection
*/
if (!db.manager.has(this.connection)) {
this.printNotAValidConnection(this.connection);
this.exitCode = 1;
return;
}
/**
* Cannot use --files and --interactive together
*/
if (this.files && this.interactive) {
this.logger.warning('Cannot use "--interactive" and "--files" together. Ignoring "--interactive"');
}
await this.instantiateSeeder();
const files = await this.seeder.getList();
const cherryPickedFiles = await this.getCherryPickedFiles(files);
const result = await this.executedSeeders(cherryPickedFiles, files);
if (this.compactOutput && result) {
this.logCompactFinalStatus(result);
}
this.exitCode = this.hasError ? 1 : 0;
}
/**
* Branching out, so that if required we can implement
* "runAsMain" separately from "runAsSubCommand".
*
* For now, they both are the same
*/
async runAsMain() {
await this.runAsSubCommand();
}
/**
* Handle command
*/
async run() {
if (this.isMain) {
await this.runAsMain();
}
else {
await this.runAsSubCommand();
}
}
/**
* Lifecycle method invoked by ace after the "run"
* method.
*/
async completed() {
if (this.seeder && this.isMain) {
await this.seeder.close();
}
}
}
Object.defineProperty(DbSeed, "commandName", {
enumerable: true,
configurable: true,
writable: true,
value: 'db:seed'
});
Object.defineProperty(DbSeed, "description", {
enumerable: true,
configurable: true,
writable: true,
value: 'Execute database seeders'
});
Object.defineProperty(DbSeed, "settings", {
enumerable: true,
configurable: true,
writable: true,
value: {
loadApp: true,
}
});
__decorate([
standalone_1.flags.string({ description: 'Define a custom database connection for the seeders', alias: 'c' }),
__metadata("design:type", String)
], DbSeed.prototype, "connection", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Run seeders in interactive mode', alias: 'i' }),
__metadata("design:type", Boolean)
], DbSeed.prototype, "interactive", void 0);
__decorate([
standalone_1.flags.array({ description: 'Define a custom set of seeders files names to run', alias: 'f' }),
__metadata("design:type", Array)
], DbSeed.prototype, "files", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'A compact single-line output' }),
__metadata("design:type", Boolean)
], DbSeed.prototype, "compactOutput", void 0);
exports.default = DbSeed;
+50
View File
@@ -0,0 +1,50 @@
import { BaseCommand } from '@adonisjs/core/build/standalone';
export default class DbTruncate extends BaseCommand {
static commandName: string;
static description: string;
static settings: {
loadApp: boolean;
};
/**
* Choose a custom pre-defined connection. Otherwise, we use the
* default connection
*/
connection: string;
/**
* Force command execution in production
*/
force: boolean;
/**
* Not a valid connection
*/
private printNotAValidConnection;
/**
* Prompts to take consent when truncating the database in production
*/
private takeProductionConstent;
/**
* Truncate all tables except adonis migrations table
*/
private performTruncate;
/**
* Run as a subcommand. Never close database connections or exit
* process inside this method
*/
private runAsSubCommand;
/**
* Branching out, so that if required we can implement
* "runAsMain" separately from "runAsSubCommand".
*
* For now, they both are the same
*/
private runAsMain;
/**
* Handle command
*/
run(): Promise<void>;
/**
* Lifecycle method invoked by ace after the "run"
* method.
*/
completed(): Promise<void>;
}
+167
View File
@@ -0,0 +1,167 @@
"use strict";
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const standalone_1 = require("@adonisjs/core/build/standalone");
class DbTruncate extends standalone_1.BaseCommand {
constructor() {
super(...arguments);
/**
* Choose a custom pre-defined connection. Otherwise, we use the
* default connection
*/
Object.defineProperty(this, "connection", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Force command execution in production
*/
Object.defineProperty(this, "force", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
/**
* Not a valid connection
*/
printNotAValidConnection(connection) {
this.logger.error(`"${connection}" is not a valid connection name. Double check "config/database" file`);
}
/**
* Prompts to take consent when truncating the database in production
*/
async takeProductionConstent() {
/**
* 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);
}
catch (error) {
return false;
}
}
/**
* Truncate all tables except adonis migrations table
*/
async performTruncate(client) {
let tables = await client.getAllTables(['public']);
tables = tables.filter((table) => !['adonis_schema', 'adonis_schema_versions'].includes(table));
await Promise.all(tables.map((table) => client.truncate(table, true)));
this.logger.success('Truncated tables successfully');
}
/**
* Run as a subcommand. Never close database connections or exit
* process inside this method
*/
async runAsSubCommand() {
const db = this.application.container.use('Adonis/Lucid/Database');
this.connection = this.connection || db.primaryConnectionName;
const connection = db.connection(this.connection || db.primaryConnectionName);
/**
* Continue with clearing the database when not in production
* or force flag is passed
*/
let continueTruncate = !this.application.inProduction || this.force;
if (!continueTruncate) {
continueTruncate = await this.takeProductionConstent();
}
/**
* Do not continue when in prod and the prompt was cancelled
*/
if (!continueTruncate) {
return;
}
/**
* Invalid database connection
*/
if (!db.manager.has(this.connection)) {
this.printNotAValidConnection(this.connection);
this.exitCode = 1;
return;
}
await this.performTruncate(connection);
}
/**
* Branching out, so that if required we can implement
* "runAsMain" separately from "runAsSubCommand".
*
* For now, they both are the same
*/
async runAsMain() {
await this.runAsSubCommand();
}
/**
* Handle command
*/
async run() {
if (this.isMain) {
await this.runAsMain();
}
else {
await this.runAsSubCommand();
}
}
/**
* Lifecycle method invoked by ace after the "run"
* method.
*/
async completed() {
if (this.isMain) {
await this.application.container.use('Adonis/Lucid/Database').manager.closeAll(true);
}
}
}
Object.defineProperty(DbTruncate, "commandName", {
enumerable: true,
configurable: true,
writable: true,
value: 'db:truncate'
});
Object.defineProperty(DbTruncate, "description", {
enumerable: true,
configurable: true,
writable: true,
value: 'Truncate all tables in database'
});
Object.defineProperty(DbTruncate, "settings", {
enumerable: true,
configurable: true,
writable: true,
value: {
loadApp: true,
}
});
__decorate([
standalone_1.flags.string({ description: 'Define a custom database connection', alias: 'c' }),
__metadata("design:type", String)
], DbTruncate.prototype, "connection", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Explicitly force command to run in production' }),
__metadata("design:type", Boolean)
], DbTruncate.prototype, "force", void 0);
exports.default = DbTruncate;
+66
View File
@@ -0,0 +1,66 @@
import { BaseCommand } from '@adonisjs/core/build/standalone';
export default class DbWipe extends BaseCommand {
static commandName: string;
static description: string;
static settings: {
loadApp: boolean;
};
/**
* Choose a custom pre-defined connection. Otherwise, we use the
* default connection
*/
connection: string;
/**
* Drop all views in database
*/
dropViews: boolean;
/**
* Drop all types in database
*/
dropTypes: boolean;
/**
* Force command execution in production
*/
force: boolean;
/**
* Not a valid connection
*/
private printNotAValidConnection;
/**
* Prompts to take consent when wiping the database in production
*/
private takeProductionConstent;
/**
* Drop all views (if asked for and supported)
*/
private performDropViews;
/**
* Drop all tables
*/
private performDropTables;
/**
* Drop all types (if asked for and supported)
*/
private performDropTypes;
/**
* Run as a subcommand. Never close database connections or exit
* process inside this method
*/
private runAsSubCommand;
/**
* Branching out, so that if required we can implement
* "runAsMain" separately from "runAsSubCommand".
*
* For now, they both are the same
*/
private runAsMain;
/**
* Handle command
*/
run(): Promise<void>;
/**
* Lifecycle method invoked by ace after the "run"
* method.
*/
completed(): Promise<void>;
}
+219
View File
@@ -0,0 +1,219 @@
"use strict";
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const standalone_1 = require("@adonisjs/core/build/standalone");
class DbWipe extends standalone_1.BaseCommand {
constructor() {
super(...arguments);
/**
* Choose a custom pre-defined connection. Otherwise, we use the
* default connection
*/
Object.defineProperty(this, "connection", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Drop all views in database
*/
Object.defineProperty(this, "dropViews", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Drop all types in database
*/
Object.defineProperty(this, "dropTypes", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Force command execution in production
*/
Object.defineProperty(this, "force", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
/**
* Not a valid connection
*/
printNotAValidConnection(connection) {
this.logger.error(`"${connection}" is not a valid connection name. Double check "config/database" file`);
}
/**
* Prompts to take consent when wiping the database in production
*/
async takeProductionConstent() {
/**
* 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);
}
catch (error) {
return false;
}
}
/**
* Drop all views (if asked for and supported)
*/
async performDropViews(client) {
if (!this.dropViews) {
return;
}
if (!client.dialect.supportsViews) {
this.logger.warning(`Dropping views is not supported by "${client.dialect.name}"`);
}
await client.dropAllViews();
this.logger.success('Dropped views successfully');
}
/**
* Drop all tables
*/
async performDropTables(client) {
await client.dropAllTables();
this.logger.success('Dropped tables successfully');
}
/**
* Drop all types (if asked for and supported)
*/
async performDropTypes(client) {
if (!this.dropTypes) {
return;
}
if (!client.dialect.supportsTypes) {
this.logger.warning(`Dropping types is not supported by "${client.dialect.name}"`);
}
await client.dropAllTypes();
this.logger.success('Dropped types successfully');
}
/**
* Run as a subcommand. Never close database connections or exit
* process inside this method
*/
async runAsSubCommand() {
const db = this.application.container.use('Adonis/Lucid/Database');
this.connection = this.connection || db.primaryConnectionName;
const connection = db.connection(this.connection || db.primaryConnectionName);
/**
* Continue with clearing the database when not in production
* or force flag is passed
*/
let continueWipe = !this.application.inProduction || this.force;
if (!continueWipe) {
continueWipe = await this.takeProductionConstent();
}
/**
* Do not continue when in prod and the prompt was cancelled
*/
if (!continueWipe) {
return;
}
/**
* Invalid database connection
*/
if (!db.manager.has(this.connection)) {
this.printNotAValidConnection(this.connection);
this.exitCode = 1;
return;
}
await this.performDropViews(connection);
await this.performDropTables(connection);
await this.performDropTypes(connection);
}
/**
* Branching out, so that if required we can implement
* "runAsMain" separately from "runAsSubCommand".
*
* For now, they both are the same
*/
async runAsMain() {
await this.runAsSubCommand();
}
/**
* Handle command
*/
async run() {
if (this.isMain) {
await this.runAsMain();
}
else {
await this.runAsSubCommand();
}
}
/**
* Lifecycle method invoked by ace after the "run"
* method.
*/
async completed() {
if (this.isMain) {
await this.application.container.use('Adonis/Lucid/Database').manager.closeAll(true);
}
}
}
Object.defineProperty(DbWipe, "commandName", {
enumerable: true,
configurable: true,
writable: true,
value: 'db:wipe'
});
Object.defineProperty(DbWipe, "description", {
enumerable: true,
configurable: true,
writable: true,
value: 'Drop all tables, views and types in database'
});
Object.defineProperty(DbWipe, "settings", {
enumerable: true,
configurable: true,
writable: true,
value: {
loadApp: true,
}
});
__decorate([
standalone_1.flags.string({ description: 'Define a custom database connection', alias: 'c' }),
__metadata("design:type", String)
], DbWipe.prototype, "connection", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Drop all views' }),
__metadata("design:type", Boolean)
], DbWipe.prototype, "dropViews", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Drop all custom types (Postgres only)' }),
__metadata("design:type", Boolean)
], DbWipe.prototype, "dropTypes", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Explicitly force command to run in production' }),
__metadata("design:type", Boolean)
], DbWipe.prototype, "force", void 0);
exports.default = DbWipe;
+34
View File
@@ -0,0 +1,34 @@
import { BaseCommand } from '@adonisjs/core/build/standalone';
/**
* Command to make a new Factory
*/
export default class MakeFactory extends BaseCommand {
static commandName: string;
static description: string;
/**
* Name of the model to be used in the factory
*/
model: string;
/**
* Import path to the model used in the factory
*/
modelPath: string;
exact: boolean;
/**
* Generate model import path used in the factory
*/
private generateModelImportPath;
/**
* Path to the factories directory
*/
protected getDestinationPath(): string;
/**
* Passed down to the stub template
*/
protected templateData(): {
model: string;
modelImportPath: string;
toModelName: () => (model: string, render: any) => any;
};
run(): Promise<void>;
}
+133
View File
@@ -0,0 +1,133 @@
"use strict";
/*
* @adonisjs/assembler
*
* (c) AdonisJS
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("path");
const standalone_1 = require("@adonisjs/core/build/standalone");
/**
* Command to make a new Factory
*/
class MakeFactory extends standalone_1.BaseCommand {
constructor() {
super(...arguments);
/**
* Name of the model to be used in the factory
*/
Object.defineProperty(this, "model", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Import path to the model used in the factory
*/
Object.defineProperty(this, "modelPath", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "exact", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
/**
* Generate model import path used in the factory
*/
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
*/
getDestinationPath() {
const base = this.application.rcFile.directories.database || 'database';
return (0, path_1.join)(base, 'factories');
}
/**
* Passed down to the stub template
*/
templateData() {
return {
model: this.model,
modelImportPath: this.generateModelImportPath(),
toModelName: () => {
return function (model, render) {
return render(model).split('/').pop();
};
},
};
}
async run() {
const stub = (0, path_1.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();
}
}
Object.defineProperty(MakeFactory, "commandName", {
enumerable: true,
configurable: true,
writable: true,
value: 'make:factory'
});
Object.defineProperty(MakeFactory, "description", {
enumerable: true,
configurable: true,
writable: true,
value: 'Make a new factory'
});
__decorate([
standalone_1.args.string({ description: 'The name of the model' }),
__metadata("design:type", String)
], MakeFactory.prototype, "model", void 0);
__decorate([
standalone_1.flags.string({ description: 'The path to the model' }),
__metadata("design:type", String)
], MakeFactory.prototype, "modelPath", void 0);
__decorate([
standalone_1.flags.boolean({
description: 'Create the factory with the exact name as provided',
alias: 'e',
}),
__metadata("design:type", Boolean)
], MakeFactory.prototype, "exact", void 0);
exports.default = MakeFactory;
+43
View File
@@ -0,0 +1,43 @@
import { BaseCommand } from '@adonisjs/core/build/standalone';
export default class MakeMigration extends BaseCommand {
static commandName: string;
static description: string;
static settings: {
loadApp: boolean;
};
/**
* The name of the migration file. We use this to create the migration
* file and generate the table name
*/
name: string;
/**
* Choose a custom pre-defined connection. Otherwise, we use the
* default connection
*/
connection: string;
/**
* Pre select migration directory. If this is defined, we will ignore the paths
* defined inside the config.
*/
folder: string;
/**
* Custom table name for creating a new table
*/
create: string;
/**
* Custom table name for altering an existing table
*/
table: string;
/**
* Not a valid connection
*/
private printNotAValidConnection;
/**
* Returns the directory for creating the migration file
*/
private getDirectory;
/**
* Execute command
*/
run(): Promise<void>;
}
+198
View File
@@ -0,0 +1,198 @@
"use strict";
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("path");
const helpers_1 = require("@poppinss/utils/build/helpers");
const standalone_1 = require("@adonisjs/core/build/standalone");
class MakeMigration extends standalone_1.BaseCommand {
constructor() {
super(...arguments);
/**
* The name of the migration file. We use this to create the migration
* file and generate the table name
*/
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Choose a custom pre-defined connection. Otherwise, we use the
* default connection
*/
Object.defineProperty(this, "connection", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Pre select migration directory. If this is defined, we will ignore the paths
* defined inside the config.
*/
Object.defineProperty(this, "folder", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Custom table name for creating a new table
*/
Object.defineProperty(this, "create", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Custom table name for altering an existing table
*/
Object.defineProperty(this, "table", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
/**
* Not a valid connection
*/
printNotAValidConnection(connection) {
this.logger.error(`"${connection}" is not a valid connection name. Double check "config/database" file`);
}
/**
* Returns the directory for creating the migration file
*/
async getDirectory(migrationPaths) {
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() {
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 = (0, path_1.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, render) {
const migrationClassName = helpers_1.string.camelCase(tableName || render(filename).replace(prefix, ''));
return `${migrationClassName.charAt(0).toUpperCase()}${migrationClassName.slice(1)}`;
};
},
toTableName() {
return function (filename, render) {
return tableName || helpers_1.string.snakeCase(render(filename).replace(prefix, ''));
};
},
});
await this.generator.run();
}
}
Object.defineProperty(MakeMigration, "commandName", {
enumerable: true,
configurable: true,
writable: true,
value: 'make:migration'
});
Object.defineProperty(MakeMigration, "description", {
enumerable: true,
configurable: true,
writable: true,
value: 'Make a new migration file'
});
Object.defineProperty(MakeMigration, "settings", {
enumerable: true,
configurable: true,
writable: true,
value: {
loadApp: true,
}
});
__decorate([
standalone_1.args.string({ description: 'Name of the migration file' }),
__metadata("design:type", String)
], MakeMigration.prototype, "name", void 0);
__decorate([
standalone_1.flags.string({
description: 'The connection flag is used to lookup the directory for the migration file',
}),
__metadata("design:type", String)
], MakeMigration.prototype, "connection", void 0);
__decorate([
standalone_1.flags.string({ description: 'Pre-select a migration directory' }),
__metadata("design:type", String)
], MakeMigration.prototype, "folder", void 0);
__decorate([
standalone_1.flags.string({ description: 'Define the table name for creating a new table' }),
__metadata("design:type", String)
], MakeMigration.prototype, "create", void 0);
__decorate([
standalone_1.flags.string({ description: 'Define the table name for altering an existing table' }),
__metadata("design:type", String)
], MakeMigration.prototype, "table", void 0);
exports.default = MakeMigration;
+40
View File
@@ -0,0 +1,40 @@
import { BaseCommand } from '@adonisjs/core/build/standalone';
export default class MakeModel extends BaseCommand {
static commandName: string;
static description: string;
static settings: {
loadApp: boolean;
};
/**
* The name of the model file.
*/
name: string;
/**
* Defines if we generate the migration for the model.
*/
migration: boolean;
/**
* Defines if we generate the controller for the model.
*/
controller: boolean;
/**
* Defines if we generate the factory for the model.
*/
factory: boolean;
/**
* Run migrations
*/
private runMakeMigration;
/**
* Make controller
*/
private runMakeController;
/**
* Make factory
*/
private runMakeFactory;
/**
* Execute command
*/
run(): Promise<void>;
}
+164
View File
@@ -0,0 +1,164 @@
"use strict";
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("path");
const standalone_1 = require("@adonisjs/core/build/standalone");
class MakeModel extends standalone_1.BaseCommand {
constructor() {
super(...arguments);
/**
* The name of the model file.
*/
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Defines if we generate the migration for the model.
*/
Object.defineProperty(this, "migration", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Defines if we generate the controller for the model.
*/
Object.defineProperty(this, "controller", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Defines if we generate the factory for the model.
*/
Object.defineProperty(this, "factory", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
/**
* Run migrations
*/
async runMakeMigration() {
if (!this.migration) {
return;
}
const makeMigration = await this.kernel.exec('make:migration', [this.name]);
this.exitCode = makeMigration.exitCode;
this.error = makeMigration.error;
}
/**
* Make controller
*/
async runMakeController() {
if (!this.controller) {
return;
}
const makeController = await this.kernel.exec('make:controller', [this.name]);
this.exitCode = makeController.exitCode;
this.error = makeController.error;
}
/**
* Make factory
*/
async runMakeFactory() {
if (!this.factory) {
return;
}
const makeFactory = await this.kernel.exec('make:factory', [this.name]);
this.exitCode = makeFactory.exitCode;
this.error = makeFactory.error;
}
/**
* Execute command
*/
async run() {
const stub = (0, path_1.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();
await this.runMakeMigration();
if (this.exitCode) {
return;
}
await this.runMakeController();
await this.runMakeFactory();
}
}
Object.defineProperty(MakeModel, "commandName", {
enumerable: true,
configurable: true,
writable: true,
value: 'make:model'
});
Object.defineProperty(MakeModel, "description", {
enumerable: true,
configurable: true,
writable: true,
value: 'Make a new Lucid model'
});
Object.defineProperty(MakeModel, "settings", {
enumerable: true,
configurable: true,
writable: true,
value: {
loadApp: true,
}
});
__decorate([
standalone_1.args.string({ description: 'Name of the model class' }),
__metadata("design:type", String)
], MakeModel.prototype, "name", void 0);
__decorate([
standalone_1.flags.boolean({
name: 'migration',
alias: 'm',
description: 'Generate the migration for the model',
}),
__metadata("design:type", Boolean)
], MakeModel.prototype, "migration", void 0);
__decorate([
standalone_1.flags.boolean({
name: 'controller',
alias: 'c',
description: 'Generate the controller for the model',
}),
__metadata("design:type", Boolean)
], MakeModel.prototype, "controller", void 0);
__decorate([
standalone_1.flags.boolean({
name: 'factory',
alias: 'f',
description: 'Generate a factory for the model',
}),
__metadata("design:type", Boolean)
], MakeModel.prototype, "factory", void 0);
exports.default = MakeModel;
+13
View File
@@ -0,0 +1,13 @@
import { BaseCommand } from '@adonisjs/core/build/standalone';
export default class MakeSeeder extends BaseCommand {
static commandName: string;
static description: string;
/**
* The name of the seeder file.
*/
name: string;
/**
* Execute command
*/
run(): Promise<void>;
}
+66
View File
@@ -0,0 +1,66 @@
"use strict";
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("path");
const standalone_1 = require("@adonisjs/core/build/standalone");
class MakeSeeder extends standalone_1.BaseCommand {
constructor() {
super(...arguments);
/**
* The name of the seeder file.
*/
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
/**
* Execute command
*/
async run() {
const stub = (0, path_1.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();
}
}
Object.defineProperty(MakeSeeder, "commandName", {
enumerable: true,
configurable: true,
writable: true,
value: 'make:seeder'
});
Object.defineProperty(MakeSeeder, "description", {
enumerable: true,
configurable: true,
writable: true,
value: 'Make a new Seeder file'
});
__decorate([
standalone_1.args.string({ description: 'Name of the seeder class' }),
__metadata("design:type", String)
], MakeSeeder.prototype, "name", void 0);
exports.default = MakeSeeder;
+39
View File
@@ -0,0 +1,39 @@
import { BaseCommand } from '@adonisjs/core/build/standalone';
import { MigratedFileNode, MigratorContract } from '@ioc:Adonis/Lucid/Migrator';
/**
* Base class to execute migrations and print logs
*/
export default abstract class MigrationsBase extends BaseCommand {
/**
* Should print one-liner compact output
*/
protected compactOutput: boolean;
/**
* Not a valid connection
*/
protected printNotAValidConnection(connection: string): void;
/**
* Prompts to take consent for running migrations in production
*/
protected takeProductionConstent(): Promise<boolean>;
/**
* Returns beautified log message string
*/
protected printLogMessage(file: MigratedFileNode, direction: 'down' | 'up'): void;
/**
* Pretty print sql queries of a file
*/
private prettyPrintSql;
/**
* Log final status with verbose output
*/
private logVerboseFinalStatus;
/**
* Log final status with compact output
*/
private logCompactFinalStatus;
/**
* Runs the migrations using the migrator
*/
protected runMigrations(migrator: MigratorContract, connectionName: string): Promise<void>;
}
+214
View File
@@ -0,0 +1,214 @@
"use strict";
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const pretty_hrtime_1 = __importDefault(require("pretty-hrtime"));
const standalone_1 = require("@adonisjs/core/build/standalone");
const utils_1 = require("../../src/utils");
const prettyPrint_1 = require("../../src/Helpers/prettyPrint");
/**
* Base class to execute migrations and print logs
*/
class MigrationsBase extends standalone_1.BaseCommand {
constructor() {
super(...arguments);
/**
* Should print one-liner compact output
*/
Object.defineProperty(this, "compactOutput", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
}
/**
* Not a valid connection
*/
printNotAValidConnection(connection) {
this.logger.error(`"${connection}" is not a valid connection name. Double check "config/database" file`);
}
/**
* Prompts to take consent for running migrations in production
*/
async takeProductionConstent() {
/**
* 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);
}
catch (error) {
return false;
}
}
/**
* Returns beautified log message string
*/
printLogMessage(file, direction) {
const color = file.status === 'pending' ? 'gray' : file.status === 'completed' ? 'green' : 'red';
const arrow = this.colors[color]('');
const message = file.status === 'pending'
? direction === 'up'
? 'migrating'
: 'reverting'
: file.status === 'completed'
? direction === 'up'
? 'migrated'
: 'reverted'
: 'error';
this.logger.logUpdate(`${arrow} ${this.colors[color](message)} ${file.file.name}`);
}
/**
* Pretty print sql queries of a file
*/
prettyPrintSql(file, connectionName) {
console.log(this.logger.colors.gray(`------------- ${file.file.name} -------------`));
console.log();
file.queries.map((sql) => {
(0, prettyPrint_1.prettyPrint)({
connection: connectionName,
sql: sql,
ddl: true,
method: (0, utils_1.getDDLMethod)(sql),
bindings: [],
});
console.log();
});
console.log(this.logger.colors.gray('------------- END -------------'));
}
/**
* Log final status with verbose output
*/
logVerboseFinalStatus(migrator, duration) {
switch (migrator.status) {
case 'completed':
const completionMessage = migrator.direction === 'up' ? 'Migrated in' : 'Reverted in';
console.log(`\n${completionMessage} ${this.colors.cyan((0, pretty_hrtime_1.default)(duration))}`);
break;
case 'skipped':
const message = migrator.direction === 'up' ? 'Already up to date' : 'Already at latest batch';
console.log(this.colors.cyan(message));
break;
case 'error':
this.logger.fatal(migrator.error);
this.exitCode = 1;
break;
}
}
/**
* Log final status with compact output
*/
logCompactFinalStatus(processedFiles, migrator, duration) {
let output = '';
let message = '';
let isUp = migrator.direction === 'up';
switch (migrator.status) {
case 'completed':
message = ` ${isUp ? 'Executed' : 'Reverted'} ${processedFiles.size} migrations`;
output = this.colors.grey(message + ` (${(0, pretty_hrtime_1.default)(duration)})`);
break;
case 'skipped':
message = ` ${isUp ? 'Already up to date' : 'Already at latest batch'}`;
output = this.colors.grey(message);
break;
case 'error':
const skippedMigrations = Object.values(migrator.migratedFiles).filter((file) => file.status === 'pending').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.exitCode = 1;
break;
}
this.logger.log(output);
}
/**
* Runs the migrations using the migrator
*/
async runMigrations(migrator, connectionName) {
/**
* Pretty print SQL in dry run and return early
*/
if (migrator.dryRun) {
await migrator.run();
Object.keys(migrator.migratedFiles).forEach((file) => {
this.prettyPrintSql(migrator.migratedFiles[file], connectionName);
});
return;
}
/**
* A set of files processed and emitted using event emitter.
*/
const processedFiles = new Set();
let start;
let duration;
/**
* Starting to process a new migration file
*/
migrator.on('migration:start', (file) => {
processedFiles.add(file.file.name);
if (!this.compactOutput) {
this.printLogMessage(file, migrator.direction);
}
});
/**
* Migration completed
*/
migrator.on('migration:completed', (file) => {
if (!this.compactOutput) {
this.printLogMessage(file, migrator.direction);
this.logger.logUpdatePersist();
}
});
/**
* Migration error
*/
migrator.on('migration:error', (file) => {
if (!this.compactOutput) {
this.printLogMessage(file, migrator.direction);
this.logger.logUpdatePersist();
}
});
/**
* Migration completed
*/
migrator.on('upgrade:version', ({ from, to }) => {
this.logger.info(`Upgrading migrations version from "${from}" to "${to}"`);
});
migrator.on('start', () => (start = process.hrtime()));
migrator.on('end', () => (duration = process.hrtime(start)));
/**
* Run migrations
*/
await migrator.run();
/**
* Log all pending files. This will happen, when one of the migration
* fails with an error and then the migrator stops emitting events.
*/
Object.keys(migrator.migratedFiles).forEach((file) => {
if (!processedFiles.has(file) && !this.compactOutput) {
this.printLogMessage(migrator.migratedFiles[file], migrator.direction);
}
});
if (this.compactOutput) {
this.logCompactFinalStatus(processedFiles, migrator, duration);
}
else {
this.logVerboseFinalStatus(migrator, duration);
}
}
}
exports.default = MigrationsBase;
+60
View File
@@ -0,0 +1,60 @@
import { BaseCommand } from '@adonisjs/core/build/standalone';
/**
* This command reset the database by rolling back to batch 0 and then
* re-run all migrations.
*/
export default class Refresh extends BaseCommand {
static commandName: string;
static description: string;
static settings: {
loadApp: boolean;
};
/**
* Custom connection for running migrations.
*/
connection: string;
/**
* Force command execution in production
*/
force: boolean;
/**
* Run seeders
*/
seed: boolean;
/**
* Drop all views in database
*/
dropViews: boolean;
/**
* Drop all types in database
*/
dropTypes: boolean;
/**
* Disable advisory locks
*/
disableLocks: boolean;
/**
* Converting command properties to arguments
*/
private getArgs;
/**
* Converting command properties to db:wipe arguments
*/
private getWipeArgs;
/**
* Wipe the database
*/
private runDbWipe;
/**
* Run migrations
*/
private runMigrations;
/**
* Run seeders
*/
private runDbSeed;
/**
* Handle command
*/
run(): Promise<void>;
}
+201
View File
@@ -0,0 +1,201 @@
"use strict";
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const standalone_1 = require("@adonisjs/core/build/standalone");
/**
* This command reset the database by rolling back to batch 0 and then
* re-run all migrations.
*/
class Refresh extends standalone_1.BaseCommand {
constructor() {
super(...arguments);
/**
* Custom connection for running migrations.
*/
Object.defineProperty(this, "connection", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Force command execution in production
*/
Object.defineProperty(this, "force", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Run seeders
*/
Object.defineProperty(this, "seed", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Drop all views in database
*/
Object.defineProperty(this, "dropViews", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Drop all types in database
*/
Object.defineProperty(this, "dropTypes", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Disable advisory locks
*/
Object.defineProperty(this, "disableLocks", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
/**
* Converting command properties to arguments
*/
getArgs() {
const args = [];
if (this.force) {
args.push('--force');
}
if (this.connection) {
args.push(`--connection="${this.connection}"`);
}
if (this.disableLocks) {
args.push('--disable-locks');
}
return args;
}
/**
* Converting command properties to db:wipe arguments
*/
getWipeArgs() {
const args = this.getArgs();
if (this.dropTypes) {
args.push('--drop-types');
}
if (this.dropViews) {
args.push('--drop-views');
}
return args;
}
/**
* Wipe the database
*/
async runDbWipe() {
const dbWipe = await this.kernel.exec('db:wipe', this.getWipeArgs());
this.exitCode = dbWipe.exitCode;
this.error = dbWipe.error;
}
/**
* Run migrations
*/
async runMigrations() {
const migrate = await this.kernel.exec('migration:run', this.getArgs());
this.exitCode = migrate.exitCode;
this.error = migrate.error;
}
/**
* Run seeders
*/
async runDbSeed() {
const args = [];
if (this.connection) {
args.push(`--connection="${this.connection}"`);
}
const dbSeed = await this.kernel.exec('db:seed', args);
this.exitCode = dbSeed.exitCode;
this.error = dbSeed.error;
}
/**
* Handle command
*/
async run() {
await this.runDbWipe();
if (this.exitCode) {
return;
}
await this.runMigrations();
if (this.exitCode) {
return;
}
if (this.seed) {
await this.runDbSeed();
}
}
}
Object.defineProperty(Refresh, "commandName", {
enumerable: true,
configurable: true,
writable: true,
value: 'migration:fresh'
});
Object.defineProperty(Refresh, "description", {
enumerable: true,
configurable: true,
writable: true,
value: 'Drop all tables and re-migrate the database'
});
Object.defineProperty(Refresh, "settings", {
enumerable: true,
configurable: true,
writable: true,
value: {
loadApp: true,
}
});
__decorate([
standalone_1.flags.string({ description: 'Define a custom database connection', alias: 'c' }),
__metadata("design:type", String)
], Refresh.prototype, "connection", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Explicitly force command to run in production' }),
__metadata("design:type", Boolean)
], Refresh.prototype, "force", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Run seeders' }),
__metadata("design:type", Boolean)
], Refresh.prototype, "seed", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Drop all views' }),
__metadata("design:type", Boolean)
], Refresh.prototype, "dropViews", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Drop all custom types (Postgres only)' }),
__metadata("design:type", Boolean)
], Refresh.prototype, "dropTypes", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Disable locks acquired to run migrations safely' }),
__metadata("design:type", Boolean)
], Refresh.prototype, "disableLocks", void 0);
exports.default = Refresh;
+52
View File
@@ -0,0 +1,52 @@
import { BaseCommand } from '@adonisjs/core/build/standalone';
/**
* This command reset the database by rolling back to batch 0 and then
* re-run all migrations.
*/
export default class Refresh extends BaseCommand {
static commandName: string;
static description: string;
static settings: {
loadApp: boolean;
};
/**
* Custom connection for running migrations.
*/
connection: string;
/**
* Force command execution in production
*/
force: boolean;
/**
* Perform dry run
*/
dryRun: boolean;
/**
* Run seeders
*/
seed: boolean;
/**
* Disable advisory locks
*/
disableLocks: boolean;
/**
* Converting command properties to arguments
*/
private getArgs;
/**
* Reset all migrations
*/
private resetMigrations;
/**
* Run migrations
*/
private runMigrations;
/**
* Run seeders
*/
private runDbSeed;
/**
* Handle command
*/
run(): Promise<void>;
}
+178
View File
@@ -0,0 +1,178 @@
"use strict";
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const standalone_1 = require("@adonisjs/core/build/standalone");
/**
* This command reset the database by rolling back to batch 0 and then
* re-run all migrations.
*/
class Refresh extends standalone_1.BaseCommand {
constructor() {
super(...arguments);
/**
* Custom connection for running migrations.
*/
Object.defineProperty(this, "connection", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Force command execution in production
*/
Object.defineProperty(this, "force", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Perform dry run
*/
Object.defineProperty(this, "dryRun", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Run seeders
*/
Object.defineProperty(this, "seed", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Disable advisory locks
*/
Object.defineProperty(this, "disableLocks", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
/**
* Converting command properties to arguments
*/
getArgs() {
const args = [];
if (this.force) {
args.push('--force');
}
if (this.connection) {
args.push(`--connection="${this.connection}"`);
}
if (this.dryRun) {
args.push('--dry-run');
}
if (this.disableLocks) {
args.push('--disable-locks');
}
return args;
}
/**
* Reset all migrations
*/
async resetMigrations() {
const reset = await this.kernel.exec('migration:reset', this.getArgs());
this.exitCode = reset.exitCode;
this.error = reset.error;
}
/**
* Run migrations
*/
async runMigrations() {
const migrate = await this.kernel.exec('migration:run', this.getArgs());
this.exitCode = migrate.exitCode;
this.error = migrate.error;
}
/**
* Run seeders
*/
async runDbSeed() {
const args = [];
if (this.connection) {
args.push(`--connection="${this.connection}"`);
}
const dbSeed = await this.kernel.exec('db:seed', args);
this.exitCode = dbSeed.exitCode;
this.error = dbSeed.error;
}
/**
* Handle command
*/
async run() {
await this.resetMigrations();
if (this.exitCode) {
return;
}
await this.runMigrations();
if (this.exitCode) {
return;
}
if (this.seed) {
await this.runDbSeed();
}
}
}
Object.defineProperty(Refresh, "commandName", {
enumerable: true,
configurable: true,
writable: true,
value: 'migration:refresh'
});
Object.defineProperty(Refresh, "description", {
enumerable: true,
configurable: true,
writable: true,
value: 'Rollback and migrate database'
});
Object.defineProperty(Refresh, "settings", {
enumerable: true,
configurable: true,
writable: true,
value: {
loadApp: true,
}
});
__decorate([
standalone_1.flags.string({ description: 'Define a custom database connection', alias: 'c' }),
__metadata("design:type", String)
], Refresh.prototype, "connection", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Explicitly force command to run in production' }),
__metadata("design:type", Boolean)
], Refresh.prototype, "force", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Do not run actual queries. Instead view the SQL output' }),
__metadata("design:type", Boolean)
], Refresh.prototype, "dryRun", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Run seeders' }),
__metadata("design:type", Boolean)
], Refresh.prototype, "seed", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Disable locks acquired to run migrations safely' }),
__metadata("design:type", Boolean)
], Refresh.prototype, "disableLocks", void 0);
exports.default = Refresh;
+36
View File
@@ -0,0 +1,36 @@
import { BaseCommand } from '@adonisjs/core/build/standalone';
/**
* This command resets the database by rolling back to batch 0. Same
* as calling "migration:rollback --batch=0"
*/
export default class Reset extends BaseCommand {
static commandName: string;
static description: string;
static settings: {
loadApp: boolean;
};
/**
* Custom connection for running migrations.
*/
connection: string;
/**
* Force command execution in production
*/
force: boolean;
/**
* Perform dry run
*/
dryRun: boolean;
/**
* Disable advisory locks
*/
disableLocks: boolean;
/**
* Converting command properties to arguments
*/
private getArgs;
/**
* Handle command
*/
run(): Promise<void>;
}
+129
View File
@@ -0,0 +1,129 @@
"use strict";
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const standalone_1 = require("@adonisjs/core/build/standalone");
/**
* This command resets the database by rolling back to batch 0. Same
* as calling "migration:rollback --batch=0"
*/
class Reset extends standalone_1.BaseCommand {
constructor() {
super(...arguments);
/**
* Custom connection for running migrations.
*/
Object.defineProperty(this, "connection", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Force command execution in production
*/
Object.defineProperty(this, "force", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Perform dry run
*/
Object.defineProperty(this, "dryRun", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Disable advisory locks
*/
Object.defineProperty(this, "disableLocks", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
/**
* Converting command properties to arguments
*/
getArgs() {
const args = ['--batch=0'];
if (this.force) {
args.push('--force');
}
if (this.connection) {
args.push(`--connection="${this.connection}"`);
}
if (this.dryRun) {
args.push('--dry-run');
}
if (this.disableLocks) {
args.push('--disable-locks');
}
return args;
}
/**
* Handle command
*/
async run() {
const rollback = await this.kernel.exec('migration:rollback', this.getArgs());
this.exitCode = rollback.exitCode;
this.error = rollback.error;
}
}
Object.defineProperty(Reset, "commandName", {
enumerable: true,
configurable: true,
writable: true,
value: 'migration:reset'
});
Object.defineProperty(Reset, "description", {
enumerable: true,
configurable: true,
writable: true,
value: 'Rollback all migrations'
});
Object.defineProperty(Reset, "settings", {
enumerable: true,
configurable: true,
writable: true,
value: {
loadApp: true,
}
});
__decorate([
standalone_1.flags.string({ description: 'Define a custom database connection', alias: 'c' }),
__metadata("design:type", String)
], Reset.prototype, "connection", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Explicitly force command to run in production' }),
__metadata("design:type", Boolean)
], Reset.prototype, "force", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Do not run actual queries. Instead view the SQL output' }),
__metadata("design:type", Boolean)
], Reset.prototype, "dryRun", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Disable locks acquired to run migrations safely' }),
__metadata("design:type", Boolean)
], Reset.prototype, "disableLocks", void 0);
exports.default = Reset;
+62
View File
@@ -0,0 +1,62 @@
import MigrationsBase from './Base';
/**
* The command is meant to migrate the database by executing migrations
* in `down` direction.
*/
export default class Migrate extends MigrationsBase {
static commandName: string;
static description: string;
static settings: {
loadApp: boolean;
};
private migrator;
/**
* Custom connection for running migrations.
*/
connection: string;
/**
* Force run migrations in production
*/
force: boolean;
/**
* Perform dry run
*/
dryRun: boolean;
/**
* Define custom batch, instead of rolling back to the latest batch
*/
batch: number;
/**
* Display migrations result in one compact single-line output
*/
compactOutput: boolean;
/**
* Disable advisory locks
*/
disableLocks: boolean;
/**
* Instantiating the migrator instance
*/
private instantiateMigrator;
/**
* Run as a subcommand. Never close database connections or exit
* process inside this method
*/
private runAsSubCommand;
/**
* Branching out, so that if required we can implement
* "runAsMain" separately from "runAsSubCommand".
*
* For now, they both are the same
*/
private runAsMain;
/**
* Handle command
*/
run(): Promise<void>;
/**
* Lifecycle method invoked by ace after the "run"
* method.
*/
completed(): Promise<void>;
}
+215
View File
@@ -0,0 +1,215 @@
"use strict";
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const standalone_1 = require("@adonisjs/core/build/standalone");
const Base_1 = __importDefault(require("./Base"));
/**
* The command is meant to migrate the database by executing migrations
* in `down` direction.
*/
class Migrate extends Base_1.default {
constructor() {
super(...arguments);
Object.defineProperty(this, "migrator", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Custom connection for running migrations.
*/
Object.defineProperty(this, "connection", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Force run migrations in production
*/
Object.defineProperty(this, "force", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Perform dry run
*/
Object.defineProperty(this, "dryRun", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Define custom batch, instead of rolling back to the latest batch
*/
Object.defineProperty(this, "batch", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Display migrations result in one compact single-line output
*/
Object.defineProperty(this, "compactOutput", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
/**
* Disable advisory locks
*/
Object.defineProperty(this, "disableLocks", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
/**
* Instantiating the migrator instance
*/
instantiateMigrator() {
const db = this.application.container.use('Adonis/Lucid/Database');
const Migrator = this.application.container.resolveBinding('Adonis/Lucid/Migrator');
this.migrator = new Migrator(db, this.application, {
direction: 'down',
connectionName: this.connection,
batch: this.batch,
dryRun: this.dryRun,
disableLocks: this.disableLocks,
});
}
/**
* Run as a subcommand. Never close database connections or exit
* process inside this method
*/
async runAsSubCommand() {
const db = this.application.container.use('Adonis/Lucid/Database');
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;
if (!continueMigrations) {
continueMigrations = await this.takeProductionConstent();
}
/**
* Do not continue when in prod and the prompt was cancelled
*/
if (!continueMigrations) {
return;
}
/**
* Invalid database connection
*/
if (!db.manager.has(this.connection)) {
this.printNotAValidConnection(this.connection);
this.exitCode = 1;
return;
}
this.instantiateMigrator();
await this.runMigrations(this.migrator, this.connection);
}
/**
* Branching out, so that if required we can implement
* "runAsMain" separately from "runAsSubCommand".
*
* For now, they both are the same
*/
runAsMain() {
return this.runAsSubCommand();
}
/**
* Handle command
*/
async run() {
if (this.isMain) {
await this.runAsMain();
}
else {
await this.runAsSubCommand();
}
}
/**
* Lifecycle method invoked by ace after the "run"
* method.
*/
async completed() {
if (this.migrator && this.isMain) {
await this.migrator.close();
}
}
}
Object.defineProperty(Migrate, "commandName", {
enumerable: true,
configurable: true,
writable: true,
value: 'migration:rollback'
});
Object.defineProperty(Migrate, "description", {
enumerable: true,
configurable: true,
writable: true,
value: 'Rollback migrations to a specific batch number'
});
Object.defineProperty(Migrate, "settings", {
enumerable: true,
configurable: true,
writable: true,
value: {
loadApp: true,
}
});
__decorate([
standalone_1.flags.string({ description: 'Define a custom database connection', alias: 'c' }),
__metadata("design:type", String)
], Migrate.prototype, "connection", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Explictly force to run migrations in production' }),
__metadata("design:type", Boolean)
], Migrate.prototype, "force", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Do not run actual queries. Instead view the SQL output' }),
__metadata("design:type", Boolean)
], Migrate.prototype, "dryRun", void 0);
__decorate([
standalone_1.flags.number({
description: 'Define custom batch number for rollback. Use 0 to rollback to initial state',
}),
__metadata("design:type", Number)
], Migrate.prototype, "batch", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'A compact single-line output' }),
__metadata("design:type", Boolean)
], Migrate.prototype, "compactOutput", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Disable locks acquired to run migrations safely' }),
__metadata("design:type", Boolean)
], Migrate.prototype, "disableLocks", void 0);
exports.default = Migrate;
+58
View File
@@ -0,0 +1,58 @@
import MigrationsBase from './Base';
/**
* The command is meant to migrate the database by executing migrations
* in `up` direction.
*/
export default class Migrate extends MigrationsBase {
static commandName: string;
static description: string;
static settings: {
loadApp: boolean;
};
private migrator;
/**
* Custom connection for running migrations.
*/
connection: string;
/**
* Force run migrations in production
*/
force: boolean;
/**
* Perform dry run
*/
dryRun: boolean;
/**
* Display migrations result in one compact single-line output
*/
compactOutput: boolean;
/**
* Disable advisory locks
*/
disableLocks: boolean;
/**
* Instantiating the migrator instance
*/
private instantiateMigrator;
/**
* Run as a subcommand. Never close database connections or exit
* process inside this method
*/
private runAsSubCommand;
/**
* Branching out, so that if required we can implement
* "runAsMain" separately from "runAsSubCommand".
*
* For now, they both are the same
*/
private runAsMain;
/**
* Handle command
*/
run(): Promise<void>;
/**
* Lifecycle method invoked by ace after the "run"
* method.
*/
completed(): Promise<void>;
}
+199
View File
@@ -0,0 +1,199 @@
"use strict";
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const standalone_1 = require("@adonisjs/core/build/standalone");
const Base_1 = __importDefault(require("./Base"));
/**
* The command is meant to migrate the database by executing migrations
* in `up` direction.
*/
class Migrate extends Base_1.default {
constructor() {
super(...arguments);
Object.defineProperty(this, "migrator", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Custom connection for running migrations.
*/
Object.defineProperty(this, "connection", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Force run migrations in production
*/
Object.defineProperty(this, "force", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Perform dry run
*/
Object.defineProperty(this, "dryRun", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Display migrations result in one compact single-line output
*/
Object.defineProperty(this, "compactOutput", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
/**
* Disable advisory locks
*/
Object.defineProperty(this, "disableLocks", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
/**
* Instantiating the migrator instance
*/
instantiateMigrator() {
const db = this.application.container.use('Adonis/Lucid/Database');
const Migrator = this.application.container.resolveBinding('Adonis/Lucid/Migrator');
this.migrator = new Migrator(db, this.application, {
direction: 'up',
connectionName: this.connection,
dryRun: this.dryRun,
disableLocks: this.disableLocks,
});
}
/**
* Run as a subcommand. Never close database connections or exit
* process inside this method
*/
async runAsSubCommand() {
const db = this.application.container.use('Adonis/Lucid/Database');
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;
if (!continueMigrations) {
continueMigrations = await this.takeProductionConstent();
}
/**
* Do not continue when in prod and the prompt was cancelled
*/
if (!continueMigrations) {
return;
}
/**
* Invalid database connection
*/
if (!db.manager.has(this.connection)) {
this.printNotAValidConnection(this.connection);
this.exitCode = 1;
return;
}
this.instantiateMigrator();
await this.runMigrations(this.migrator, this.connection);
}
/**
* Branching out, so that if required we can implement
* "runAsMain" separately from "runAsSubCommand".
*
* For now, they both are the same
*/
async runAsMain() {
await this.runAsSubCommand();
}
/**
* Handle command
*/
async run() {
if (this.isMain) {
await this.runAsMain();
}
else {
await this.runAsSubCommand();
}
}
/**
* Lifecycle method invoked by ace after the "run"
* method.
*/
async completed() {
if (this.migrator && this.isMain) {
await this.migrator.close();
}
}
}
Object.defineProperty(Migrate, "commandName", {
enumerable: true,
configurable: true,
writable: true,
value: 'migration:run'
});
Object.defineProperty(Migrate, "description", {
enumerable: true,
configurable: true,
writable: true,
value: 'Migrate database by running pending migrations'
});
Object.defineProperty(Migrate, "settings", {
enumerable: true,
configurable: true,
writable: true,
value: {
loadApp: true,
}
});
__decorate([
standalone_1.flags.string({ description: 'Define a custom database connection', alias: 'c' }),
__metadata("design:type", String)
], Migrate.prototype, "connection", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Explicitly force to run migrations in production' }),
__metadata("design:type", Boolean)
], Migrate.prototype, "force", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Do not run actual queries. Instead view the SQL output' }),
__metadata("design:type", Boolean)
], Migrate.prototype, "dryRun", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'A compact single-line output' }),
__metadata("design:type", Boolean)
], Migrate.prototype, "compactOutput", void 0);
__decorate([
standalone_1.flags.boolean({ description: 'Disable locks acquired to run migrations safely' }),
__metadata("design:type", Boolean)
], Migrate.prototype, "disableLocks", void 0);
exports.default = Migrate;
+54
View File
@@ -0,0 +1,54 @@
import { BaseCommand } from '@adonisjs/core/build/standalone';
/**
* The command is meant to migrate the database by execute migrations
* in `up` direction.
*/
export default class Status extends BaseCommand {
static commandName: string;
static description: string;
static settings: {
loadApp: boolean;
};
private migrator;
/**
* Define custom connection
*/
connection: string;
/**
* Not a valid connection
*/
protected printNotAValidConnection(connection: string): void;
/**
* Colorizes the status string
*/
private colorizeStatus;
/**
* Instantiating the migrator instance
*/
private instantiateMigrator;
/**
* Render list inside a table
*/
private renderList;
/**
* Run as a subcommand. Never close database connections or exit
* process inside this method
*/
private runAsSubCommand;
/**
* Branching out, so that if required we can implement
* "runAsMain" separately from "runAsSubCommand".
*
* For now, they both are the same
*/
private runAsMain;
/**
* Handle command
*/
run(): Promise<void>;
/**
* Lifecycle method invoked by ace after the "run"
* method.
*/
completed(): Promise<void>;
}
+165
View File
@@ -0,0 +1,165 @@
"use strict";
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const standalone_1 = require("@adonisjs/core/build/standalone");
/**
* The command is meant to migrate the database by execute migrations
* in `up` direction.
*/
class Status extends standalone_1.BaseCommand {
constructor() {
super(...arguments);
Object.defineProperty(this, "migrator", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/**
* Define custom connection
*/
Object.defineProperty(this, "connection", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
/**
* Not a valid connection
*/
printNotAValidConnection(connection) {
this.logger.error(`"${connection}" is not a valid connection name. Double check "config/database" file`);
}
/**
* Colorizes the status string
*/
colorizeStatus(status) {
switch (status) {
case 'pending':
return this.colors.yellow('pending');
case 'migrated':
return this.colors.green('completed');
case 'corrupt':
return this.colors.red('corrupt');
}
}
/**
* Instantiating the migrator instance
*/
instantiateMigrator() {
const db = this.application.container.use('Adonis/Lucid/Database');
const Migrator = this.application.container.resolveBinding('Adonis/Lucid/Migrator');
this.migrator = new Migrator(db, this.application, {
direction: 'up',
connectionName: this.connection,
});
}
/**
* Render list inside a table
*/
renderList(list) {
const table = this.ui.table();
table.head(['Name', 'Status', 'Batch', 'Message']);
/**
* Push a new row to the table
*/
list.forEach((node) => {
table.row([
node.name,
this.colorizeStatus(node.status),
node.batch ? String(node.batch) : 'NA',
node.status === 'corrupt' ? 'The migration file is missing on filesystem' : '',
]);
});
table.render();
}
/**
* Run as a subcommand. Never close database connections or exit
* process inside this method
*/
async runAsSubCommand() {
const db = this.application.container.use('Adonis/Lucid/Database');
this.connection = this.connection || db.primaryConnectionName;
/**
* Not a valid connection
*/
if (!db.manager.has(this.connection)) {
this.printNotAValidConnection(this.connection);
this.exitCode = 1;
return;
}
this.instantiateMigrator();
this.renderList(await this.migrator.getList());
}
/**
* Branching out, so that if required we can implement
* "runAsMain" separately from "runAsSubCommand".
*
* For now, they both are the same
*/
async runAsMain() {
await this.runAsSubCommand();
}
/**
* Handle command
*/
async run() {
if (this.isMain) {
await this.runAsMain();
}
else {
await this.runAsSubCommand();
}
}
/**
* Lifecycle method invoked by ace after the "run"
* method.
*/
async completed() {
if (this.migrator && this.isMain) {
await this.migrator.close();
}
}
}
Object.defineProperty(Status, "commandName", {
enumerable: true,
configurable: true,
writable: true,
value: 'migration:status'
});
Object.defineProperty(Status, "description", {
enumerable: true,
configurable: true,
writable: true,
value: 'View migrations status'
});
Object.defineProperty(Status, "settings", {
enumerable: true,
configurable: true,
writable: true,
value: {
loadApp: true,
}
});
__decorate([
standalone_1.flags.string({ description: 'Define a custom database connection', alias: 'c' }),
__metadata("design:type", String)
], Status.prototype, "connection", void 0);
exports.default = Status;
+2
View File
@@ -0,0 +1,2 @@
declare const _default: string[];
export default _default;
+25
View File
@@ -0,0 +1,25 @@
"use strict";
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = [
'@adonisjs/lucid/build/commands/DbSeed',
'@adonisjs/lucid/build/commands/DbWipe',
'@adonisjs/lucid/build/commands/DbTruncate',
'@adonisjs/lucid/build/commands/MakeModel',
'@adonisjs/lucid/build/commands/MakeMigration',
'@adonisjs/lucid/build/commands/MakeSeeder',
'@adonisjs/lucid/build/commands/MakeFactory',
'@adonisjs/lucid/build/commands/Migration/Run',
'@adonisjs/lucid/build/commands/Migration/Rollback',
'@adonisjs/lucid/build/commands/Migration/Status',
'@adonisjs/lucid/build/commands/Migration/Reset',
'@adonisjs/lucid/build/commands/Migration/Refresh',
'@adonisjs/lucid/build/commands/Migration/Fresh',
];