UNPKG

@dbcube/query-builder

Version:

The DBCube Query Builder is a lightweight, flexible, and fluent library for building queries across multiple database engines, including MySQL, PostgreSQL, SQLite, and MongoDB, using JavaScript/Node.js. Its agnostic design allows you to generate data man

396 lines (393 loc) 16.2 kB
type WhereCallback = (query: Table) => void; type DatabaseRecord = Record<string, any>; /** * Main class to handle MySQL database connections and queries. * Implements the Singleton pattern to ensure a single instance of the connection pool. */ declare class Database { private name; private engine; private computedFields; private triggers; constructor(name: string); useComputes(): Promise<void>; useTriggers(): Promise<void>; connect(): Promise<void>; disconnect(): Promise<void>; /** * Creates and returns a new instance of `Table` for the specified table. * This method is used to start building queries for a specific table. * It provides a fluent interface for common database operations like select, insert, update, and delete. * * @param {string} tableName - The name of the table to query. * @returns {Table} - Returns a new instance of `Table` for the specified table. * * @example * // Select all records from a table * const users = await db.table('users').get(); * * // Select records with conditions * const activeUsers = await db.table('users') * .where('status', '=', 'active') * .orderBy('created_at', 'DESC') * .limit(10) * .get(); * * // Insert records * await db.table('users').insert([ * { name: 'John', email: 'john@example.com', age: 30 } * ]); * * // Update records * await db.table('users') * .where('id', '=', 1) * .update({ status: 'inactive' }); * * // Delete records * await db.table('users') * .where('status', '=', 'deleted') * .delete(); * * // Access column management * const columns = await db.table('users').columns().get(); */ table(tableName: string): Table; } /** * Class to build and execute SQL queries for a specific table. * Supports operations like SELECT, INSERT, UPDATE, DELETE, and more. */ declare class Table { private engine; private nextType; private dml; private computedFields; private trigger; private triggers; constructor(instance: any, databaseName: string, tableName: string, engine?: any, computedFields?: any[], triggers?: any[]); /** * Specifies the columns to select in a SELECT query. * * @param {string[]} fields - Array of column names to select. If empty, selects all columns. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').select(['id', 'name']).get(); * console.log(users); // [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }] */ select(fields?: string[]): Table; /** * Adds a WHERE condition to the query. * * @param {string} column - The column to filter by. * @param {string} operator - The comparison operator (e.g., '=', '>', '<', 'IS NULL', 'IS NOT NULL'). * @param {any} value - The value to compare against (optional for IS NULL/IS NOT NULL). * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').where('age', '>', 25).get(); * const nullUsers = await db.table('users').where('email', 'IS NULL').get(); * console.log(users); // [{ id: 1, name: 'John', age: 30 }] */ where(column: string, operator: 'IS NULL' | 'IS NOT NULL'): Table; where(column: string, operator: '=' | '!=' | '<>' | '>' | '<' | '>=' | '<=' | 'LIKE' | 'NOT LIKE' | 'IN' | 'NOT IN' | 'BETWEEN' | 'NOT BETWEEN', value: any): Table; /** * Adds an OR WHERE condition to the query. * * @param {string} column - The column to filter by. * @param {string} operator - The comparison operator (e.g., '=', '>', '<', 'IS NULL', 'IS NOT NULL'). * @param {any} value - The value to compare against (optional for IS NULL/IS NOT NULL). * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').where('age', '>', 25).orWhere('name', '=', 'Jane').get(); * const nullUsers = await db.table('users').where('active', '=', true).orWhere('email', 'IS NULL').get(); * console.log(users); // [{ id: 1, name: 'John', age: 30 }, { id: 2, name: 'Jane', age: 25 }] */ orWhere(column: string, operator: 'IS NULL' | 'IS NOT NULL'): Table; orWhere(column: string, operator: '=' | '!=' | '<>' | '>' | '<' | '>=' | '<=' | 'LIKE' | 'NOT LIKE' | 'IN' | 'NOT IN' | 'BETWEEN' | 'NOT BETWEEN', value: any): Table; /** * Adds a grouped WHERE condition to the query. * * @param {WhereCallback} callback - A callback function that receives a new Table instance to build the grouped conditions. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').whereGroup(query => { * query.where('age', '>', 25).orWhere('name', '=', 'Jane'); * }).get(); * console.log(users); // [{ id: 1, name: 'John', age: 30 }, { id: 2, name: 'Jane', age: 25 }] */ whereGroup(callback: WhereCallback): Table; or(): Table; and(): Table; /** * Adds a WHERE BETWEEN condition to the query. * * @param {string} column - The column to filter by. * @param {[any, any]} values - A tuple with two values representing the range. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').whereBetween('age', [20, 30]).get(); * console.log(users); // [{ id: 1, name: 'John', age: 30 }, { id: 2, name: 'Jane', age: 25 }] */ whereBetween(column: string, values: [any, any]): Table; /** * Adds a WHERE IN condition to the query. * * @param {string} column - The column to filter by. * @param {any[]} values - An array of values to match. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').whereIn('id', [1, 2]).get(); * console.log(users); // [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }] */ whereIn(column: string, values: any[]): Table; /** * Adds a WHERE IS NULL condition to the query. * * @param {string} column - The column to filter by. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').whereNull('email').get(); * console.log(users); // [{ id: 3, name: 'Alice', email: null }] */ whereNull(column: string): Table; /** * Adds a WHERE IS NOT NULL condition to the query. * * @param {string} column - The column to filter by. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').whereNotNull('email').get(); * console.log(users); // [{ id: 1, name: 'John', email: 'john@example.com' }] */ whereNotNull(column: string): Table; /** * Adds a JOIN clause to the query. * * @param {string} table - The table to join. * @param {string} column1 - The column from the current table. * @param {string} operator - The comparison operator (e.g., '=', '>', '<'). * @param {string} column2 - The column from the joined table. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').join('orders', 'users.id', '=', 'orders.user_id').get(); * console.log(users); // [{ id: 1, name: 'John', order_id: 101 }] */ join(table: string, column1: string, operator: string, column2: string): Table; /** * Adds a LEFT JOIN clause to the query. * * @param {string} table - The table to join. * @param {string} column1 - The column from the current table. * @param {string} operator - The comparison operator (e.g., '=', '>', '<'). * @param {string} column2 - The column from the joined table. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').leftJoin('orders', 'users.id', '=', 'orders.user_id').get(); * console.log(users); // [{ id: 1, name: 'John', order_id: 101 }, { id: 2, name: 'Jane', order_id: null }] */ leftJoin(table: string, column1: string, operator: string, column2: string): Table; /** * Adds a RIGHT JOIN clause to the query. * * @param {string} table - The table to join. * @param {string} column1 - The column from the current table. * @param {string} operator - The comparison operator (e.g., '=', '>', '<'). * @param {string} column2 - The column from the joined table. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').rightJoin('orders', 'users.id', '=', 'orders.user_id').get(); * console.log(users); // [{ id: 1, name: 'John', order_id: 101 }, { id: null, name: null, order_id: 102 }] */ rightJoin(table: string, column1: string, operator: string, column2: string): Table; /** * Adds an ORDER BY clause to the query. * * @param {string} column - The column to order by. * @param {'ASC' | 'DESC'} direction - The sorting direction ('ASC' or 'DESC'). * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').orderBy('name', 'ASC').get(); * console.log(users); // [{ id: 2, name: 'Jane' }, { id: 1, name: 'John' }] */ orderBy(column: string, direction?: 'ASC' | 'DESC'): Table; /** * Adds a GROUP BY clause to the query. * * @param {string} column - The column to group by. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').groupBy('age').get(); * console.log(users); // [{ age: 30, count: 1 }, { age: 25, count: 1 }] */ groupBy(column: string): Table; /** * Adds a DISTINCT clause to the query. * * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').distinct().select(['name']).get(); * console.log(users); // [{ name: 'John' }, { name: 'Jane' }] */ distinct(): Table; /** * Adds a COUNT clause to the query. * * @param {string} column - The column to count (default is '*'). * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const count = await db.table('users').count().first(); * console.log(count); // { count: 2 } */ count(column?: string): Table; /** * Adds a SUM clause to the query. * * @param {string} column - The column to sum. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const totalAge = await db.table('users').sum('age').first(); * console.log(totalAge); // { sum: 55 } */ sum(column: string): Table; /** * Adds an AVG clause to the query. * * @param {string} column - The column to calculate the average. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const avgAge = await db.table('users').avg('age').first(); * console.log(avgAge); // { avg: 27.5 } */ avg(column: string): Table; /** * Adds a MAX clause to the query. * * @param {string} column - The column to find the maximum value. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const maxAge = await db.table('users').max('age').first(); * console.log(maxAge); // { max: 30 } */ max(column: string): Table; /** * Adds a MIN clause to the query. * * @param {string} column - The column to find the minimum value. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const minAge = await db.table('users').min('age').first(); * console.log(minAge); // { min: 25 } */ min(column: string): Table; /** * Adds a LIMIT clause to the query. * * @param {number} number - The maximum number of rows to return. * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').limit(1).get(); * console.log(users); // [{ id: 1, name: 'John', age: 30 }] */ limit(number: number): Table; /** * Adds pagination to the query using LIMIT and OFFSET. * * @param {number} number - The page number (starting from 1). * @returns {Table} - Returns the current instance of Table for method chaining. * * @example * const users = await db.table('users').limit(1).page(2).get(); * console.log(users); // [{ id: 2, name: 'Jane', age: 25 }] */ page(number: number): Table; /** * Executes the query and returns all matching rows. * * @returns {Promise<DatabaseRecord[]>} - Returns an array of rows. * * @example * const users = await db.table('users').get(); * console.log(users); // [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }] */ get(): Promise<DatabaseRecord[]>; /** * Executes the query and returns the first matching row. * * @returns {Promise<DatabaseRecord | null>} - Returns the first row or null if no rows match. * * @example * const user = await db.table('users').first(); * console.log(user); // { id: 1, name: 'John' } */ first(): Promise<DatabaseRecord | null>; /** * Finds a row by a specific column value. * * @param {any} value - The value to search for. * @param {string} column - The column to search in (default is 'id'). * @returns {Promise<DatabaseRecord | null>} - Returns the first matching row or null if no rows match. * * @example * const user = await db.table('users').find(1); * console.log(user); // { id: 1, name: 'John' } */ find(value: any, column?: string): Promise<DatabaseRecord | null>; /** * Inserts one or more rows into the table. * * @param {DatabaseRecord[]} data - An array of objects representing the rows to insert. * @returns {Promise<DatabaseRecord[]>} - Returns an array of the inserted rows. * * @example * const newUsers = await db.table('users').insert([ * { name: 'Alice', age: 28 }, * { name: 'Bob', age: 32 } * ]); * console.log(newUsers); // [{ id: 3, name: 'Alice', age: 28 }, { id: 4, name: 'Bob', age: 32 }] */ insert(data: DatabaseRecord[]): Promise<DatabaseRecord[]>; /** * Updates rows in the table based on the defined conditions. * * @param {DatabaseRecord} data - An object with key-value pairs representing the fields to update. * @returns {Promise<any>} - Returns the result of the update operation. * * @example * const result = await db.table('users') * .where('id', '=', 1) * .update({ name: 'John Updated', age: 31 }); * console.log(result); // { affectedRows: 1 } */ update(data: DatabaseRecord): Promise<any>; /** * Deletes rows from the table based on the defined conditions. * * @returns {Promise<any>} - Returns the result of the delete operation. * * @example * const result = await db.table('users').where('id', '=', 1).delete(); * console.log(result); // { affectedRows: 1 } */ delete(): Promise<any>; private getResponse; } export { Database, type DatabaseRecord, Table, type WhereCallback, Database as default };