Skip to content

Commit 5b94712

Browse files
documentation for raw query updated
1 parent d44a194 commit 5b94712

File tree

2 files changed

+67
-31
lines changed

2 files changed

+67
-31
lines changed

readme2.md

+58-16
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ const { UnSQL } = require('unsql')
161161
const pool = require('path/to/your/db/service')
162162

163163
/**
164-
* @class User
164+
* @class
165165
* @extends UnSQL
166166
*/
167167
class User extends UnSQL {
@@ -191,7 +191,7 @@ import { UnSQL } from 'unsql'
191191
import { pool } from 'path/to/your/db/service'
192192

193193
/**
194-
* @class User
194+
* @class
195195
* @extends UnSQL
196196
*/
197197
export class User extends UnSQL {
@@ -306,7 +306,7 @@ Each of these properties is explained below:
306306
}
307307
}
308308
],
309-
join: [{ table: 'order_history', using: ['orderId'] }] // ref. of join object
309+
join: [{ table: 'order_items', using: ['orderId'] }] // ref. of join object
310310
})
311311
```
312312
**Please note:**
@@ -458,17 +458,55 @@ Each of these properties is explained below:
458458

459459
### 3.4 Raw Query Method
460460

461-
`rawQuery` method is the most powerful method among all, unlike other methods that are limited to the base mapping, this method is not tied to any particular table, but utilizes the connection pool to execute queries on that database itself. It is capable of executing any and all types of queries including DDL, DML etc. It supports normal queries as well as placeholders:
462-
- In `mysql`:
463-
- Positional placeholders: `??`, `?`,
464-
- Named placeholders: `:namedVariable`,
465-
- user defined variables: `@userVariable`,
466-
- In `postgresql`:
467-
- Positional placeholder: `$1`, `$2`, `$3`...
468-
- In `sqlite`:
469-
- Positional placeholder: `?`,
470-
- Named placeholders: `:namedVariable` or `$namedVariable` or `@namedVariable`,
471-
- Indexed placeholder: `$1`, `$2`, `$3`... or `?1`, `?2`, `?3`...
461+
`rawQuery` method is the most powerful method among all, unlike other methods that are limited to the base mapping, this method is not tied to any particular table, but utilizes the connection pool to execute queries on that database itself. It is capable of executing any and all types of queries including **DDL, DML etc** (In `sqlite`, set `methodType: 'exec'`).
462+
463+
It supports various types of methods (as mentioned below) for `mysql` and `sqlite`, each method has specific capabilities:
464+
465+
| Method Type | Dialect | Description |
466+
| ----------- | -------- | ------------------------------------------------------------------------------------- |
467+
| `execute` | `mysql` | supports **Session Manager**, and all type of queries (DML, DDL etc.) |
468+
| `query` | `mysql` | supports multiple sql statements in single query string, and all type of queries |
469+
| `all` | `sqlite` | supports **Session Manager and SELECT query** returns *record(s) as array* |
470+
| `run` | `sqlite` | supports **Session Manager, INSERT and UPDATE query**, *returns insertId and changes* |
471+
| `exec` | `sqlite` | supports **CREATE, DROP ALTER and similar query**, returns nothing |
472+
473+
It supports normal queries as well as placeholders:
474+
- In `mysql`:
475+
- Positional placeholders: `??`, `?`,
476+
- Named placeholders: `:namedVariable`,
477+
- user defined variables: `@userVariable`,
478+
- In `postgresql`:
479+
- Positional placeholder: `$1`, `$2`, `$3`...
480+
- In `sqlite`:
481+
- Positional placeholder: `?`,
482+
- Named placeholders: `:namedVariable` or `$namedVariable` or `@namedVariable`,
483+
- Indexed placeholder: `$1`, `$2`, `$3`... or `?1`, `?2`, `?3`...
484+
485+
```javascript
486+
// Sample: (dialect: 'mysql')
487+
const response = await User.rawQuery({ // here user model is used just to utilize 'pool'
488+
sql: `CREATE TABLE IF NOT EXISTS users (
489+
userId INT(11) PRIMARY KEY AUTO_INCREMENT,
490+
firstName VARCHAR(45) DEFAULT NULL,
491+
lastName VARCHAR(45) DEFAULT NULL,
492+
email VARCHAR(255) UNIQUE DEFAULT NOT NULL,
493+
password VARCHAR(255) DEFAULT NOT NULL,
494+
createdOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
495+
lastUpdatedOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
496+
status TINYINT(1) DEFAULT 1
497+
);
498+
CREATE TABLE IF NOT EXISTS order_history (
499+
orderId INT(11) PRIMARY KEY AUTO_INCREMENT,
500+
amount DECIMAL (10,2) DEFAULT 0.00,
501+
coupon VARCHAR(45) DEFAULT NULL,
502+
discount DECIMAL (10,2) DEFAULT 0.00,
503+
createdOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
504+
lastUpdatedOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
505+
status TINYINT(1) DEFAULT 0
506+
);`,
507+
methodType: 'query' // this supports multiple statements in single query string
508+
})
509+
```
472510

473511
### 3.5 Export Method
474512

@@ -1118,8 +1156,8 @@ All objects are explained below:
11181156
value: {
11191157
orderId: 'orderId',
11201158
purchaseDate: 'createdOn',
1121-
orderAmount: 'totalAmount',
1122-
orderStatus: 'orderStatus'
1159+
total: 'amount',
1160+
status: 'status'
11231161
},
11241162
table: 'order_history',
11251163
where: {
@@ -1530,6 +1568,10 @@ router.post('/orders', async (req,res) => {
15301568

15311569
UnSQL uses `#` as prefix to identify if string is plain text, or column name if string does not start with `#`.
15321570

