Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ here are some details about each config option:
- rollbackDirectory: Override the default rollbacks directory name.
- autoCreateRollbacks: Set to true to automatically create rollback files.
- migrationsTableName: Name of the table created in your database.
- seedDirectory: Directory to use to store the seed file.

#

Expand Down Expand Up @@ -196,11 +197,16 @@ Essentially, you will need to do the following:

### `migrationsTableName`

The `migrationsTableName` option allows you to set a cusom table name in which
The `migrationsTableName` option allows you to set a custom table name in which
to store migration records. Make sure that this name does not conflict with
other tables in your database. Once set, there is currently no way to update
this configuration option within a project.

### `seedDirectory`

The `seedDirectory` option is how you set `seed` directory name. It should
contain `.sql` files that add data to the db.

## Commands

To view a list of commands, run:
Expand All @@ -222,6 +228,7 @@ Commands:
-m, make Create a migration file
-r, run Run all pending migrations
-rb, rollback Rollback a migration
-s, seed Run a seed file

Examples:
$ postgrate -h
Expand All @@ -230,4 +237,5 @@ Examples:
$ postgrate -m create-users-table
$ postgrate -r
$ postgrate -rb 1
$ postgrate -s base-seed
```
2 changes: 2 additions & 0 deletions src/commands/help.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Commands:
-m, make Create a migration file
-r, run Run all pending migrations
-rb, rollback Rollback a migration
-s, seed Run a seed file

Examples:
$ postgrate -h
Expand All @@ -18,5 +19,6 @@ Examples:
$ postgrate -m create-users-table
$ postgrate -r
$ postgrate -rb 1
$ postgrate -s base-seed
`);
}
1 change: 1 addition & 0 deletions src/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ export { default as run } from './run.command.js';
export { default as rollback } from './rollback.command.js';
export { default as list } from './list.command.js';
export { default as help } from './help.command.js';
export { default as seed } from './seed.command.js';
33 changes: 26 additions & 7 deletions src/commands/list.command.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,41 @@
import fs from 'fs/promises';
import config from '../config.js';
import pool from '../modules/pool.module.js';

export default async function () {
const { migrationsTableName } = config();
const { migrationsTableName, seedDirectory } = config();

const { rows } = await pool.query(
`SELECT name, id, created_at FROM ${migrationsTableName} ORDER BY id DESC`,
);

if (!rows.length) {
console.log('\nNo migrations found!\n');
return;
} else {
console.log('\nMigrations:\n');
rows.forEach((row) => {
const date = new Date(row.created_at).toLocaleDateString();
console.log(`> ID: ${row.id}, Name: ${row.name} Created: ${date}`);
});
}

console.log('\n');

if (!seedDirectory) {
console.error(`\nNo seed directory found!\n`);
} else {
const files = await fs.readdir(seedDirectory);

console.log('\NSeeds:\n');

if (files.length === 0) {
console.error(`\nNo seeds found in ${seedDirectory}\n`);
} else {
files.forEach((file) => {
console.log(`> Name: ${file}`);
});
}
}

console.log('\nMigrations:\n');
rows.forEach((row) => {
const date = new Date(row.created_at).toLocaleDateString();
console.log(`> ID: ${row.id}, Name: ${row.name} Created: ${date}`);
});
console.log('');
}
43 changes: 43 additions & 0 deletions src/commands/seed.command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import fsSync from 'fs';
import fs from 'fs/promises';
import Config from '../config';
import { confirmation, pool } from '../modules';

export default async function (seedName?: string, resetOption?: boolean) {
const { rootDirectory, seedDirectory } = Config();
if (!seedDirectory) {
console.error(`Seed directory does not exist!`);
process.exit(1);
}
if (seedName) {
const seedFilePath = `${rootDirectory}/${seedDirectory}/${seedName}.sql`;
if (!fsSync.existsSync(seedFilePath)) {
console.error(`${seedName}.sql does not exist!`);
process.exit(1);
}
const resetFilePath = `${rootDirectory}/${seedDirectory}/reset.sql`;
if (!fsSync.existsSync(resetFilePath) && resetOption) {
console.error(`reset.sql does not exist!`);
process.exit(1);
}
if (resetOption) {
await confirmation([`${seedName}.sql`, 'reset.sql']);
} else {
await confirmation(`${seedName}.sql`);
}
if(resetOption) {
const seed = await fs.readFile(resetFilePath, 'utf-8');
await pool.query(seed);
}
const seed = await fs.readFile(seedFilePath, 'utf-8');
await pool.query(seed);
if(resetOption) {
console.log(`\nDatabase truncated\n`);
}
console.log(`\nDatabase seeded\n`);
pool.end();
} else {
console.error(`Please provide a seed file name!`);
process.exit(1);
}
}
1 change: 1 addition & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ export interface IConfig {
rollbacksDirectory: string;
autoCreateRollbacks: boolean;
migrationsTableName: string;
seedDirectory?: string;
}
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
import { parser } from './modules/index.js';

const args = process.argv.slice(2);
const [command, second] = args;
const [command, second, third] = args;

await parser({ command, second });
await parser({ command, second, third });

process.exit(0);
20 changes: 17 additions & 3 deletions src/modules/parser.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { help, init, list, make, rollback, run } from '../commands/index.js';

export default async ({ command, second }: IParserInput) => {
import {
help,
init,
list,
make,
rollback,
run,
seed,
} from '../commands/index.js';

export default async ({ command, second, third }: IParserInput) => {
switch (command) {
case '-i':
case 'init':
Expand Down Expand Up @@ -32,6 +40,11 @@ export default async ({ command, second }: IParserInput) => {
help();
break;

case '-s':
case 'seed':
seed(second, !!third);
break;

default:
console.log(`Invalid command: ${command}`);
help();
Expand All @@ -43,4 +56,5 @@ export default async ({ command, second }: IParserInput) => {
interface IParserInput {
command: string;
second?: string;
third?: string;
}
28 changes: 27 additions & 1 deletion src/tests/parser.module.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { expect, it, describe, vi, afterEach } from 'vitest';
import { help, init, list, make, rollback, run } from '../commands/index.js';
import {
help,
init,
list,
make,
rollback,
run,
seed,
} from '../commands/index.js';
import { parser } from '../modules/index.js';

describe('Parser', () => {
Expand Down Expand Up @@ -54,6 +62,23 @@ describe('Parser', () => {
expect(run).toHaveBeenCalledTimes(2);
});

it('should seed upon `seed` and `-s`', () => {
vi.mock('../commands/index.js', () => {
return {
init: vi.fn(),
make: vi.fn(),
run: vi.fn(),
seed: vi.fn(),
};
});

parser({ command: 'seed' });
expect(seed).toHaveBeenCalledTimes(1);

parser({ command: '-s' });
expect(seed).toHaveBeenCalledTimes(2);
});

it('should rollback upon `rollback` and `-rb`', () => {
vi.mock('../commands/index.js', () => {
return {
Expand Down Expand Up @@ -116,6 +141,7 @@ describe('Parser', () => {
init: vi.fn(),
make: vi.fn(),
run: vi.fn(),
seed: vi.fn(),
rollback: vi.fn(),
list: vi.fn(),
help: vi.fn(),
Expand Down