Multi-Database Query Library
The `database-query` package (current stable version 1.1.22) provides a unified, lightweight interface for connecting to and executing queries against a variety of popular SQL and NoSQL databases. It supports MySQL, PostgreSQL, MS SQL Server, Oracle, MongoDB, and ClickHouse. This library acts as an abstraction layer, aiming to simplify interaction with diverse database systems through a consistent API, rather than requiring developers to learn the specific nuances of each underlying database driver. Its core functionality focuses on direct query execution and connection management, distinguishing it from full-fledged ORMs or complex query builders. The project, maintained by the Apipost-Team, has a moderate release cadence, with the last significant update in October 2023, indicating an active or maintenance status. Its primary differentiator lies in offering broad multi-database support under a single, streamlined API, facilitating integration in applications that require connectivity to multiple data stores.
Common errors
-
Error: Cannot find module 'mysql' (or 'pg', 'mssql', etc.)
cause Although `database-query` lists all drivers as dependencies, sometimes a specific driver might fail to install or be missing from the environment.fixManually try `npm install <missing-driver-package>` (e.g., `npm install mysql`) to ensure the required database driver is present in your `node_modules`. -
Error: connect ECONNREFUSED <host>:<port>
cause The application could not establish a connection to the database server. This usually indicates an incorrect host, port, database server not running, or a firewall blocking the connection.fixVerify the `host` and `port` in your database configuration. Ensure the database server is running and accessible from the machine running your application. Check firewall rules on both client and server. -
Error: Access denied for user 'youruser'@'localhost' (using password: YES)
cause The provided username or password in the database configuration is incorrect, or the user lacks necessary permissions from the specified host.fixDouble-check your `user` and `password` credentials. Ensure the database user has permissions to connect from the `host` where your application is running, and to the `database` you specified.
Warnings
- gotcha The `oracledb` driver, included as a dependency, often requires native build tools (like `gcc` on Linux or Xcode command line tools on macOS) and the Oracle Instant Client libraries to be installed on the system where the package is used. This can lead to complex installation issues, particularly in containerized environments or on different operating systems.
- gotcha While `database-query` provides a unified API, the underlying connection configurations (e.g., specific options for connection pooling, SSL/TLS, timeouts) can still vary significantly between database types. Misconfigured options for a specific database can lead to connection failures or unexpected behavior.
- gotcha This library primarily focuses on direct query execution. While it supports parameterized queries (which protect against SQL injection), constructing queries via string concatenation without proper escaping or parameterization is a major security vulnerability.
- gotcha All supported database drivers (mysql, pg, mssql, oracledb, mongodb, clickhouse) are listed as direct dependencies in `package.json`. This means `npm install database-query` will attempt to install all of them, even if you only intend to use one. This can lead to increased install times, package bloat, and potential native module compilation failures for unused drivers (especially `oracledb`).
Install
-
npm install database-query -
yarn add database-query -
pnpm add database-query
Imports
- DataBase
const DataBase = require('database-query');import { DataBase } from 'database-query'; - IDataBaseConfig
import { IDataBaseConfig } from 'database-query'; - DataBaseType
import { DataBaseType } from 'database-query';
Quickstart
import { DataBase, DataBaseType } from 'database-query';
const runQuery = async () => {
const config = {
type: DataBaseType.MySql,
host: process.env.DB_MYSQL_HOST ?? 'localhost',
port: parseInt(process.env.DB_MYSQL_PORT ?? '3306', 10),
user: process.env.DB_MYSQL_USER ?? 'root',
password: process.env.DB_MYSQL_PASSWORD ?? 'password',
database: process.env.DB_MYSQL_DATABASE ?? 'testdb',
connectionLimit: 10 // Example for MySQL, other DBs might have different pool options
};
let db: DataBase | null = null;
try {
db = new DataBase(config);
await db.connect();
console.log('Successfully connected to MySQL.');
const query = 'SELECT * FROM users WHERE age > ?';
const params = [25];
const results = await db.query(query, params);
console.log('Query results:', results);
// Example for an insert operation
const insertQuery = 'INSERT INTO logs (message) VALUES (?)';
const insertParams = ['User query executed successfully.'];
const insertResult = await db.execute(insertQuery, insertParams);
console.log('Insert result:', insertResult);
} catch (error) {
console.error('Database operation failed:', error);
} finally {
if (db) {
await db.close();
console.log('Database connection closed.');
}
}
};
runQuery();