Skip to content

Commit d654d21

Browse files
Docs added.
1 parent a521290 commit d654d21

File tree

8 files changed

+1633
-12
lines changed

8 files changed

+1633
-12
lines changed

docs/PuddySqlEngine.md

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
# 📚 `PuddySqlEngine` Class Documentation
2+
3+
A lightweight class for managing SQL engine state and basic query methods in a pluggable and validated manner.
4+
5+
---
6+
7+
## 🔐 Private Properties
8+
9+
### `#sqlEngine: string`
10+
11+
Holds the SQL engine identifier used internally by this instance. It's set only once and used for engine-specific behaviors.
12+
13+
---
14+
15+
## 🧪 Methods
16+
17+
### 🔎 `isSqlEngineEmpty(): boolean`
18+
19+
Checks if the SQL engine is undefined, null, or an empty string.
20+
21+
***Returns**: `true` if not set or empty, otherwise `false`.
22+
23+
---
24+
25+
### 📥 `setSqlEngine(engine: string): void`
26+
27+
Sets the SQL engine to be used by this instance. Can only be set **once**, and only with a valid non-empty string.
28+
29+
* 📌 **Parameters**:
30+
31+
* `engine` *(string)*: Name of the SQL engine, e.g. `'sqlite3'`, `'postgre'`.
32+
* ⚠️ **Throws**:
33+
34+
* If already set.
35+
* If provided value is not a valid non-empty string.
36+
37+
---
38+
39+
### 📤 `getSqlEngine(): string`
40+
41+
Returns the currently set SQL engine.
42+
43+
***Returns**: SQL engine name.
44+
* ⚠️ **Throws**: If engine is not set.
45+
46+
---
47+
48+
### `isConnectionError(err: Error): boolean`
49+
50+
Detects if a given error matches known SQL engine-specific connection issues.
51+
52+
* 📌 **Parameters**:
53+
54+
* `err` *(Error)*: Error object to check.
55+
* 🔍 **Behavior**:
56+
57+
* For **PostgreSQL**, checks for known error codes like:
58+
59+
* `ECONNREFUSED`, `ETIMEDOUT`, `28P01`, `08006`, etc.
60+
* For **SQLite3**, checks if the error message includes `SQLITE_CANTOPEN`.
61+
***Returns**: `true` if a known connection error is detected.
62+
63+
---
64+
65+
## ⚙️ Query Methods
66+
67+
These methods are placeholders but follow the async query signature.
68+
69+
### 📄 `all(query: string, params?: any[], debugName?: string): Promise<any[]>`
70+
71+
Executes an SQL `SELECT` query expected to return **multiple rows**.
72+
73+
* 📌 **Parameters**:
74+
75+
* `query`: SQL string.
76+
* `params`: Optional array of parameters.
77+
* `debugName`: Optional debug label.
78+
***Returns**: Array of row results.
79+
* ⚠️ **Throws**: On query failure.
80+
81+
---
82+
83+
### 📄 `get(query: string, params?: any[], debugName?: string): Promise<object|null>`
84+
85+
Executes an SQL `SELECT` query expected to return **a single row**.
86+
87+
* 📌 **Parameters**:
88+
89+
* `query`: SQL string.
90+
* `params`: Optional array of parameters.
91+
* `debugName`: Optional debug label.
92+
***Returns**: Single result object or `null`.
93+
* ⚠️ **Throws**: On query failure.
94+
95+
---
96+
97+
### ✏️ `run(query: string, params: any[], debugName?: string): Promise<object|null>`
98+
99+
Executes an SQL `INSERT`, `UPDATE`, or `DELETE` statement.
100+
101+
* 📌 **Parameters**:
102+
103+
* `query`: SQL string.
104+
* `params`: Parameters to bind.
105+
* `debugName`: Optional debug label.
106+
***Returns**: Result object or `null`.
107+
* ⚠️ **Throws**: On execution failure.
108+
109+
---
110+
111+
## 🚀 Export
112+
113+
```js
114+
export default PuddySqlEngine;
115+
```
116+
117+
This class is ready to be used as a foundational SQL abstraction for SQLite3, PostgreSQL, and others with minimal setup.

