|
3 | 3 | */ |
4 | 4 |
|
5 | 5 | import { SQLiteCloudConfig, SQLiteCloudError, ErrorCallback, ResultsCallback } from './types' |
6 | | -import { validateConfiguration } from './utilities' |
| 6 | +import { validateConfiguration, prepareSql } from './utilities' |
7 | 7 | import { OperationsQueue } from './queue' |
8 | | -import { anonimizeCommand } from './utilities' |
| 8 | +import { anonimizeCommand, getUpdateResults } from './utilities' |
9 | 9 |
|
10 | 10 | /** |
11 | 11 | * Base class for SQLiteCloudConnection handles basics and defines methods. |
@@ -102,6 +102,49 @@ export abstract class SQLiteCloudConnection { |
102 | 102 | return this |
103 | 103 | } |
104 | 104 |
|
| 105 | + /** |
| 106 | + * Sql is a promise based API for executing SQL statements. You can |
| 107 | + * pass a simple string with a SQL statement or a template string |
| 108 | + * using backticks and parameters in ${parameter} format. These parameters |
| 109 | + * will be properly escaped and quoted like when using a prepared statement. |
| 110 | + * @param sql A sql string or a template string in `backticks` format |
| 111 | + * @returns An array of rows in case of selections or an object with |
| 112 | + * metadata in case of insert, update, delete. |
| 113 | + */ |
| 114 | + public async sql(sql: TemplateStringsArray | string, ...values: any[]): Promise<any> { |
| 115 | + let preparedSql = '' |
| 116 | + |
| 117 | + // sql is a TemplateStringsArray, the 'raw' property is specific to TemplateStringsArray |
| 118 | + if (Array.isArray(sql) && 'raw' in sql) { |
| 119 | + sql.forEach((string, i) => { |
| 120 | + preparedSql += string + (i < values.length ? '?' : '') |
| 121 | + }) |
| 122 | + preparedSql = prepareSql(preparedSql, ...values) |
| 123 | + } else { |
| 124 | + if (typeof sql === 'string') { |
| 125 | + if (values?.length > 0) { |
| 126 | + preparedSql = prepareSql(sql, ...values) |
| 127 | + } else { |
| 128 | + preparedSql = sql |
| 129 | + } |
| 130 | + } else { |
| 131 | + throw new Error('Invalid sql') |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + return new Promise((resolve, reject) => { |
| 136 | + this.sendCommands(preparedSql, (error, results) => { |
| 137 | + if (error) { |
| 138 | + reject(error) |
| 139 | + } else { |
| 140 | + // metadata for operations like insert, update, delete? |
| 141 | + const context = getUpdateResults(results) |
| 142 | + resolve(context ? context : results) |
| 143 | + } |
| 144 | + }) |
| 145 | + }) |
| 146 | + } |
| 147 | + |
105 | 148 | /** Disconnect from server, release transport. */ |
106 | 149 | public abstract close(): this |
107 | 150 | } |
0 commit comments