1571+
### 7.2 What will happen if secret/iv/sha is defined inside config, encryption and decrypt/encrypt property?
1572+
1573+
When configurations like `secret` | `iv` | `sha` are declared in all places, `encryption` at method level will override `encryption` at `config`, similarly `decrypt` / `encrypt` inside special object will override all other.
1574+
15331575
### Support
15341576
![npm](https://img.shields.io/badge/npm-CB3837?style=for-the-badge&logo=npm&logoColor=white)
15351577
![Yarn](https://img.shields.io/badge/yarn-%232C8EBB.svg?style=for-the-badge&logo=yarn&logoColor=white)

unsql.js

+9-15
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ class UnSQL {
2929
static _variableCount = 0
3030
static isMySQL = false
3131
static isPostgreSQL = false
32-
static SQLite = false
32+
static isSQLite = false
3333

3434
/**
3535
* Find method
@@ -362,13 +362,13 @@ class UnSQL {
362362
* @param {import("./defs/types").EncryptionConfig} [rawQueryParams.encryption] (optional) enables debug mode
363363
* @param {import("./defs/types").DebugTypes} [rawQueryParams.debug] (optional) enables debug mode
364364
* @param {Object} [rawQueryParams.session] (optional) global session reference for transactions and rollback
365-
* @param {'run'|'all'|'exec'} [rawQueryParams.methodType=all] (optional) used only with 'sqlite'
365+
* @param {'run'|'all'|'exec'|'execute'|'query'} [rawQueryParams.methodType=all] (optional) used only with 'sqlite'
366366
* @returns {Promise<{success:boolean, error?:object, result?:object}>} Promise resolving with two parameters: boolean 'success' and either 'error' or 'result'
367367
*/
368-
static async rawQuery({ sql = '', values = [], debug = false, encryption = undefined, session = undefined, methodType = 'all' }) {
368+
static async rawQuery({ sql = '', values = [], debug = false, encryption = undefined, session = undefined, methodType = this?.isSQLite ? 'all' : 'execute' }) {
369369
switch (this?.config?.dialect) {
370370
case 'mysql':
371-
return await executeMySQL({ sql, values, encryption, debug, session, config: this?.config, debugMessage: `Executed raw query in` })
371+
return await executeMySQL({ sql, values, encryption, debug, session, config: this?.config, methodType, debugMessage: `Executed raw query in` })
372372
case 'postgresql':
373373
return await executePostgreSQL({ sql, values, debug, config: this?.config, debugMessage: `Executed raw query in` })
374374
case 'sqlite':
@@ -498,30 +498,28 @@ class UnSQL {
498498
* @param {import("./defs/types").DebugTypes} [options.debug] enables debug mode
499499
* @param {Object} [options.session] global session reference for transactions and rollback
500500
* @param {Object} [options.config] global configuration object
501+
* @param {'all'|'run'|'exec'|'execute'|'query'} [options.methodType=execute] global configuration object
501502
* @param {string} [options.debugMessage] global configuration object
502503
* @param {import("./defs/types").EncryptionConfig} [options.encryption] enables encryption
503504
* @returns {Promise<{success:false, error:*}|{success:true, result:*}>} Promise resolving with two parameters: boolean 'success' and either 'error' or 'results'
504505
*/
505-
const executeMySQL = async ({ sql, values, debug = false, session = undefined, config, encryption = undefined, debugMessage = '' }) => {
506-
506+
const executeMySQL = async ({ sql, values, debug = false, session = undefined, config, methodType = 'execute', encryption = undefined, debugMessage = '' }) => {
507507
const conn = await (session?.conn || config?.pool?.getConnection() || config?.connection)
508-
509-
510508
try {
511509
if (!session?.conn) await conn?.beginTransaction()
512510
if (debug === 'benchmark' || debug === 'benchmark-query' || debug === 'benchmark-error' || debug === true) console.time(`${colors.blue}UnSQL benchmark:${colors.reset} ${colors.cyan}${debugMessage}${colors.reset}`)
513511
if ((encryption?.mode && encryption?.mode != config?.dbEncryptionMode) || (config?.encryption?.mode && config?.encryption?.mode != config?.dbEncryptionMode)) {
514512
try {
515513
const encPrepared = await conn.format('SET block_encryption_mode = ?', [encryption?.mode || config?.encryption?.mode])
516-
const [encResp] = await conn?.execute(encPrepared)
514+
const [encResp] = await conn?.[methodType](encPrepared)
517515
if (!session?.conn) await conn?.commit()
518516
} catch (error) {
519517
throw { message: `[Error]: ${error?.message} `, cause: `While setting encryption mode to: '${encryption?.mode || config?.encryption?.mode}'` }
520518
}
521519
}
522520
const prepared = conn.format(sql, values)
523521
handleQueryDebug(debug, sql, values, prepared)
524-
const [result] = await conn.execute(prepared)
522+
const [result] = await conn[methodType](prepared)
525523
if (!session?.conn) await conn?.commit()
526524
if (debug) console.info(colors.green, 'Query executed successfully!\n', colors.reset)
527525
if (debug === 'benchmark' || debug === 'benchmark-query' || debug === 'benchmark-error' || debug === true) console.timeEnd(`${colors.blue}UnSQL benchmark:${colors.reset} ${colors.cyan}${debugMessage}${colors.reset}\n`)
@@ -533,7 +531,6 @@ const executeMySQL = async ({ sql, values, debug = false, session = undefined, c
533531
} finally {
534532
if (config?.pool && !session?.conn) await conn?.release()
535533
}
536-
537534
}
538535

539536
/**
@@ -545,11 +542,8 @@ const executeMySQL = async ({ sql, values, debug = false, session = undefined, c
545542
* @author Siddharth Tiwari <[email protected]>
546543
*/
547544
const executePostgreSQL = async ({ sql, values, debug = false, config, session = undefined, timezone = undefined, encryption = undefined, debugMessage = '' }) => {
548-
549545
const client = await (session?.conn || config?.pool?.connect())
550-
551546
const isBenchmarking = debug === 'benchmark' || debug === 'benchmark-query' || debug === 'benchmark-error' || debug === true
552-
553547
handleQueryDebug(debug, sql, values)
554548
try {
555549
if (!session?.conn) await client.query('BEGIN')
@@ -580,7 +574,7 @@ const executePostgreSQL = async ({ sql, values, debug = false, config, session =
580574
* @param {Array} options.values
581575
* @param {import("./defs/types").DebugTypes} [options.debug]
582576
* @param {import("./defs/types").ConfigObject} [options.config]
583-
* @param {'all'|'run'|'exec'} [options.methodType=all]
577+
* @param {'all'|'run'|'exec'|'execute'|'query'} [options.methodType=all]
584578
* @param {string} [options.debugMessage]
585579
* @param {*} [options.session]
586580
* @returns {Promise<{success:boolean, result?:Array, insertId?:number, changes?:number, error?:*}>}

0 commit comments

Comments
 (0)