UNPKG

puddysql

Version:

🍮 Powerful SQL toolkit for Node.js, built with flexibility and structure in mind. Easily manage SQLite3/PostgreSQL, advanced queries, smart tag systems, and full JSON-friendly filters.

314 lines (313 loc) 15.8 kB
export default PuddySqlInstance; export type PgPool = import("pg").Pool; export type SqliteDb = import("sqlite").Database; /** @typedef {import('pg').Pool} PgPool */ /** @typedef {import('sqlite').Database} SqliteDb */ /** * PuddySql is a wrapper for basic SQL operations on a local storage abstraction. * It supports inserting, updating, deleting, querying and joining JSON-based structured data. */ declare class PuddySqlInstance extends PuddySqlEngine { /** * Provides access to a secure internal EventEmitter for subclass use only. * * This method exposes a dedicated EventEmitter instance intended specifically for subclasses * that extend the main class. It prevents subclasses from accidentally or intentionally using * the primary class's public event system (`emit`), which could lead to unpredictable behavior * or interference in the base class's event flow. * * For security and consistency, this method is designed to be accessed only once. * Multiple accesses are blocked to avoid leaks or misuse of the internal event bus. * * @returns {EventEmitter} A special internal EventEmitter instance for subclass use. * @throws {Error} If the method is called more than once. */ getSysEvents(): EventEmitter; /** * Enables or disables console color output for debug messages. * * @param {boolean} state - Set to `true` to enable colors, or `false` to disable. */ setConsoleColors(state: boolean): void; /** * Returns whether console color output is currently enabled. * * @returns {boolean} */ getConsoleColors(): boolean; /** * Public wrapper for #debugSql(). * Formats a SQL query using styled indentation and ANSI colors for terminal output. * * @param {string} value - The raw SQL query string to be formatted. * @returns {string} Formatted and colorized SQL for terminal display. */ debugSql(value: string): string; /** * @typedef {(...args: any[]) => void} ListenerCallback * A generic callback function used for event listeners. */ /** * Sets the maximum number of listeners for the internal event emitter. * * @param {number} max - The maximum number of listeners allowed. */ setMaxListeners(max: number): void; /** * Emits an event with optional arguments. * @param {string | symbol} event - The name of the event to emit. * @param {...any} args - Arguments passed to event listeners. * @returns {boolean} `true` if the event had listeners, `false` otherwise. */ emit(event: string | symbol, ...args: any[]): boolean; /** * Registers a listener for the specified event. * @param {string | symbol} event - The name of the event to listen for. * @param {ListenerCallback} listener - The callback function to invoke. * @returns {this} The current class instance (for chaining). */ on(event: string | symbol, listener: (...args: any[]) => void): this; /** * Registers a one-time listener for the specified event. * @param {string | symbol} event - The name of the event to listen for once. * @param {ListenerCallback} listener - The callback function to invoke. * @returns {this} The current class instance (for chaining). */ once(event: string | symbol, listener: (...args: any[]) => void): this; /** * Removes a listener from the specified event. * @param {string | symbol} event - The name of the event. * @param {ListenerCallback} listener - The listener to remove. * @returns {this} The current class instance (for chaining). */ off(event: string | symbol, listener: (...args: any[]) => void): this; /** * Alias for `on`. * @param {string | symbol} event - The name of the event. * @param {ListenerCallback} listener - The callback to register. * @returns {this} The current class instance (for chaining). */ addListener(event: string | symbol, listener: (...args: any[]) => void): this; /** * Alias for `off`. * @param {string | symbol} event - The name of the event. * @param {ListenerCallback} listener - The listener to remove. * @returns {this} The current class instance (for chaining). */ removeListener(event: string | symbol, listener: (...args: any[]) => void): this; /** * Removes all listeners for a specific event, or all events if no event is specified. * @param {string | symbol} [event] - The name of the event. If omitted, all listeners from all events will be removed. * @returns {this} The current class instance (for chaining). */ removeAllListeners(event?: string | symbol): this; /** * Returns the number of times the given `listener` is registered for the specified `event`. * If no `listener` is passed, returns how many listeners are registered for the `event`. * @param {string | symbol} eventName - The name of the event. * @param {Function} [listener] - Optional listener function to count. * @returns {number} Number of matching listeners. */ listenerCount(eventName: string | symbol, listener?: Function): number; /** * Adds a listener function to the **beginning** of the listeners array for the specified event. * The listener is called every time the event is emitted. * @param {string | symbol} eventName - The event name. * @param {ListenerCallback} listener - The callback function. * @returns {this} The current class instance (for chaining). */ prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; /** * Adds a **one-time** listener function to the **beginning** of the listeners array. * The next time the event is triggered, this listener is removed and then invoked. * @param {string | symbol} eventName - The event name. * @param {ListenerCallback} listener - The callback function. * @returns {this} The current class instance (for chaining). */ prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; /** * Returns an array of event names for which listeners are currently registered. * @returns {(string | symbol)[]} Array of event names. */ eventNames(): (string | symbol)[]; /** * Gets the current maximum number of listeners allowed for any single event. * @returns {number} The max listener count. */ getMaxListeners(): number; /** * Returns a copy of the listeners array for the specified event. * @param {string | symbol} eventName - The event name. * @returns {Function[]} An array of listener functions. */ listeners(eventName: string | symbol): Function[]; /** * Returns a copy of the internal listeners array for the specified event, * including wrapper functions like those used by `.once()`. * @param {string | symbol} eventName - The event name. * @returns {Function[]} An array of raw listener functions. */ rawListeners(eventName: string | symbol): Function[]; /** * Public wrapper for the internal debug message formatter. * Returns a formatted debug string with consistent styling. * * @param {string|number} id - Identifier used in the SQL tag (e.g., query ID). * @param {string} [debugName] - Optional label or context name for the debug log. * @param {string} [status] - Optional status message (e.g., 'OK', 'ERROR', 'LOADING'). * @returns {string} - ANSI-colored debug string for console output. */ debugConsoleText(id: string | number, debugName?: string, status?: string): string; /** * Enables or disables debug mode. * * When debug mode is enabled, SQL queries and additional debug info will be logged to the console. * * @param {boolean} isDebug - If true, debug mode is enabled; otherwise, it's disabled. */ setIsDebug(isDebug: boolean): void; /** * Checks whether debug mode is currently enabled. * * @returns {boolean} True if debug mode is enabled; otherwise, false. */ isDebug(): boolean; /** * Initializes a new table. * * This method checks if a table with the provided name already exists in the internal `#tables` object. * If the table doesn't exist, it creates a new instance of the `PuddySqlQuery` submodule, sets the database * and settings, and creates the table using the provided column data. The table is then stored in the * `#tables` object for future reference. * * The table name and column data are passed into the `PuddySqlQuery` submodule to construct the table schema. * Additional settings can be provided to customize the behavior of the table (e.g., `select`, `order`, `id`). * * @param {TableSettings} [settings={}] - Optional settings to customize the table creation. This can include properties like `select`, `join`, `order`, `id`, etc. * @param {SqlTableConfig} [tableData=[]] - An array of columns and their definitions to create the table. Each column is defined by an array, which can include column name, type, and additional settings. * @returns {Promise<PuddySqlQuery>} Resolves to the `PuddySqlQuery` instance associated with the created or existing table. * @throws {Error} If the table has already been initialized. */ initTable(settings?: import("./PuddySqlQuery.mjs").TableSettings, tableData?: import("./PuddySqlQuery.mjs").SqlTableConfig): Promise<PuddySqlQuery>; /** * Retrieves the `PuddySqlQuery` instance for the given table name. * * This method checks the internal `#tables` object and returns the corresponding `PuddySqlQuery` * instance associated with the table name. If the table does not exist, it returns `null`. * * @param {string} tableName - The name of the table to retrieve. * @returns {PuddySqlQuery} The `PuddySqlQuery` instance associated with the table, or `null` if the table does not exist. */ getTable(tableName: string): PuddySqlQuery; /** * Checks if a table with the given name exists. * * This method checks if the table with the specified name has been initialized in the internal * `#tables` object and returns a boolean value indicating its existence. * * @param {string} tableName - The name of the table to check. * @returns {boolean} `true` if the table exists, `false` if it does not. */ hasTable(tableName: string): boolean; /** * Removes the table with the given name from the internal table collection. * * This method deletes the table instance from the `#tables` object, effectively removing it from * the internal management of tables. It returns `true` if the table was successfully removed, * or `false` if the table does not exist. * * @param {string} tableName - The name of the table to remove. */ removeTable(tableName: string): void; /** * Drops and removes the table with the given name. * * This method calls the `dropTable()` method on the corresponding `PuddySqlQuery` instance, * removing the table schema from the database. After successfully dropping the table, it removes * the table from the internal `#tables` object. * * @param {string} tableName - The name of the table to drop. */ dropTable(tableName: string): Promise<void>; /** * Returns the raw database instance currently in use. * * This gives direct access to the internal database connection (PostgreSQL `Pool` or SQLite3 `Database`), * which can be useful for advanced queries or database-specific operations not covered by this wrapper. * * @returns {SqliteDb|PgPool} The internal database instance, or `null` if not initialized. */ getDb(): SqliteDb | PgPool; /** * A method to check if the database connection is open. * * This method attempts to run a simple query on the database to determine if the * connection is open or closed. It returns `true` if the database is open and * `false` if the database is closed. * * @function * @returns {Promise<boolean>} A promise that resolves to `true` if the database is open, `false` otherwise. */ isDbOpen(): Promise<boolean>; /** * Initializes an SQLite3 >= 3.35.0 database connection and sets up the SQL engine for this instance. * * This method creates a new SQLite3 database using the specified file path (or in-memory by default), * assigns the SQL engine behavior using `setSqlite3()`, and sets up a `SIGINT` listener to ensure * the database is properly closed when the process is interrupted. * * @param {string} [filePath=':memory:'] - Path to the SQLite3 database file. Defaults to in-memory. * @returns {Promise<void>} Resolves when the database is ready and the engine is set. * @throws {Error} If a SQL engine has already been initialized for this instance. */ initSqlite3(filePath?: string): Promise<void>; /** * Initializes SQLite3-specific SQL methods on this instance using the provided database wrapper. * * This method sets the SQL engine to "sqlite3" and defines the `all`, `get`, and `run` methods. * These methods internally wrap around the provided `db` object's asynchronous methods (`all`, `get`, `run`), * returning promises that resolve with the expected results or `null` on invalid data. * * @param {SqliteDb} db - A SQLite3 database wrapper that exposes `all`, `get`, and `run` methods returning Promises. * @throws {Error} If a SQL engine has already been set for this instance. */ setSqlite3(db: SqliteDb): void; /** * Initializes a PostgreSQL client and sets up the SQL engine for this instance. * * This method creates a new PostgreSQL `Pool` using the given configuration, * connects to the database, and assigns the SQL engine behavior using `setPostgre()`. * It also attaches a `SIGINT` listener to gracefully close the database connection * when the process is terminated. * * @param {import('pg').PoolConfig} config - PostgreSQL client configuration object. * Must be compatible with the `pg` Pool constructor. * @throws {Error} If a SQL engine is already initialized for this instance. */ initPostgre(config: import("pg").PoolConfig): Promise<void>; /** * Initializes PostgreSQL-specific SQL methods on this instance using the provided database wrapper. * * This method sets the engine to "postgre" and defines the `all`, `get`, and `run` methods, * wrapping around the provided `db` interface. * * @param {PgPool} db - A PostgreSQL database instance that exposes `open()` and `query()` methods. * @throws {Error} If a SQL engine is already set for this instance. */ setPostgre(db: PgPool): void; /** * Gracefully destroys the current instance by: * - Removing all internal and system event listeners; * - Properly closing the database connection based on the SQL engine in use. * * Supports both PostgreSQL (`postgre`) and SQLite3 (`sqlite3`) engines. * Errors during database disconnection are caught and logged to the console. * * @returns {Promise<void>} Resolves when all cleanup operations are complete. */ destroy(): Promise<void>; #private; } import PuddySqlEngine from './PuddySqlEngine.mjs'; import { EventEmitter } from 'events'; import PuddySqlQuery from './PuddySqlQuery.mjs';