docs/PuddySqlInstance.md

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
# 🗃️ `PuddySqlInstance` Class
2+
3+
Extends [`PuddySqlEngine`](./PuddySqlEngine.mjs) to provide high-level SQL operations with table management, debug logging, and support for both **SQLite3** and **PostgreSQL**.
4+
5+
---
6+
7+
## 🧠 Constructor
8+
9+
```js
10+
new PuddySqlInstance()
11+
```
12+
13+
Initializes the instance and sets up internal properties.
14+
15+
---
16+
17+
## 🔧 Internal Properties
18+
19+
* `#db`: The internal database instance (`sqlite` or `pg.Pool`).
20+
* `#tables`: A record of initialized tables using `PuddySqlQuery`.
21+
* `#debug`: Whether debug logging is enabled.
22+
* `#debugCount`: Number of debug calls (optional use).
23+
* `#consoleColors`: Whether debug console output uses colors.
24+
25+
---
26+
27+
## 🎨 Debug Configuration
28+
29+
### 🎛️ `setConsoleColors(state: boolean): void`
30+
31+
Enable or disable ANSI colors in debug output.
32+
33+
### `getConsoleColors(): boolean`
34+
35+
Returns whether color output is enabled.
36+
37+
---
38+
39+
## 🖌️ SQL Formatting (for Debug Output)
40+
41+
### 📜 `debugSql(value: string): string`
42+
43+
Formats a SQL string with indentation and ANSI color codes for better console readability.
44+
45+
* Adds line breaks and highlights clauses like `SELECT`, `WHERE`, `JOIN`, `LIMIT`, etc.
46+
* Wraps in decorative box with ANSI colors.
47+
48+
### 🧾 `debugConsoleText(id: string | number, debugName?: string, status?: string): string`
49+
50+
Formats a debug console message with styled tags like:
51+
52+
```txt
53+
[SQL][123] [DEBUG] [MyQuery] [OK]
54+
```
55+
56+
---
57+
58+
## 🐞 Debug Mode
59+
60+
### 🔛 `setIsDebug(isDebug: boolean): void`
61+
62+
Turns debug logging on or off.
63+
64+
### 🔍 `isDebug(): boolean`
65+
66+
Returns `true` if debug mode is enabled.
67+
68+
---
69+
70+
## 📦 Table Management
71+
72+
### 🆕 `initTable(settings?: TableSettings, tableData?: SqlTableConfig): Promise<PuddySqlQuery>`
73+
74+
Initializes a new table if it hasn't already been created.
75+
76+
* Throws if the table already exists.
77+
* Internally creates a `PuddySqlQuery` instance and assigns settings/data.
78+
79+
### 🔍 `getTable(tableName: string): PuddySqlQuery`
80+
81+
Returns the existing table instance for a given name.
82+
83+
* Throws if table does not exist.
84+
85+
### `hasTable(tableName: string): boolean`
86+
87+
Checks if a table has been initialized.
88+
89+
### 🗑️ `removeTable(tableName: string): void`
90+
91+
Removes a table from the internal map without affecting the actual DB.
92+
93+
* Throws if the table does not exist.
94+
95+
### 💣 `dropTable(tableName: string): Promise<void>`
96+
97+
Drops the table from the database schema, then removes it internally.
98+
99+
* Uses the `dropTable()` method of the `PuddySqlQuery` class.
100+
101+
---
102+
103+
## 🔍 Database Access
104+
105+
### 💾 `getDb(): SqliteDb | PgPool`
106+
107+
Returns the internal database connection instance.
108+
109+
* Useful for advanced custom queries.
110+
* Throws if the DB has not been initialized.
111+
112+
---
113+
114+
## 🔌 Connection & Engine Initialization
115+
116+
### `isDbOpen(): Promise<boolean>`
117+
118+
Checks if the database connection is open by running a test query (`SELECT 1`).
119+
120+
---
121+
122+
### 🐿️ `initSqlite3(filePath?: string = ':memory:'): Promise<void>`
123+
124+
Initializes a SQLite3 database connection (requires SQLite ≥ 3.35.0).
125+
126+
* Automatically sets the SQL engine to `"sqlite3"`.
127+
* Adds graceful shutdown logic (e.g., on `SIGINT`).
128+
129+
---
130+
131+
### 🧩 `setSqlite3(db: SqliteDb): void`
132+
133+
Sets SQLite3-specific methods (`all`, `get`, `run`) using the provided DB instance.
134+
135+
Each method includes:
136+
137+
* SQL validation and parameter checking;
138+
* Colorized debug output (if enabled);
139+
* Safe error catching and optional `connection-error` event emission.
140+
141+
---
142+
143+
### 🐘 `initPostgre(config: Pg.PoolConfig): Promise<void>`
144+
145+
Initializes a PostgreSQL client using the provided configuration.
146+
147+
* Automatically connects the pool.
148+
* Sets the SQL engine to `"postgre"`.
149+
150+
---
151+
152+
### 🔄 `setPostgre(db: Pg.Pool): void`
153+
154+
Sets PostgreSQL-specific methods (`all`, `get`, `run`) using a PostgreSQL Pool.
155+
156+
* Includes debug output;
157+
* Connection error handling via event emitter;
158+
* Uses `pg`'s async `query()` method for operations.
159+
160+
---
161+
162+
## 🔧 SQL Operation Overrides
163+
164+
All three methods below are overridden dynamically depending on the SQL engine used:
165+
166+
### 📚 `all(query: string, params?: any[], debugName?: string): Promise<Object[] | null>`
167+
168+
Executes a query expected to return multiple rows.
169+
170+
---
171+
172+
### 🧍 `get(query: string, params?: any[], debugName?: string): Promise<Object | null>`
173+
174+
Executes a query expected to return a single row.
175+
176+
---
177+
178+
### ✍️ `run(query: string, params: any[], debugName?: string): Promise<Object | null>`
179+
180+
Executes a query that modifies data (e.g., `INSERT`, `UPDATE`, `DELETE`).
181+
182+
---
183+
184+
## 🧹 Cleanup
185+
186+
### `destroy(): Promise<void>`
187+
188+
Gracefully shuts down the current instance:
189+
190+
* Removes all event listeners;
191+
* Properly closes the DB connection depending on the SQL engine (`sqlite3` or `postgre`);
192+
* Errors on disconnection are caught and logged.

0 commit comments

Comments
 (0)