node-database-connectors: JSON to SQL Query Builder
The `node-database-connectors` library provides a programmatic interface for converting structured JSON objects into database-specific SQL queries. It aims to abstract the direct SQL string construction process, offering a declarative approach to database interactions within Node.js applications. The library supports generating various SQL statements, including SELECT, INSERT, UPDATE, and DELETE, by interpreting JSON representations of tables, fields, aliases, join conditions, sorting, and filtering logic. Currently at version 1.7.20, it demonstrates a consistent release cadence with minor updates. Key differentiators include its focus on a JSON-based query language, its support for complex SQL operations and join conditions, and its ability to simplify application-level database logic by providing a structured, configuration-driven method for query construction.
Common errors
-
TypeError: connectionIdentifier.identify is not a function
cause Attempting to call `identify` on an incorrectly imported or undefined `connectionIdentifier` module, often due to incorrect CommonJS `require` or ESM `import` syntax.fixEnsure `node-database-connectors` is correctly installed and imported as a default export using `const connectionIdentifier = require('node-database-connectors');` for CommonJS or `import connectionIdentifier from 'node-database-connectors';` for ESM. -
Error: Invalid JSON query structure: 'table' is a required field.
cause The `jsonQuery` object provided to `prepareQuery` is missing a mandatory top-level key like `table`, which is essential for almost all SQL operations.fixReview your `jsonQuery` object and ensure all necessary fields, such as `table`, `select`, `insert`, `update`, or `filter`, are present and correctly structured according to the library's documentation for the intended query type. -
Error: Unsupported database type: 'sqlserver'
cause The `databaseType` specified in your `sampleConfig` is not recognized or supported by the `node-database-connectors` library for generating SQL queries.fixCheck the `databaseType` field in your configuration object. Use one of the officially supported types (e.g., 'mysql', 'postgres') as documented by the library.
Warnings
- gotcha The library generates SQL strings from JSON input. While it provides abstraction, proper input validation and sanitization are crucial. Directly inserting unvalidated user-supplied values into the `value` fields of `jsonQuery` could expose your application to SQL injection vulnerabilities, as the library's internal escaping mechanisms are not explicitly documented. Always sanitize or validate external input thoroughly.
- gotcha The library's support for specific SQL features, functions, and syntax may vary across different `databaseType` engines (e.g., 'mysql', 'postgres'). Complex or highly database-specific SQL constructs might not be fully supported, or they might generate unexpected or inefficient SQL. Always test generated queries thoroughly for your target database environment.
- gotcha The library strictly expects `jsonQuery` objects to adhere to a predefined structure for each SQL operation type (SELECT, INSERT, UPDATE, DELETE). Incorrectly formatted JSON objects, missing required fields, or misspellings will lead to runtime errors during query generation.
Install
-
npm install node-database-connectors -
yarn add node-database-connectors -
pnpm add node-database-connectors
Imports
- connectionIdentifier
import { connectionIdentifier } from 'node-database-connectors';import connectionIdentifier from 'node-database-connectors';
- connectionIdentifier
const connectionIdentifier = require('node-database-connectors'); - objConnection.prepareQuery
const objConnection = connectionIdentifier.identify(sampleConfig); const query = objConnection.prepareQuery(jsonQuery);
Quickstart
const connectionIdentifier = require('node-database-connectors');
// Sample database configuration
const sampleConfig = {
type: "database",
engine: 'MyISAM',
databaseType: 'mysql',
database: 'test_db',
host: "localhost",
port: "3306",
user: "root",
password: process.env.DB_PASSWORD ?? '', // Use environment variables for sensitive data
cacheResponse: false
};
// Sample JSON query for a SELECT statement
const jsonQuery = {
table: "tbl_SampleMaster",
alias: "SM",
select: [
{ field: 'pk_tableID', alias: 'pk' },
{ field: 'refNumber' }
],
sortby: [
{ field: 'refNumber' }
],
filter: {
AND: [
{ field: 'pk_id', operator: 'EQ', value: '1' }
]
}
};
try {
const objConnection = connectionIdentifier.identify(sampleConfig);
const generatedQuery = objConnection.prepareQuery(jsonQuery);
console.log('Generated SQL Query:\n', generatedQuery);
} catch (error) {
console.error('Error generating query:', error.message);
}
// Expected Output (similar to README example):
// SELECT ``.`pk_tableID` as `pk`,``.`refNumber`
// FROM `tbl_SampleMaster` as SM
// WHERE (``.`pk_id` = '1')
// ORDER BY `refNumber` ASC;