@ttoss/postgresdb-cli 0.1.19 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @ttoss/postgresdb-cli
2
2
 
3
- This package provides a CLI to interact with a PostgreSQL database using the [sequelize](https://sequelize.org/) library.
3
+ CLI for managing PostgreSQL databases with [Sequelize](https://sequelize.org/).
4
4
 
5
5
  ## Installation
6
6
 
@@ -8,50 +8,78 @@ This package provides a CLI to interact with a PostgreSQL database using the [se
8
8
  pnpm add -D @ttoss/postgresdb-cli
9
9
  ```
10
10
 
11
- ## Usage
11
+ ## Prerequisites
12
12
 
13
- First, you need to create define the `db` object in your project using the `@ttoss/postgresdb` package. Check [@ttoss/postgresdb documentation](https://ttoss.dev/docs/modules/packages/postgresdb/) for more information. The CLI will use this object to load the models and interact with the database.
13
+ Define your `db` object using [@ttoss/postgresdb](https://ttoss.dev/docs/modules/packages/postgresdb/). The CLI imports this object to load models and interact with the database.
14
14
 
15
- Second, you need to define the following environment variables to connect to the database:
15
+ Set connection environment variables in `.env` files:
16
16
 
17
- - `DB_NAME`: database name
18
- - `DB_USERNAME`: database username
19
- - `DB_PASSWORD`: database password
20
- - `DB_HOST`: database host
21
- - `DB_PORT`: database port. Default: 5432
17
+ ```env
18
+ DB_NAME=postgres
19
+ DB_USERNAME=postgres
20
+ DB_PASSWORD=mysecretpassword
21
+ DB_HOST=localhost
22
+ DB_PORT=5432
23
+ ```
24
+
25
+ **Environment-specific configuration:** Use `--environment` or `-e` flag to load `.env.<environment>` files (e.g., `.env.Production`, `.env.Staging`) instead of the default `.env`. This prevents accidental use of production credentials.
22
26
 
23
- ### Sync
27
+ ## Commands
24
28
 
25
- To [sync](https://sequelize.org/docs/v6/core-concepts/model-basics/#model-synchronization) the database schema with the models, you can use the `sync` command:
29
+ ### `sync`
30
+
31
+ [Synchronize](https://sequelize.org/docs/v6/core-concepts/model-basics/#model-synchronization) database schema with models:
26
32
 
27
33
  ```bash
28
- pnpm dlx @ttoss/postgresdb-cli sync
34
+ pnpm dlx @ttoss/postgresdb-cli sync -e Development
29
35
  ```
30
36
 
31
- Or you can add the command to your `package.json` scripts for easier access:
37
+ **⚠️ Required:** The `--environment` or `-e` flag is **mandatory** to explicitly specify which environment credentials to use. This prevents accidental operations on the wrong database.
38
+
39
+ **Using environment-specific credentials:**
40
+
41
+ ```bash
42
+ pnpm dlx @ttoss/postgresdb-cli sync --alter -e Production
43
+ ```
44
+
45
+ This loads variables from `.env.Production`.
46
+
47
+ **Behavior:**
48
+
49
+ - **Without `--alter`**: Creates new tables only (preserves existing schema)
50
+ - **With `--alter`**: Creates new tables, adds/removes columns to match models, creates new indexes (preserves tables and indexes not in models). **Requires confirmation** before executing.
51
+
52
+ ⚠️ **Caution:** The `--alter` flag modifies your database schema. Removing columns will **delete data permanently**. The CLI will prompt for confirmation before proceeding. Always backup your database before using `--alter` in production. For production environments, use proper migration tools instead of `sync`.
53
+
54
+ **Add to `package.json` for convenience:**
32
55
 
33
56
  ```json
34
57
  {
35
58
  "scripts": {
36
- "sync": "ttoss-postgresdb sync"
59
+ "sync:dev": "ttoss-postgresdb sync -e Development",
60
+ "sync:staging": "ttoss-postgresdb sync --alter -e Staging",
61
+ "sync:prod": "ttoss-postgresdb sync --alter -e Production"
37
62
  }
38
63
  }
39
64
  ```
40
65
 
41
- #### Options
66
+ **Options:**
42
67
 
43
- - `--db-path` or `-d`: Path to the file where the `db` object is defined. Default: `./src/db.js`.
44
- - `--alter`: Alter the database schema to match the models. Default: `false`.
68
+ - `--db-path, -d`: Path to `db` object file (default: `./src/db.js`)
69
+ - `--alter`: Alter schema to match models (default: `false`)
70
+ - `--environment, -e`: **(Required)** Specify environment to load `.env.<environment>` file
45
71
 
46
- ### ERD (Entity-Relationship Diagram)
72
+ ### `erd`
47
73
 
48
- To generate an [ERD](https://en.wikipedia.org/wiki/Entity%E2%80%93relationship_model) of the database, you can use the `erd` command:
74
+ Generate an [Entity-Relationship Diagram](https://en.wikipedia.org/wiki/Entity%E2%80%93relationship_model) from your models:
49
75
 
50
76
  ```bash
51
77
  pnpm dlx @ttoss/postgresdb-cli erd
52
78
  ```
53
79
 
54
- Or you can add the command to your `package.json` scripts for easier access:
80
+ **Note:** This command generates diagrams from model definitions only - database credentials are **not required** unless you need to validate against an actual database.
81
+
82
+ **Add to `package.json` for convenience:**
55
83
 
56
84
  ```json
57
85
  {
@@ -61,7 +89,7 @@ Or you can add the command to your `package.json` scripts for easier access:
61
89
  }
62
90
  ```
63
91
 
64
- #### Options
92
+ **Options:**
65
93
 
66
- - `--db-path` or `-d`: Path to the file where the `db` object is defined. Default: `./src/db.js`.
67
- - `--engine`: Layout engine to use, options are "circo", "dot", "fdp", "neato", "osage", "twopi". Default to "circo"
94
+ - `--db-path, -d`: Path to `db` object file (default: `./src/db.js`)
95
+ - `--engine`: Layout engine - `circo`, `dot`, `fdp`, `neato`, `osage`, `twopi` (default: `circo`)
package/dist/esm/index.js CHANGED
@@ -11,7 +11,7 @@ import { Command } from "commander";
11
11
  // package.json
12
12
  var package_default = {
13
13
  name: "@ttoss/postgresdb-cli",
14
- version: "0.1.18",
14
+ version: "0.1.20",
15
15
  description: "A library to handle PostgreSQL database actions through the command line",
16
16
  license: "MIT",
17
17
  author: "ttoss",
@@ -39,7 +39,7 @@ var package_default = {
39
39
  devDependencies: {
40
40
  "@ttoss/config": "workspace:^",
41
41
  jest: "^30.2.0",
42
- tsup: "^8.5.0"
42
+ tsup: "^8.5.1"
43
43
  },
44
44
  keywords: ["database", "postgres", "postgresql"],
45
45
  publishConfig: {
@@ -53,14 +53,23 @@ import * as fs from "fs";
53
53
  import sequelizeErd from "sequelize-erd";
54
54
 
55
55
  // src/getDbDynamically.ts
56
- import "dotenv/config";
57
56
  import * as builtinModules from "module";
58
57
  import path from "path";
58
+ import { config } from "dotenv";
59
59
  import * as esbuild from "esbuild";
60
60
  var nodeBuiltins = builtinModules.builtinModules;
61
61
  var getDbDynamically = /* @__PURE__ */__name(async ({
62
- dbPath
62
+ dbPath,
63
+ environment
63
64
  }) => {
65
+ if (environment) {
66
+ const envPath = path.resolve(process.cwd(), `.env.${environment}`);
67
+ config({
68
+ path: envPath,
69
+ override: true
70
+ });
71
+ console.info(`Loaded environment variables from .env.${environment}`);
72
+ }
64
73
  const lastEntryPointName = dbPath.split("/").pop();
65
74
  const filename = lastEntryPointName?.split(".")[0];
66
75
  const outfile = path.resolve(process.cwd(), "out", filename + ".js");
@@ -104,13 +113,45 @@ var erd = /* @__PURE__ */__name(async ({
104
113
  }, "erd");
105
114
 
106
115
  // src/sync.ts
116
+ import * as readline from "readline";
117
+ var confirmAlter = /* @__PURE__ */__name(() => {
118
+ return new Promise(resolve => {
119
+ const rl = readline.createInterface({
120
+ input: process.stdin,
121
+ output: process.stdout
122
+ });
123
+ rl.question("Do you want to continue? (yes/no): ", answer => {
124
+ rl.close();
125
+ resolve(answer.toLowerCase() === "yes" || answer.toLowerCase() === "y");
126
+ });
127
+ });
128
+ }, "confirmAlter");
107
129
  var sync = /* @__PURE__ */__name(async ({
108
130
  alter,
109
- dbPath
131
+ dbPath,
132
+ environment
110
133
  }) => {
134
+ console.info("Starting database synchronization...");
135
+ console.info("Environment: %s", environment || "default (.env)");
136
+ console.info("DB Path: %s", dbPath);
137
+ console.info("Mode: %s", alter ? "ALTER (will modify schema)" : "SAFE (create tables only)");
138
+ if (alter) {
139
+ console.warn("\n\u26A0\uFE0F WARNING: ALTER mode will modify your database schema!");
140
+ console.warn(" - Columns not in models will be DELETED (data loss!)");
141
+ console.warn(" - New columns will be added");
142
+ console.warn(" - Tables not in models will be preserved\n");
143
+ const confirmed = await confirmAlter();
144
+ if (!confirmed) {
145
+ console.info("Synchronization cancelled.");
146
+ process.exit(0);
147
+ }
148
+ }
149
+ console.info("\nConnecting to database...");
111
150
  const db = await getDbDynamically({
112
- dbPath
151
+ dbPath,
152
+ environment
113
153
  });
154
+ console.info("Synchronizing schema...");
114
155
  await db.sequelize.sync({
115
156
  /**
116
157
  * Don't force anymore because it's better to run migrations.
@@ -118,13 +159,13 @@ var sync = /* @__PURE__ */__name(async ({
118
159
  force: false,
119
160
  alter
120
161
  });
121
- console.info("Database synced (alter: %s)", alter);
162
+ console.info("\u2713 Database synchronized successfully (alter: %s)", alter);
122
163
  db.sequelize.close();
123
164
  }, "sync");
124
165
 
125
166
  // src/index.ts
126
167
  var program = new Command();
127
168
  program.name("ttoss-postgresdb").version(package_default.version).description("ttoss postgresdb CLI");
128
- program.command("sync").description("Sync database").action(sync).option("--alter", "Alter sync", false).option("-d, --db-path <dbPath>", "db initialization file path", "src/db.ts");
169
+ program.command("sync").description("Sync database").action(sync).option("--alter", "Alter sync", false).option("-d, --db-path <dbPath>", "db initialization file path", "src/db.ts").requiredOption("-e, --environment <environment>", "Environment name to load .env.<environment> file");
129
170
  program.command("erd").description("Generate ERD").action(erd).option("-d, --db-path <dbPath>", "db initialization file path", "src/db.ts").option("--engine <engine>", "Layout engine to use", "circo");
130
171
  program.parse(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ttoss/postgresdb-cli",
3
- "version": "0.1.19",
3
+ "version": "0.1.21",
4
4
  "description": "A library to handle PostgreSQL database actions through the command line",
5
5
  "license": "MIT",
6
6
  "author": "ttoss",
@@ -29,8 +29,8 @@
29
29
  },
30
30
  "devDependencies": {
31
31
  "jest": "^30.2.0",
32
- "tsup": "^8.5.0",
33
- "@ttoss/config": "^1.35.9"
32
+ "tsup": "^8.5.1",
33
+ "@ttoss/config": "^1.35.10"
34
34
  },
35
35
  "keywords": [
36
36
  "database",