@maddiethegm/dbconnector 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.npmignore +38 -0
- package/LICENSE +21 -0
- package/package.json +57 -3
- package/readme.md +208 -0
- package/services/dbconnector/connectionManager.js +91 -0
- package/services/dbconnector/logger.js +126 -0
- package/services/dbconnector/paramLibrary.js +142 -0
- package/services/dbconnector/paramsConfig.json +49 -0
- package/services/dbconnector/queryConstructor.js +271 -0
- package/services/dbconnector/queryExecutor.js +153 -0
- package/services/index.js +6 -0
- package/README.md +0 -3
package/.npmignore
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# Environment files (should be loaded separately)
|
|
2
|
+
.env
|
|
3
|
+
.env.*
|
|
4
|
+
!.env.example
|
|
5
|
+
|
|
6
|
+
# Node modules
|
|
7
|
+
node_modules/
|
|
8
|
+
npm-debug.log*
|
|
9
|
+
|
|
10
|
+
# IDE and editor files
|
|
11
|
+
.idea/
|
|
12
|
+
.vscode/
|
|
13
|
+
*.swp
|
|
14
|
+
*.swo
|
|
15
|
+
*~
|
|
16
|
+
.DS_Store
|
|
17
|
+
|
|
18
|
+
# Git artifacts
|
|
19
|
+
.git/
|
|
20
|
+
.gitignore
|
|
21
|
+
|
|
22
|
+
# Local logs (should not be published)
|
|
23
|
+
logs/
|
|
24
|
+
*.log
|
|
25
|
+
|
|
26
|
+
# Local documentation (keep these for dev, not needed for npm package)
|
|
27
|
+
docs/
|
|
28
|
+
.PUBLISHING.md
|
|
29
|
+
.SUMMARY.md
|
|
30
|
+
PUBLISHING.md
|
|
31
|
+
|
|
32
|
+
# Test data
|
|
33
|
+
test/
|
|
34
|
+
data/
|
|
35
|
+
scripts/
|
|
36
|
+
|
|
37
|
+
# Package lock file (npm will auto-generate this when users install)
|
|
38
|
+
package-lock.json
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dbconnector
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maddiethegm/dbconnector",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "A general-purpose Node.js database connector for SQL backends with CRUD operations support.",
|
|
5
|
+
"main": "./services/index.js",
|
|
6
|
+
"types": "./services/dbconnector/queryExecutor.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./services/index.js",
|
|
9
|
+
"./connectionManager": "./services/dbconnector/connectionManager.js",
|
|
10
|
+
"./logger": "./services/dbconnector/logger.js",
|
|
11
|
+
"./package.json": "./package.json"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"services/",
|
|
15
|
+
"LICENSE",
|
|
16
|
+
"README.md",
|
|
17
|
+
".npmignore"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"start": "node client.js",
|
|
21
|
+
"test": "echo \"Error: no test specified\" && exit 1",
|
|
22
|
+
"publish:dry-run": "npm publish --dry-run",
|
|
23
|
+
"prepublishOnly": "npm run lint",
|
|
24
|
+
"lint": "echo \"Linting not configured\"",
|
|
25
|
+
"prepare": "echo 'No prepare scripts needed for simple package'"
|
|
26
|
+
},
|
|
27
|
+
"keywords": [
|
|
28
|
+
"database",
|
|
29
|
+
"sql",
|
|
30
|
+
"connector",
|
|
31
|
+
"crud",
|
|
32
|
+
"query",
|
|
33
|
+
"sqlserver",
|
|
34
|
+
"mariadb",
|
|
35
|
+
"postgres",
|
|
36
|
+
"oracle"
|
|
37
|
+
],
|
|
38
|
+
"author": "Madeline Williams <mad.wills.work@gmail.com>",
|
|
39
|
+
"license": "MIT",
|
|
40
|
+
"repository": {
|
|
41
|
+
"type": "git",
|
|
42
|
+
"url": "git+https://github.com/maddiethegm/dbconnector.git"
|
|
43
|
+
},
|
|
44
|
+
"bugs": {
|
|
45
|
+
"url": "https://github.com/maddiethegm/dbconnector/issues"
|
|
46
|
+
},
|
|
47
|
+
"homepage": "https://github.com/maddiethegm/dbconnector#readme",
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"axios": "^1.11.0",
|
|
50
|
+
"cors": "^2.8.5",
|
|
51
|
+
"dotenv": "^17.2.1",
|
|
52
|
+
"express": "^5.1.0",
|
|
53
|
+
"mssql": "^11.0.1",
|
|
54
|
+
"mysql2": "^3.14.3",
|
|
55
|
+
"oracledb": "^6.9.0",
|
|
56
|
+
"pg": "^8.16.3",
|
|
57
|
+
"uuid": "^14.0.3",
|
|
58
|
+
"winston": "^3.17.0"
|
|
59
|
+
}
|
|
6
60
|
}
|
package/readme.md
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
# @maddiethegm/dbconnector
|
|
2
|
+
|
|
3
|
+
A general-purpose Node.js database connector for SQL backends with CRUD operations support. This module provides a unified interface for communicating with various SQL databases including Microsoft SQL Server, MariaDB, PostgreSQL, and Oracle.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
Install from npm:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @maddiethegm/dbconnector
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Or add it to your `package.json`:
|
|
14
|
+
|
|
15
|
+
```json
|
|
16
|
+
{
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@maddiethegm/dbconnector": "^2.0.0"
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Features
|
|
24
|
+
|
|
25
|
+
- 🔌 **Multi-database support**: SQL Server, MariaDB, PostgreSQL, Oracle
|
|
26
|
+
- ✨ **CRUD operations**: Create, Read, Update, Delete with parametric queries
|
|
27
|
+
- 🛡️ **SQL injection protection**: Uses parameterized queries for safe data handling
|
|
28
|
+
- 📝 **Logging**: Built-in Winston logger for debugging and monitoring
|
|
29
|
+
- 🔐 **Connection management**: Handles connection pooling and lifecycle
|
|
30
|
+
|
|
31
|
+
## Quick Start
|
|
32
|
+
|
|
33
|
+
### 1. Configure Database Connection
|
|
34
|
+
|
|
35
|
+
```javascript
|
|
36
|
+
require('dotenv').config();
|
|
37
|
+
|
|
38
|
+
const { queryExecutor } = require('@maddiethegm/dbconnector');
|
|
39
|
+
|
|
40
|
+
// Set environment variables:
|
|
41
|
+
// DB_USER, DB_PASSWORD, DB_SERVER, DB_PORT, DB_DATABASE, DB_TYPE
|
|
42
|
+
|
|
43
|
+
await queryExecutor.initialize({
|
|
44
|
+
user: process.env.DB_USER,
|
|
45
|
+
password: process.env.DB_PASSWORD,
|
|
46
|
+
server: process.env.DB_SERVER,
|
|
47
|
+
database: process.env.DB_DATABASE,
|
|
48
|
+
port: process.env.DB_PORT || defaultPortForType
|
|
49
|
+
});
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### 2. Perform CRUD Operations
|
|
53
|
+
|
|
54
|
+
#### Create
|
|
55
|
+
|
|
56
|
+
```javascript
|
|
57
|
+
const result = await queryExecutor.executeQuery('Users', 'CREATE', {
|
|
58
|
+
name: 'John Doe',
|
|
59
|
+
email: 'john@example.com'
|
|
60
|
+
});
|
|
61
|
+
console.log(result.insertId); // Returns the new record ID
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
#### Read (Get all or filtered)
|
|
65
|
+
|
|
66
|
+
```javascript
|
|
67
|
+
// Get all users
|
|
68
|
+
const users = await queryExecutor.executeQuery('Users', 'READ', {});
|
|
69
|
+
|
|
70
|
+
// Get a single user by ID
|
|
71
|
+
const user = await queryExecutor.executeQuery('Users', 'READ', {
|
|
72
|
+
id: 123
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// Search with partial match
|
|
76
|
+
const searchResults = await queryExecutor.executeQuery('Users', 'READ', {
|
|
77
|
+
name: 'John',
|
|
78
|
+
partialMatch: true
|
|
79
|
+
});
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
#### Update
|
|
83
|
+
|
|
84
|
+
```javascript
|
|
85
|
+
const result = await queryExecutor.executeQuery('Users', 'UPDATE', {
|
|
86
|
+
id: 123,
|
|
87
|
+
email: 'newemail@example.com' // Fields to update
|
|
88
|
+
});
|
|
89
|
+
console.log(result.affectedRows); // Returns number of affected rows
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
#### Delete
|
|
93
|
+
|
|
94
|
+
```javascript
|
|
95
|
+
await queryExecutor.executeQuery('Users', 'DELETE', {
|
|
96
|
+
id: 123
|
|
97
|
+
});
|
|
98
|
+
console.log(result.affectedRows); // Returns number of deleted rows
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### 3. Error Handling
|
|
102
|
+
|
|
103
|
+
```javascript
|
|
104
|
+
try {
|
|
105
|
+
const result = await queryExecutor.executeQuery('Users', 'READ', { id: 999 });
|
|
106
|
+
} catch (error) {
|
|
107
|
+
console.error('Query failed:', error.message);
|
|
108
|
+
console.error('Details:', error.details || '');
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### 4. Using the Logger
|
|
113
|
+
|
|
114
|
+
```javascript
|
|
115
|
+
const { logger } = require('@maddiethegm/dbconnector');
|
|
116
|
+
|
|
117
|
+
// Use the Winston logger instance
|
|
118
|
+
logger.info('Starting application');
|
|
119
|
+
logger.error('An error occurred!', { errorCode: 'E001' });
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### 5. Connection Management
|
|
123
|
+
|
|
124
|
+
```javascript
|
|
125
|
+
const { connectionManager } = require('@maddiethegm/dbconnector');
|
|
126
|
+
|
|
127
|
+
async function testConnection() {
|
|
128
|
+
await connectionManager.initialize({
|
|
129
|
+
user: process.env.DB_USER,
|
|
130
|
+
password: process.env.DB_PASSWORD,
|
|
131
|
+
server: process.env.DB_SERVER,
|
|
132
|
+
database: process.env.DB_DATABASE,
|
|
133
|
+
port: parseInt(process.env.DB_PORT) || 3006
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
const connection = await connectionManager.getConnection();
|
|
137
|
+
// Use connection for custom queries
|
|
138
|
+
connection.end();
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## Environment Variables
|
|
143
|
+
|
|
144
|
+
Set these in your `.env` file:
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
DB_USER=your_username
|
|
148
|
+
DB_PASSWORD=your_password
|
|
149
|
+
DB_SERVER=localhost
|
|
150
|
+
DB_PORT=1433 # or appropriate port for DB_TYPE
|
|
151
|
+
DB_DATABASE=your_database
|
|
152
|
+
DB_TYPE=MSSQL # Options: MSSQL, MARIADB, POSTGRES, ORACLEDB
|
|
153
|
+
DB_TRUST_CERT=false # Trust system SSL cert (useful for local dev)
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## API Structure
|
|
157
|
+
|
|
158
|
+
The module exports several utilities:
|
|
159
|
+
|
|
160
|
+
- `queryExecutor.executeQuery(table, operation, params)` - Main CRUD interface
|
|
161
|
+
- `connectionManager` - Connection pooling management
|
|
162
|
+
- `logger` - Winston logger instance
|
|
163
|
+
|
|
164
|
+
## Example Server Setup
|
|
165
|
+
|
|
166
|
+
```javascript
|
|
167
|
+
require('dotenv').config();
|
|
168
|
+
const express = require('express');
|
|
169
|
+
const { queryExecutor } = require('@maddiethegm/dbconnector');
|
|
170
|
+
const cors = require('cors');
|
|
171
|
+
|
|
172
|
+
const app = express();
|
|
173
|
+
app.use(express.json());
|
|
174
|
+
app.use(cors());
|
|
175
|
+
|
|
176
|
+
// Initialize database connection
|
|
177
|
+
await queryExecutor.initialize({
|
|
178
|
+
user: process.env.DB_USER,
|
|
179
|
+
password: process.env.DB_PASSWORD,
|
|
180
|
+
server: process.env.DB_SERVER,
|
|
181
|
+
database: process.env.DB_DATABASE,
|
|
182
|
+
port: parseInt(process.env.DB_PORT) || 3006
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
app.post('/api/query', async (req, res) => {
|
|
186
|
+
try {
|
|
187
|
+
const { table, operation, params } = req.body;
|
|
188
|
+
const result = await queryExecutor.executeQuery(table, operation, params);
|
|
189
|
+
res.status(200).json(result);
|
|
190
|
+
} catch (err) {
|
|
191
|
+
console.error('Error executing query:', err);
|
|
192
|
+
res.status(500).json({ error: err.message });
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
const PORT = process.env.PORT || 3100;
|
|
197
|
+
app.listen(PORT, () => {
|
|
198
|
+
console.log(`Server is running on port ${PORT}`);
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
## License
|
|
203
|
+
|
|
204
|
+
MIT License - see [LICENSE](./LICENSE) file for details.
|
|
205
|
+
|
|
206
|
+
## Support
|
|
207
|
+
|
|
208
|
+
For issues or feature requests, please open a ticket in the GitHub repository: https://github.com/maddiethegm/dbconnector/issues
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// /services/dbconnector/connectionManager.js
|
|
2
|
+
|
|
3
|
+
require('dotenv').config();
|
|
4
|
+
const sql = require('mssql');
|
|
5
|
+
const mysql = require('mysql2/promise');
|
|
6
|
+
const log = require('./logger');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Gets a connection based on the configured database type.
|
|
10
|
+
*
|
|
11
|
+
* @returns {Promise<Object>} A promise that resolves with the database connection.
|
|
12
|
+
*/
|
|
13
|
+
async function getConnection() {
|
|
14
|
+
const dbType = process.env.DB_TYPE;
|
|
15
|
+
const config = getDBConfig(dbType);
|
|
16
|
+
|
|
17
|
+
log.debug(`Getting database connection for ${dbType.toUpperCase()}...`);
|
|
18
|
+
|
|
19
|
+
try {
|
|
20
|
+
switch (dbType) {
|
|
21
|
+
case 'MSSQL':
|
|
22
|
+
log.info('Connecting to Microsoft SQL Server...');
|
|
23
|
+
const mssqlConnection = await sql.connect(config);
|
|
24
|
+
log.info('Microsoft SQL Server connection established', {
|
|
25
|
+
server: config.server,
|
|
26
|
+
database: config.database
|
|
27
|
+
});
|
|
28
|
+
return mssqlConnection;
|
|
29
|
+
|
|
30
|
+
case 'MARIADB':
|
|
31
|
+
log.info('Connecting to MariaDB...');
|
|
32
|
+
const mysqlConnection = await mysql.createConnection(config);
|
|
33
|
+
log.info('MariaDB connection established', {
|
|
34
|
+
host: config.host,
|
|
35
|
+
port: config.port,
|
|
36
|
+
database: config.database
|
|
37
|
+
});
|
|
38
|
+
return mysqlConnection;
|
|
39
|
+
|
|
40
|
+
default:
|
|
41
|
+
throw new Error(`Unsupported database type: ${dbType}`);
|
|
42
|
+
}
|
|
43
|
+
} catch (err) {
|
|
44
|
+
log.error('Database connection failed:', {
|
|
45
|
+
dbType,
|
|
46
|
+
errorMessage: err.message,
|
|
47
|
+
errorDetails: process.env.DB_SERVER ? 'server connected' : 'no server specified',
|
|
48
|
+
stack: err.stack.slice(0, 200) // Limit stack trace for readability
|
|
49
|
+
});
|
|
50
|
+
throw new Error(`Failed to connect to ${dbType} database: ${err.message}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Fetches the configuration for a specified database type from environment variables.
|
|
56
|
+
*
|
|
57
|
+
* @param {string} dbType - Type of database (e.g., 'MSSQL', 'ORACLE').
|
|
58
|
+
* @returns {Object} The database configuration object.
|
|
59
|
+
*/
|
|
60
|
+
function getDBConfig(dbType) {
|
|
61
|
+
log.debug(`Resolving config for ${dbType.toUpperCase()}...`);
|
|
62
|
+
|
|
63
|
+
switch (dbType) {
|
|
64
|
+
case 'MSSQL':
|
|
65
|
+
return {
|
|
66
|
+
user: process.env.DB_USER,
|
|
67
|
+
password: process.env.DB_PASSWORD,
|
|
68
|
+
server: process.env.DB_SERVER,
|
|
69
|
+
database: process.env.DB_DATABASE,
|
|
70
|
+
port: parseInt(process.env.DB_PORT, 10) || 1433,
|
|
71
|
+
options: {
|
|
72
|
+
encrypt: true, // for secure connection
|
|
73
|
+
trustServerCertificate: true
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
case 'MARIADB':
|
|
77
|
+
return {
|
|
78
|
+
host: process.env.DB_SERVER,
|
|
79
|
+
port: parseInt(process.env.DB_PORT, 10) || 3006,
|
|
80
|
+
user: process.env.DB_USER,
|
|
81
|
+
password: process.env.DB_PASSWORD,
|
|
82
|
+
database: process.env.DB_DATABASE,
|
|
83
|
+
namedPlaceholders: true
|
|
84
|
+
};
|
|
85
|
+
default:
|
|
86
|
+
log.warn(`Database type not configured. Available options: MSSQL, MARIADB`);
|
|
87
|
+
throw new Error('Unsupported database type');
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
module.exports = { getConnection };
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// services/dbconnector/logger.js - Structured logging utility for dbconnector
|
|
2
|
+
|
|
3
|
+
const winston = require('winston');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
|
|
6
|
+
// Determine log directory (logs folder relative to this file's location)
|
|
7
|
+
const logDirectory = path.resolve(__dirname, '../logs');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Create Winston logger instance with appropriate configuration
|
|
11
|
+
*/
|
|
12
|
+
const loggers = {};
|
|
13
|
+
|
|
14
|
+
function getOrCreateLogger(name, levelOverride) {
|
|
15
|
+
if (!loggers[name]) {
|
|
16
|
+
loggers[name] = winston.createLogger({
|
|
17
|
+
level: levelOverride || process.env.LOG_LEVEL || 'info',
|
|
18
|
+
format: winston.format.combine(
|
|
19
|
+
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
|
|
20
|
+
winston.format.printf(({ timestamp, level, message }) => {
|
|
21
|
+
return `[${timestamp}] [${level.toUpperCase()}] ${message}`;
|
|
22
|
+
})
|
|
23
|
+
),
|
|
24
|
+
transports: [
|
|
25
|
+
// Console transport for immediate feedback
|
|
26
|
+
new winston.transports.Console({
|
|
27
|
+
format: winston.format.combine(
|
|
28
|
+
winston.format.colorize(),
|
|
29
|
+
winston.format.simple()
|
|
30
|
+
)
|
|
31
|
+
}),
|
|
32
|
+
// Error log file
|
|
33
|
+
new winston.transports.File({
|
|
34
|
+
filename: path.join(logDirectory, 'error.log'),
|
|
35
|
+
level: 'error',
|
|
36
|
+
maxsize: 5242880, // 5MB
|
|
37
|
+
maxFiles: 3
|
|
38
|
+
}),
|
|
39
|
+
// Info log file
|
|
40
|
+
new winston.transports.File({
|
|
41
|
+
filename: path.join(logDirectory, 'info.log'),
|
|
42
|
+
maxsize: 5242880,
|
|
43
|
+
maxFiles: 3
|
|
44
|
+
})
|
|
45
|
+
]
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
return loggers[name];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Default logger (INFO level) - for general application logs
|
|
53
|
+
*/
|
|
54
|
+
const infoLogger = getOrCreateLogger('dbconnector', 'info');
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Error logger (ERROR level only) - for errors and exceptions
|
|
58
|
+
*/
|
|
59
|
+
const errorLogger = getOrCreateLogger('dbconnector', 'error');
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Debug logger (DEBUG level, disabled by default unless LOG_LEVEL=debug)
|
|
63
|
+
*/
|
|
64
|
+
function createDebugLogger() {
|
|
65
|
+
const logger = getOrCreateLogger('dbconnector', process.env.LOG_LEVEL || 'info');
|
|
66
|
+
|
|
67
|
+
if (logger.level === 'debug') {
|
|
68
|
+
return {
|
|
69
|
+
info: (...args) => infoLogger.info(...args),
|
|
70
|
+
error: (...args) => errorLogger.error(...args),
|
|
71
|
+
debug: (...args) => logger.debug(...args)
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Return a noop logger when debug mode is disabled
|
|
76
|
+
return {
|
|
77
|
+
info: () => null,
|
|
78
|
+
error: () => null,
|
|
79
|
+
debug: () => null
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const debugLogger = createDebugLogger();
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Get the current logger based on environment and context
|
|
87
|
+
*/
|
|
88
|
+
function getLogger(type) {
|
|
89
|
+
const levels = ['info', 'error', 'debug'];
|
|
90
|
+
const levelIndex = levels.indexOf(process.env.LOG_LEVEL || 'info');
|
|
91
|
+
|
|
92
|
+
if (type === 'debug' && levelIndex >= 2) {
|
|
93
|
+
return debugLogger;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (type === 'error') {
|
|
97
|
+
return errorLogger;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return infoLogger;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Export logger functions with clear naming convention
|
|
104
|
+
module.exports = {
|
|
105
|
+
// Info-level logging
|
|
106
|
+
info: (...args) => infoLogger.info(...args),
|
|
107
|
+
|
|
108
|
+
// Error-level logging
|
|
109
|
+
error: (...args) => errorLogger.error(...args),
|
|
110
|
+
|
|
111
|
+
// Debug-level logging (only when LOG_LEVEL=debug in .env)
|
|
112
|
+
debug: (...args) => {
|
|
113
|
+
if (debugLogger.debug) {
|
|
114
|
+
debugLogger.debug(...args);
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
|
|
118
|
+
// Warning-level logging (use sparingly)
|
|
119
|
+
warn: (...args) => infoLogger.warn(...args),
|
|
120
|
+
|
|
121
|
+
// Get logger by type for advanced use cases
|
|
122
|
+
getLogger,
|
|
123
|
+
|
|
124
|
+
// Utility to check if debug mode is active
|
|
125
|
+
isDebugMode: () => process.env.LOG_LEVEL === 'debug'
|
|
126
|
+
};
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// /services/dbconnector/paramLibrary.js
|
|
2
|
+
|
|
3
|
+
const sql = require('mssql');
|
|
4
|
+
const oracledb = require('oracledb');
|
|
5
|
+
const log = require('./logger');
|
|
6
|
+
|
|
7
|
+
// Load paramsConfig.json once at the start
|
|
8
|
+
let paramsConfig;
|
|
9
|
+
try {
|
|
10
|
+
paramsConfig = require('./paramsConfig.json');
|
|
11
|
+
} catch (error) {
|
|
12
|
+
log.error('Error reading params config file', { error: error.message });
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Formats query parameters based on their keys and types, specific to each database type.
|
|
17
|
+
*
|
|
18
|
+
* @param {Object} params - An object containing the parameters to format.
|
|
19
|
+
* @returns {Promise<Object>} A promise that resolves with formatted parameters.
|
|
20
|
+
*/
|
|
21
|
+
async function formatQueryParams(params) {
|
|
22
|
+
const { DB_TYPE } = process.env;
|
|
23
|
+
|
|
24
|
+
if (log.debug) {
|
|
25
|
+
log.debug(`Formatting query parameters for ${DB_TYPE.toUpperCase()}`, {
|
|
26
|
+
paramCount: Object.keys(params).length,
|
|
27
|
+
params: JSON.stringify(params, null, 2)
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
switch (DB_TYPE.toUpperCase()) {
|
|
32
|
+
case 'MSSQL':
|
|
33
|
+
return formatMSSQLParams(params, paramsConfig.mssql);
|
|
34
|
+
case 'MARIADB':
|
|
35
|
+
return formatMariaDBParams(params, paramsConfig.mariaDB);
|
|
36
|
+
default:
|
|
37
|
+
throw new Error(`Unsupported database type for parameter formatting: ${DB_TYPE}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Formats query parameters for MSSQL.
|
|
43
|
+
*
|
|
44
|
+
* @param {Object} params - An object containing the parameters to format.
|
|
45
|
+
* @param {Object} config - Database-specific configuration from JSON.
|
|
46
|
+
* @returns {Object} Formatted parameters.
|
|
47
|
+
*/
|
|
48
|
+
function formatMSSQLParams(params, config) {
|
|
49
|
+
if (!config) {
|
|
50
|
+
throw new Error('SQL Server parameters config is not available');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const formattedParams = {};
|
|
54
|
+
for (const key in params) {
|
|
55
|
+
const paramConfig = config[key];
|
|
56
|
+
|
|
57
|
+
if (!paramConfig) {
|
|
58
|
+
log.warn(`Parameter '${key}' not defined in SQL Server configuration. Skipping...`);
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
let type;
|
|
63
|
+
|
|
64
|
+
switch (paramConfig.type.toLowerCase()) {
|
|
65
|
+
case 'uniqueidentifier':
|
|
66
|
+
type = sql.UniqueIdentifier;
|
|
67
|
+
break;
|
|
68
|
+
case 'nvarchar':
|
|
69
|
+
if (!paramConfig.maxLength) {
|
|
70
|
+
throw new Error(`Parameter '${key}' is missing maxLength in configuration.`);
|
|
71
|
+
}
|
|
72
|
+
type = sql.NVarChar(paramConfig.maxLength);
|
|
73
|
+
break;
|
|
74
|
+
case 'text':
|
|
75
|
+
type = sql.Text;
|
|
76
|
+
break;
|
|
77
|
+
case 'int':
|
|
78
|
+
type = sql.Int;
|
|
79
|
+
break;
|
|
80
|
+
case 'bit':
|
|
81
|
+
type = sql.Bit;
|
|
82
|
+
break;
|
|
83
|
+
default:
|
|
84
|
+
throw new Error(`Unsupported parameter type: ${paramConfig.type} for parameter '${key}'`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
formattedParams[key] = { type, value: params[key] };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
log.debug(`Formatted ${Object.keys(formattedParams).length} parameters for MSSQL`);
|
|
91
|
+
return formattedParams;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Formats query parameters for MariaDB.
|
|
96
|
+
*
|
|
97
|
+
* @param {Object} params - An object containing the parameters to format.
|
|
98
|
+
* @param {Object} config - Database-specific configuration from JSON.
|
|
99
|
+
* @returns {Object} Formatted parameters.
|
|
100
|
+
*/
|
|
101
|
+
function formatMariaDBParams(params, config) {
|
|
102
|
+
if (!config) {
|
|
103
|
+
throw new Error('MariaDB parameters config is not available');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const formattedParams = {};
|
|
107
|
+
for (const key in params) {
|
|
108
|
+
const paramConfig = config[key];
|
|
109
|
+
|
|
110
|
+
if (!paramConfig) {
|
|
111
|
+
log.warn(`Parameter '${key}' not defined in MariaDB configuration. Skipping...`);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
let type;
|
|
116
|
+
|
|
117
|
+
switch (paramConfig.type.toLowerCase()) {
|
|
118
|
+
case 'string':
|
|
119
|
+
type = '?'; // MariaDB uses ? placeholders
|
|
120
|
+
break;
|
|
121
|
+
case 'text':
|
|
122
|
+
type = '?';
|
|
123
|
+
break;
|
|
124
|
+
case 'boolean':
|
|
125
|
+
type = '?';
|
|
126
|
+
break;
|
|
127
|
+
case 'uuid':
|
|
128
|
+
type = '?';
|
|
129
|
+
break;
|
|
130
|
+
default:
|
|
131
|
+
log.warn(`Unknown MariaDB parameter type '${paramConfig.type}' for '${key}'. Using string placeholder.`);
|
|
132
|
+
type = '?';
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
formattedParams[key] = { type, value: params[key] };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
log.debug(`Formatted ${Object.keys(formattedParams).length} parameters for MariaDB`);
|
|
139
|
+
return formattedParams;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
module.exports = { formatQueryParams };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"mssql": {
|
|
3
|
+
"ID": { "type": "uniqueidentifier" },
|
|
4
|
+
"Name": { "type": "nvarchar", "maxLength": 255 },
|
|
5
|
+
"Description": { "type": "nvarchar", "maxLength": 255 },
|
|
6
|
+
"Building": { "type": "nvarchar", "maxLength": 255 },
|
|
7
|
+
"Bin": { "type": "nvarchar", "maxLength": 255 },
|
|
8
|
+
"Owner": { "type": "nvarchar", "maxLength": 255 },
|
|
9
|
+
"Role": { "type": "nvarchar", "maxLength": 255 },
|
|
10
|
+
"Location": { "type": "nvarchar", "maxLength": 255 },
|
|
11
|
+
"Route": { "type": "nvarchar", "maxLength": 255 },
|
|
12
|
+
"Email": { "type": "nvarchar", "maxLength": 255 },
|
|
13
|
+
"DisplayName": { "type": "nvarchar", "maxLength": 255 },
|
|
14
|
+
"Team": { "type": "nvarchar", "maxLength": 255 },
|
|
15
|
+
"Username": { "type": "nvarchar", "maxLength": 50 },
|
|
16
|
+
"AuthenticatedUsername": { "type": "nvarchar", "maxLength": 50 },
|
|
17
|
+
"UITheme": { "type": "nvarchar", "maxLength": 50 },
|
|
18
|
+
"Bio": { "type": "nvarchar", "maxlength": 255 },
|
|
19
|
+
"PasswordHash": { "type": "text" },
|
|
20
|
+
"Image": { "type": "nvarchar", "maxLength": 255 },
|
|
21
|
+
"AvatarURL": { "type": "nvarchar", "maxlength": 255 },
|
|
22
|
+
"SQL_USER": { "type": "bit" },
|
|
23
|
+
"Text": { "type": "nvarchar", "maxLength": 255 },
|
|
24
|
+
"Quantity": { "type": "int" },
|
|
25
|
+
"RequestPayload": { "type": "text" }
|
|
26
|
+
},
|
|
27
|
+
"mariaDB": {
|
|
28
|
+
"ID": { "type": "uuid" },
|
|
29
|
+
"Name": { "type": "string" },
|
|
30
|
+
"Description": { "type": "string" },
|
|
31
|
+
"Text": { "type": "string" },
|
|
32
|
+
"Building": { "type": "string" },
|
|
33
|
+
"Owner": { "type": "string" },
|
|
34
|
+
"Role": { "type": "string" },
|
|
35
|
+
"Location": { "type": "string" },
|
|
36
|
+
"Route": { "type": "string" },
|
|
37
|
+
"Email": { "type": "string" },
|
|
38
|
+
"DisplayName": { "type": "string" },
|
|
39
|
+
"Team": { "type": "string" },
|
|
40
|
+
"Username": { "type": "string" },
|
|
41
|
+
"AuthenticatedUsername": { "type": "string" },
|
|
42
|
+
"UITheme": { "type": "string" },
|
|
43
|
+
"Bio": { "type": "text" },
|
|
44
|
+
"PasswordHash": { "type": "text" },
|
|
45
|
+
"Image": { "type": "text" },
|
|
46
|
+
"AvatarURL": { "type": "text" },
|
|
47
|
+
"SQL_USER": { "type": "boolean" }
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
// /services/dbconnector/queryConstructor.js
|
|
2
|
+
|
|
3
|
+
const log = require('./logger');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Generates a SQL query string based on table, operation, and parameters.
|
|
7
|
+
*
|
|
8
|
+
* @param {string} table - The name of the database table.
|
|
9
|
+
* @param {string} operation - CRUD operation (e.g., 'CREATE', 'READ').
|
|
10
|
+
* @param {Object} params - Parameters for the SQL query.
|
|
11
|
+
* @returns {Promise<string>} A promise that resolves with the constructed SQL query string.
|
|
12
|
+
*/
|
|
13
|
+
async function generateQuery(table, operation, params) {
|
|
14
|
+
const { DB_TYPE } = process.env;
|
|
15
|
+
let query = '';
|
|
16
|
+
|
|
17
|
+
log.debug(`Generating query for ${operation.toUpperCase()} on table ${table}...`);
|
|
18
|
+
|
|
19
|
+
switch (operation.toUpperCase()) {
|
|
20
|
+
case 'CREATE':
|
|
21
|
+
validateCreateParams(params);
|
|
22
|
+
query = generateCreateQuery(DB_TYPE, table, params);
|
|
23
|
+
break;
|
|
24
|
+
case 'READ':
|
|
25
|
+
validateReadParams(params);
|
|
26
|
+
query = generateReadQuery(DB_TYPE, table, params);
|
|
27
|
+
break;
|
|
28
|
+
case 'UPDATE':
|
|
29
|
+
validateUpdateParams(params);
|
|
30
|
+
query = generateUpdateQuery(DB_TYPE, table, params);
|
|
31
|
+
break;
|
|
32
|
+
case 'DELETE':
|
|
33
|
+
validateDeleteParams(params);
|
|
34
|
+
query = generateDeleteQuery(DB_TYPE, table, params);
|
|
35
|
+
break;
|
|
36
|
+
case 'TEST':
|
|
37
|
+
query = generateTestQuery(DB_TYPE);
|
|
38
|
+
break;
|
|
39
|
+
default:
|
|
40
|
+
throw new Error(`Unsupported operation: ${operation}`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
log.debug(`Generated query (length: ${query.length})`);
|
|
44
|
+
return query;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Validates parameters for CREATE operation.
|
|
49
|
+
*
|
|
50
|
+
* @param {Object} params - Parameters for the SQL query.
|
|
51
|
+
*/
|
|
52
|
+
function validateCreateParams(params) {
|
|
53
|
+
if (!params || typeof params !== 'object' || Object.keys(params).length === 0) {
|
|
54
|
+
throw new Error('Missing or invalid parameters for CREATE operation. Please provide a non-empty object with necessary fields.');
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Validates parameters for READ operation.
|
|
60
|
+
*
|
|
61
|
+
* @param {Object} params - Parameters for the SQL query.
|
|
62
|
+
*/
|
|
63
|
+
function validateReadParams(params) {
|
|
64
|
+
if (!params || typeof params !== 'object') {
|
|
65
|
+
throw new Error('Missing or invalid parameters for READ operation. Please provide an object with at least one search field.');
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Validates parameters for UPDATE operation.
|
|
71
|
+
*
|
|
72
|
+
* @param {Object} params - Parameters for the SQL query.
|
|
73
|
+
*/
|
|
74
|
+
function validateUpdateParams(params) {
|
|
75
|
+
if (!params || typeof params !== 'object' || !params.ID || Object.keys(params).length <= 1) {
|
|
76
|
+
throw new Error('Missing or invalid parameters for UPDATE operation. Please provide an object with "ID" field and at least one other field to update.');
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Validates parameters for DELETE operation.
|
|
82
|
+
*
|
|
83
|
+
* @param {Object} params - Parameters for the SQL query.
|
|
84
|
+
*/
|
|
85
|
+
function validateDeleteParams(params) {
|
|
86
|
+
if (!params || typeof params !== 'object' || !params.ID) {
|
|
87
|
+
throw new Error('Missing or invalid parameters for DELETE operation. Please provide an object with "ID" field.');
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Generates a CREATE SQL query string based on database type, table, and parameters.
|
|
93
|
+
*
|
|
94
|
+
* @param {string} dbType - Type of database (e.g., 'MSSQL', 'ORACLE').
|
|
95
|
+
* @param {string} table - The name of the database table.
|
|
96
|
+
* @param {Object} params - Parameters for the SQL query.
|
|
97
|
+
* @returns {string} The constructed CREATE SQL query string.
|
|
98
|
+
*/
|
|
99
|
+
function generateCreateQuery(dbType, table, params) {
|
|
100
|
+
const columns = Object.keys(params).join(', ');
|
|
101
|
+
|
|
102
|
+
// Generate placeholders based on dbType
|
|
103
|
+
let placeholders;
|
|
104
|
+
switch (dbType.toUpperCase()) {
|
|
105
|
+
case 'MSSQL':
|
|
106
|
+
placeholders = Object.keys(params)
|
|
107
|
+
.map(key => `@${key}`)
|
|
108
|
+
.join(', ');
|
|
109
|
+
break;
|
|
110
|
+
case 'MARIADB':
|
|
111
|
+
placeholders = Object.keys(params).map(() => `?`).join(', '); // Use ? for MariaDB
|
|
112
|
+
break;
|
|
113
|
+
default:
|
|
114
|
+
throw new Error(`Unsupported database type for CREATE operation: ${dbType}`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
log.debug(`CREATE query constructed: INSERT INTO ${table} (...)`);
|
|
118
|
+
return `INSERT INTO ${table} (${columns}) VALUES (${placeholders});`;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Generates a READ SQL query string based on database type, table, and parameters.
|
|
123
|
+
*
|
|
124
|
+
* @param {string} dbType - Type of database (e.g., 'MSSQL', 'ORACLE').
|
|
125
|
+
* @param {string} table - The name of the database table.
|
|
126
|
+
* @param {Object} params - Parameters for the SQL query.
|
|
127
|
+
* @returns {string} The constructed READ SQL query string.
|
|
128
|
+
*/
|
|
129
|
+
function generateReadQuery(dbType, table, params) {
|
|
130
|
+
log.debug(`Generating READ query for ${table}`);
|
|
131
|
+
|
|
132
|
+
// Start with the basic SELECT statement
|
|
133
|
+
let query = `SELECT * FROM ${table}`;
|
|
134
|
+
|
|
135
|
+
// Prepare an array to hold WHERE conditions
|
|
136
|
+
const whereConditions = [];
|
|
137
|
+
const searchParams = [];
|
|
138
|
+
|
|
139
|
+
for (const key in params) {
|
|
140
|
+
if (!params[key]) continue;
|
|
141
|
+
|
|
142
|
+
if (key === 'partialMatch') continue; // Skip the partialSearch flag
|
|
143
|
+
|
|
144
|
+
let condition;
|
|
145
|
+
switch (dbType.toUpperCase()) {
|
|
146
|
+
case 'MSSQL':
|
|
147
|
+
if (params.partialMatch) {
|
|
148
|
+
condition = `${key} LIKE '%' + @${key} + '%'`;
|
|
149
|
+
searchParams.push({ key, value: `%${params[key]}%`, type: sql.NVarChar(255) });
|
|
150
|
+
} else {
|
|
151
|
+
condition = `${key} = @${key}`;
|
|
152
|
+
searchParams.push({ key, value: params[key], type: sql.NVarChar(255) });
|
|
153
|
+
}
|
|
154
|
+
break;
|
|
155
|
+
case 'MARIADB':
|
|
156
|
+
if (params.partialMatch) {
|
|
157
|
+
condition = `${key} LIKE ?`;
|
|
158
|
+
searchParams.push({ key, value: `%${params[key]}%`, type: '?' });
|
|
159
|
+
} else {
|
|
160
|
+
condition = `${key} = ?`;
|
|
161
|
+
searchParams.push({ key, value: params[key], type: '?' });
|
|
162
|
+
}
|
|
163
|
+
break;
|
|
164
|
+
default:
|
|
165
|
+
throw new Error(`Unsupported database type for READ: ${dbType}`);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
whereConditions.push(condition);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// If there are any WHERE conditions, append them to the query
|
|
172
|
+
if (whereConditions.length > 0) {
|
|
173
|
+
query += ` WHERE ${whereConditions.join(' AND ')}`;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
log.debug(`READ query constructed: ${query.slice(0, 200)}`);
|
|
177
|
+
return query;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Generates an UPDATE SQL query string based on database type, table, and parameters.
|
|
182
|
+
*
|
|
183
|
+
* @param {string} dbType - Type of database (e.g., 'MSSQL', 'ORACLE').
|
|
184
|
+
* @param {string} table - The name of the database table.
|
|
185
|
+
* @param {Object} params - Parameters for the SQL query.
|
|
186
|
+
* @returns {Promise<string>} The constructed UPDATE SQL query string.
|
|
187
|
+
*/
|
|
188
|
+
async function generateUpdateQuery(dbType, table, params) {
|
|
189
|
+
log.debug(`Generating UPDATE query for ${table}`);
|
|
190
|
+
|
|
191
|
+
const updateClause = Object.keys(params)
|
|
192
|
+
.filter(key => key !== 'ID') // Exclude ID from update clause
|
|
193
|
+
.map(key => {
|
|
194
|
+
switch (dbType.toUpperCase()) {
|
|
195
|
+
case 'MSSQL':
|
|
196
|
+
return `${key} = @${key}`;
|
|
197
|
+
case 'POSTGRES':
|
|
198
|
+
return `${key} = $1`;
|
|
199
|
+
case 'MARIADB':
|
|
200
|
+
return `${key} = ?`;
|
|
201
|
+
default:
|
|
202
|
+
throw new Error(`Unsupported database type for UPDATE: ${dbType}`);
|
|
203
|
+
}
|
|
204
|
+
})
|
|
205
|
+
.join(', ');
|
|
206
|
+
|
|
207
|
+
let whereClause;
|
|
208
|
+
switch (dbType.toUpperCase()) {
|
|
209
|
+
case 'MSSQL':
|
|
210
|
+
whereClause = `WHERE ID = @ID`;
|
|
211
|
+
break;
|
|
212
|
+
case 'MARIADB':
|
|
213
|
+
whereClause = `WHERE ID = ?`;
|
|
214
|
+
break;
|
|
215
|
+
default:
|
|
216
|
+
throw new Error(`Unsupported database type for UPDATE WHERE: ${dbType}`);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
log.debug(`UPDATE query constructed: ${table} SET ...`);
|
|
220
|
+
return `UPDATE ${table} SET ${updateClause} ${whereClause};`;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Generates a DELETE SQL query string based on database type, table, and parameters.
|
|
225
|
+
*
|
|
226
|
+
* @param {string} dbType - Type of database (e.g., 'MSSQL', 'ORACLE').
|
|
227
|
+
* @param {string} table - The name of the database table.
|
|
228
|
+
* @param {Object} params - Parameters for the SQL query.
|
|
229
|
+
* @returns {Promise<string>} The constructed DELETE SQL query string.
|
|
230
|
+
*/
|
|
231
|
+
async function generateDeleteQuery(dbType, table, params) {
|
|
232
|
+
const idParam = params.ID || 'ID';
|
|
233
|
+
|
|
234
|
+
log.debug(`Generating DELETE query for ${table}`);
|
|
235
|
+
|
|
236
|
+
let whereClause;
|
|
237
|
+
switch (dbType.toUpperCase()) {
|
|
238
|
+
case 'MSSQL':
|
|
239
|
+
whereClause = `WHERE ID = @ID`;
|
|
240
|
+
break;
|
|
241
|
+
case 'MARIADB':
|
|
242
|
+
whereClause = `WHERE ID = ?`;
|
|
243
|
+
break;
|
|
244
|
+
default:
|
|
245
|
+
throw new Error(`Unsupported database type for DELETE: ${dbType}`);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
log.debug(`DELETE query constructed: DELETE FROM ${table} ...`);
|
|
249
|
+
return `DELETE FROM ${table} ${whereClause};`;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Generates a TEST SQL query string based on database type.
|
|
254
|
+
*
|
|
255
|
+
* @param {string} dbType - Type of database (e.g., 'MSSQL', 'ORACLE').
|
|
256
|
+
* @returns {Promise<string>} The constructed TEST SQL query string.
|
|
257
|
+
*/
|
|
258
|
+
async function generateTestQuery(dbType) {
|
|
259
|
+
log.debug('Generating TEST query...');
|
|
260
|
+
|
|
261
|
+
switch (dbType.toUpperCase()) {
|
|
262
|
+
case 'MSSQL':
|
|
263
|
+
return `SELECT @@SPID;`;
|
|
264
|
+
case 'MARIADB':
|
|
265
|
+
return `SELECT CONNECTION_ID();`;
|
|
266
|
+
default:
|
|
267
|
+
throw new Error(`Unsupported database type for TEST: ${dbType}`);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
module.exports = { generateQuery };
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// /services/dbconnector/queryExecutor.js
|
|
2
|
+
|
|
3
|
+
require('dotenv').config();
|
|
4
|
+
const connectionManager = require('./connectionManager');
|
|
5
|
+
const queryConstructor = require('./queryConstructor');
|
|
6
|
+
const paramLibrary = require('./paramLibrary');
|
|
7
|
+
const log = require('./logger');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Executes a query against the configured database type.
|
|
11
|
+
*
|
|
12
|
+
* @param {string} table - The name of the database table.
|
|
13
|
+
* @param {string} operation - CRUD operation (e.g., 'CREATE', 'READ').
|
|
14
|
+
* @param {Object} params - Parameters for the SQL query.
|
|
15
|
+
* @returns {Promise<Object>} A promise that resolves with the result of the query execution.
|
|
16
|
+
*/
|
|
17
|
+
async function executeQuery(table, operation, params) {
|
|
18
|
+
const operationType = operation.toUpperCase();
|
|
19
|
+
|
|
20
|
+
// Log debug info (only when LOG_LEVEL=debug in .env)
|
|
21
|
+
if (log.debug) {
|
|
22
|
+
log.debug(`[${operationType}] Query started - Table: ${table}`, {
|
|
23
|
+
params: JSON.stringify(params, null, 2)
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const query = await queryConstructor.generateQuery(table, operation, params);
|
|
28
|
+
|
|
29
|
+
let result;
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
const formattedParams = await paramLibrary.formatQueryParams(params);
|
|
33
|
+
const connection = await connectionManager.getConnection();
|
|
34
|
+
|
|
35
|
+
switch (process.env.DB_TYPE.toUpperCase()) {
|
|
36
|
+
case 'MSSQL':
|
|
37
|
+
log.info('Executing MSSQL query', { operation: operationType, table });
|
|
38
|
+
result = await executeMSSQLQuery(connection, query, formattedParams);
|
|
39
|
+
break;
|
|
40
|
+
case 'MARIADB':
|
|
41
|
+
log.info('Executing MariaDB query', { operation: operationType, table });
|
|
42
|
+
result = await executeMariaDBQuery(connection, query, formattedParams);
|
|
43
|
+
break;
|
|
44
|
+
default:
|
|
45
|
+
throw new Error(`Unsupported database type: ${process.env.DB_TYPE}`);
|
|
46
|
+
}
|
|
47
|
+
} catch (err) {
|
|
48
|
+
log.error(`${operationType} query failed`, {
|
|
49
|
+
table,
|
|
50
|
+
error: err.message,
|
|
51
|
+
stack: err.stack ? err.stack.slice(0, 200) : undefined
|
|
52
|
+
});
|
|
53
|
+
throw err;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Process and return results based on operation type
|
|
57
|
+
switch (operationType) {
|
|
58
|
+
case 'READ':
|
|
59
|
+
return result.recordset || [];
|
|
60
|
+
case 'UPDATE':
|
|
61
|
+
return { success: true, affectedRows: result.affectedRows };
|
|
62
|
+
case 'DELETE':
|
|
63
|
+
return { success: true, affectedRows: result.affectedRows };
|
|
64
|
+
case 'CREATE':
|
|
65
|
+
return { success: true };
|
|
66
|
+
case 'TEST':
|
|
67
|
+
return result.recordset || [];
|
|
68
|
+
default:
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Executes a query against Microsoft SQL Server database.
|
|
75
|
+
*
|
|
76
|
+
* @param {Object} connection - The database connection object.
|
|
77
|
+
* @param {string} query - The SQL query string to execute.
|
|
78
|
+
* @param {Object} params - Formatted parameters for the query.
|
|
79
|
+
* @returns {Promise<Object>} Query result with recordset and affected rows.
|
|
80
|
+
*/
|
|
81
|
+
async function executeMSSQLQuery(connection, query, params) {
|
|
82
|
+
const operationType = 'MSSQL'; // Used in logs
|
|
83
|
+
|
|
84
|
+
if (log.debug) {
|
|
85
|
+
log.debug(`[${operationType}] Binding parameters`, {
|
|
86
|
+
paramCount: Object.keys(params).length,
|
|
87
|
+
hasParams: Object.keys(params).length > 0
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const request = connection.request();
|
|
92
|
+
|
|
93
|
+
// Bind each parameter with its name and value
|
|
94
|
+
for (const key in params) {
|
|
95
|
+
if (params[key]) {
|
|
96
|
+
request.input(key, params[key].type, params[key].value);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
if (log.debug) {
|
|
102
|
+
log.debug(`[${operationType}] Query executed successfully`, {
|
|
103
|
+
query: query.slice(0, 200) + '...'
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const result = await request.query(query);
|
|
108
|
+
return { recordset: result.recordset, affectedRows: result.rowsAffected };
|
|
109
|
+
} catch (error) {
|
|
110
|
+
log.error(`[${operationType}] Query execution failed`, {
|
|
111
|
+
error: error.message,
|
|
112
|
+
query: query.slice(0, 200) + '...'
|
|
113
|
+
});
|
|
114
|
+
throw error;
|
|
115
|
+
} finally {
|
|
116
|
+
await request.release();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Executes a query against MariaDB database.
|
|
122
|
+
*
|
|
123
|
+
* @param {Object} connection - The database connection object.
|
|
124
|
+
* @param {string} query - The SQL query string to execute.
|
|
125
|
+
* @param {Object} params - Formatted parameters for the query.
|
|
126
|
+
* @returns {Promise<Object>} Query result with recordset.
|
|
127
|
+
*/
|
|
128
|
+
async function executeMariaDBQuery(connection, query, params) {
|
|
129
|
+
if (log.debug) {
|
|
130
|
+
log.debug(`[MARIADB] Executing query`, {
|
|
131
|
+
paramCount: Object.keys(params).length,
|
|
132
|
+
hasParams: Object.keys(params).length > 0
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Extract parameter values in order
|
|
137
|
+
const paramValues = Object.keys(params).map(key => params[key].value);
|
|
138
|
+
|
|
139
|
+
try {
|
|
140
|
+
const result = await connection.execute(query, paramValues);
|
|
141
|
+
|
|
142
|
+
if (log.debug) {
|
|
143
|
+
log.debug('[MARIADB] Query executed successfully');
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return { recordset: result };
|
|
147
|
+
} finally {
|
|
148
|
+
log.info('MariaDB connection closed');
|
|
149
|
+
await connection.end();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
module.exports = { executeQuery, executeMSSQLQuery, executeMariaDBQuery };
|
package/README.md
DELETED