@databases/mysql
Advanced tools
Comparing version 2.0.0 to 3.0.0
/// <reference types="node" /> | ||
import sql, { SQLQuery } from '@databases/sql'; | ||
import sql, { SQLQuery, isSqlQuery } from '@databases/sql'; | ||
export type { SQLQuery }; | ||
export { sql, isSqlQuery }; | ||
export interface Connection { | ||
@@ -17,3 +19,2 @@ query(query: SQLQuery): Promise<any[]>; | ||
} | ||
export { sql, SQLQuery }; | ||
export default function connect(connectionConfig?: string | undefined): ConnectionPool; |
581
lib/index.js
"use strict"; | ||
var __awaiter = undefined && undefined.__awaiter || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { | ||
return value instanceof P ? value : new P(function (resolve) { | ||
resolve(value); | ||
}); | ||
} | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { | ||
try { | ||
step(generator.next(value)); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
} | ||
function rejected(value) { | ||
try { | ||
step(generator["throw"](value)); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
} | ||
function step(result) { | ||
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); | ||
} | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
var __await = undefined && undefined.__await || function (v) { | ||
return this instanceof __await ? (this.v = v, this) : new __await(v); | ||
}; | ||
var __asyncValues = undefined && undefined.__asyncValues || function (o) { | ||
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); | ||
var m = o[Symbol.asyncIterator], | ||
i; | ||
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { | ||
return this; | ||
}, i); | ||
function verb(n) { | ||
i[n] = o[n] && function (v) { | ||
return new Promise(function (resolve, reject) { | ||
v = o[n](v), settle(resolve, reject, v.done, v.value); | ||
}); | ||
}; | ||
} | ||
function settle(resolve, reject, d, v) { | ||
Promise.resolve(v).then(function (v) { | ||
resolve({ value: v, done: d }); | ||
}, reject); | ||
} | ||
}; | ||
var __asyncGenerator = undefined && undefined.__asyncGenerator || function (thisArg, _arguments, generator) { | ||
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); | ||
var g = generator.apply(thisArg, _arguments || []), | ||
i, | ||
q = []; | ||
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { | ||
return this; | ||
}, i; | ||
function verb(n) { | ||
if (g[n]) i[n] = function (v) { | ||
return new Promise(function (a, b) { | ||
q.push([n, v, a, b]) > 1 || resume(n, v); | ||
}); | ||
}; | ||
} | ||
function resume(n, v) { | ||
try { | ||
step(g[n](v)); | ||
} catch (e) { | ||
settle(q[0][3], e); | ||
} | ||
} | ||
function step(r) { | ||
r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); | ||
} | ||
function fulfill(value) { | ||
resume("next", value); | ||
} | ||
function reject(value) { | ||
resume("throw", value); | ||
} | ||
function settle(f, v) { | ||
if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
const url_1 = require("url"); | ||
const escape_identifier_1 = require("@databases/escape-identifier"); | ||
const mysql_config_1 = require("@databases/mysql-config"); | ||
const push_to_async_iterable_1 = require("@databases/push-to-async-iterable"); | ||
const sql_1 = require("@databases/sql"); | ||
exports.sql = sql_1.default; | ||
exports.SQLQuery = sql_1.SQLQuery; | ||
exports.isSqlQuery = sql_1.isSqlQuery; | ||
const raw_1 = require("./raw"); | ||
const stream_1 = require("stream"); | ||
const { codeFrameColumns } = require('@babel/code-frame'); | ||
const { connectionStringEnvironmentVariable } = mysql_config_1.getMySqlConfigSync(); | ||
const { | ||
codeFrameColumns | ||
} = require('@babel/code-frame'); | ||
const { | ||
connectionStringEnvironmentVariable | ||
} = mysql_config_1.getMySqlConfigSync(); | ||
const mysqlFormat = { | ||
escapeIdentifier: str => escape_identifier_1.escapeMySqlIdentifier(str), | ||
formatValue: value => ({ | ||
placeholder: '?', | ||
value | ||
}) | ||
}; | ||
function transformError(text, ex) { | ||
// TODO: consider using https://github.com/Vincit/db-errors | ||
if (ex.code === 'ER_PARSE_ERROR' && ex.sqlState === '42000' && typeof ex.sqlMessage === 'string') { | ||
const match = / near \'((?:.|\n)+)\' at line (\d+)$/.exec(ex.sqlMessage); | ||
if (match) { | ||
const index = text.indexOf(match[1]); | ||
if (index === text.lastIndexOf(match[1])) { | ||
const linesUptoStart = text.substr(0, index).split('\n'); | ||
const line = linesUptoStart.length; | ||
const start = { | ||
line, | ||
column: linesUptoStart[linesUptoStart.length - 1].length + 1 | ||
}; | ||
const linesUptoEnd = text.substr(0, index + match[1].length).split('\n'); | ||
const end = { | ||
line: linesUptoEnd.length, | ||
column: linesUptoEnd[linesUptoEnd.length - 1].length + 1 | ||
}; | ||
ex.message = ex.message.replace(/ near \'((?:.|\n)+)\' at line (\d+)$/, ` near:\n\n${codeFrameColumns(text, { start, end })}\n`); | ||
} | ||
} | ||
// TODO: consider using https://github.com/Vincit/db-errors | ||
if (ex.code === 'ER_PARSE_ERROR' && ex.sqlState === '42000' && typeof ex.sqlMessage === 'string') { | ||
const match = / near \'((?:.|\n)+)\' at line (\d+)$/.exec(ex.sqlMessage); | ||
if (match) { | ||
const index = text.indexOf(match[1]); | ||
if (index === text.lastIndexOf(match[1])) { | ||
const linesUptoStart = text.substr(0, index).split('\n'); | ||
const line = linesUptoStart.length; | ||
const start = { | ||
line, | ||
column: linesUptoStart[linesUptoStart.length - 1].length + 1 | ||
}; | ||
const linesUptoEnd = text.substr(0, index + match[1].length).split('\n'); | ||
const end = { | ||
line: linesUptoEnd.length, | ||
column: linesUptoEnd[linesUptoEnd.length - 1].length + 1 | ||
}; | ||
ex.message = ex.message.replace(/ near \'((?:.|\n)+)\' at line (\d+)$/, ` near:\n\n${codeFrameColumns(text, { | ||
start, | ||
end | ||
})}\n`); | ||
} | ||
} | ||
} | ||
} | ||
class ConnectionImplementation { | ||
constructor(conn) { | ||
this.conn = conn; | ||
constructor(conn) { | ||
this.conn = conn; | ||
} | ||
async query(query) { | ||
if (!sql_1.isSqlQuery(query)) { | ||
throw new Error('Invalid query, you must use @databases/sql to create your queries.'); | ||
} | ||
query(query) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (!(query instanceof sql_1.SQLQuery)) { | ||
throw new Error('Invalid query, you must use @databases/sql to create your queries.'); | ||
} | ||
const { text, values } = query.compileMySQL(); | ||
try { | ||
return (yield this.conn.query(text, values))[0]; | ||
} catch (ex) { | ||
transformError(text, ex); | ||
throw ex; | ||
} | ||
}); | ||
const { | ||
text, | ||
values | ||
} = query.format(mysqlFormat); | ||
try { | ||
return (await this.conn.query(text, values))[0]; | ||
} catch (ex) { | ||
transformError(text, ex); | ||
throw ex; | ||
} | ||
queryStream(query, options) { | ||
if (!(query instanceof sql_1.SQLQuery)) { | ||
throw new Error('Invalid query, you must use @databases/sql to create your queries.'); | ||
} | ||
const { text, values } = query.compileMySQL(); | ||
const highWaterMark = options && options.highWaterMark || 5; | ||
const stream = this.conn.connection.query(text, values); | ||
return push_to_async_iterable_1.default({ | ||
onData(fn) { | ||
stream.on('result', fn); | ||
}, | ||
onError(fn) { | ||
stream.on('error', fn); | ||
}, | ||
onEnd(fn) { | ||
stream.on('end', fn); | ||
}, | ||
pause: () => { | ||
this.conn.connection.pause(); | ||
}, | ||
resume: () => { | ||
this.conn.connection.resume(); | ||
}, | ||
highWaterMark | ||
}); | ||
} | ||
queryStream(query, options) { | ||
if (!sql_1.isSqlQuery(query)) { | ||
throw new Error('Invalid query, you must use @databases/sql to create your queries.'); | ||
} | ||
queryNodeStream(query, options) { | ||
if (!(query instanceof sql_1.SQLQuery)) { | ||
throw new Error('Invalid query, you must use @databases/sql to create your queries.'); | ||
} | ||
const { text, values } = query.compileMySQL(); | ||
const result = this.conn.connection.query(text, values).stream(options); | ||
// tslint:disable-next-line:no-unbound-method | ||
const on = result.on; | ||
const transformedExceptions = new Set(); | ||
return Object.assign(result, { | ||
on(event, cb) { | ||
if (event !== 'error') return on.call(this, event, cb); | ||
return on.call(this, event, ex => { | ||
// TODO: consider using https://github.com/Vincit/db-errors | ||
if (!transformedExceptions.has(ex)) { | ||
transformedExceptions.add(ex); | ||
transformError(text, ex); | ||
} | ||
cb(ex); | ||
}); | ||
} | ||
const { | ||
text, | ||
values | ||
} = query.format(mysqlFormat); | ||
const highWaterMark = options && options.highWaterMark || 5; | ||
const stream = this.conn.connection.query(text, values); | ||
return push_to_async_iterable_1.default({ | ||
onData(fn) { | ||
stream.on('result', fn); | ||
}, | ||
onError(fn) { | ||
stream.on('error', fn); | ||
}, | ||
onEnd(fn) { | ||
stream.on('end', fn); | ||
}, | ||
pause: () => { | ||
this.conn.connection.pause(); | ||
}, | ||
resume: () => { | ||
this.conn.connection.resume(); | ||
}, | ||
highWaterMark | ||
}); | ||
} | ||
queryNodeStream(query, options) { | ||
if (!sql_1.isSqlQuery(query)) { | ||
throw new Error('Invalid query, you must use @databases/sql to create your queries.'); | ||
} | ||
const { | ||
text, | ||
values | ||
} = query.format(mysqlFormat); | ||
const result = this.conn.connection.query(text, values).stream(options); // tslint:disable-next-line:no-unbound-method | ||
const on = result.on; | ||
const transformedExceptions = new Set(); | ||
return Object.assign(result, { | ||
on(event, cb) { | ||
if (event !== 'error') return on.call(this, event, cb); | ||
return on.call(this, event, ex => { | ||
// TODO: consider using https://github.com/Vincit/db-errors | ||
if (!transformedExceptions.has(ex)) { | ||
transformedExceptions.add(ex); | ||
transformError(text, ex); | ||
} | ||
cb(ex); | ||
}); | ||
} | ||
} | ||
}); | ||
} | ||
} | ||
class ConnectionPoolImplemenation { | ||
constructor(pool) { | ||
this.pool = pool; | ||
constructor(pool) { | ||
this.pool = pool; | ||
} | ||
async query(query) { | ||
if (!sql_1.isSqlQuery(query)) { | ||
throw new Error('Invalid query, you must use @databases/sql to create your queries.'); | ||
} | ||
query(query) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (!(query instanceof sql_1.SQLQuery)) { | ||
throw new Error('Invalid query, you must use @databases/sql to create your queries.'); | ||
} | ||
const { text, values } = query.compileMySQL(); | ||
try { | ||
return (yield this.pool.query(text, values))[0]; | ||
} catch (ex) { | ||
transformError(text, ex); | ||
throw ex; | ||
} | ||
}); | ||
const { | ||
text, | ||
values | ||
} = query.format(mysqlFormat); | ||
try { | ||
return (await this.pool.query(text, values))[0]; | ||
} catch (ex) { | ||
transformError(text, ex); | ||
throw ex; | ||
} | ||
queryStream(query, options) { | ||
return __asyncGenerator(this, arguments, function* queryStream_1() { | ||
var e_1, _a; | ||
const connection = yield __await(this.pool.getConnection()); | ||
const c = new ConnectionImplementation(connection); | ||
try { | ||
try { | ||
for (var _b = __asyncValues(c.queryStream(query, options)), _c; _c = yield __await(_b.next()), !_c.done;) { | ||
const record = _c.value; | ||
yield yield __await(record); | ||
} | ||
} catch (e_1_1) { | ||
e_1 = { error: e_1_1 }; | ||
} finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) yield __await(_a.call(_b)); | ||
} finally { | ||
if (e_1) throw e_1.error; | ||
} | ||
} | ||
} finally { | ||
connection.release(); | ||
} | ||
}); | ||
} | ||
async *queryStream(query, options) { | ||
const connection = await this.pool.getConnection(); | ||
const c = new ConnectionImplementation(connection); | ||
try { | ||
for await (const record of c.queryStream(query, options)) { | ||
yield record; | ||
} | ||
} finally { | ||
connection.release(); | ||
} | ||
queryNodeStream(query, options) { | ||
const stream = new stream_1.PassThrough({ objectMode: true, highWaterMark: 2 }); | ||
this.pool.getConnection().then(connection => { | ||
const c = new ConnectionImplementation(connection); | ||
let released = false; | ||
return c.queryNodeStream(query, options).on('fields', fields => { | ||
stream.emit('fields', fields); | ||
}).on('error', err => { | ||
if (!released) { | ||
released = true; | ||
connection.release(); | ||
} | ||
stream.emit('error', err); | ||
}).on('end', () => { | ||
if (!released) { | ||
released = true; | ||
connection.release(); | ||
} | ||
stream.emit('end'); | ||
}).pipe(stream); | ||
}).catch(ex => stream.emit('error', ex)); | ||
return stream; | ||
} | ||
queryNodeStream(query, options) { | ||
const stream = new stream_1.PassThrough({ | ||
objectMode: true, | ||
highWaterMark: 2 | ||
}); | ||
this.pool.getConnection().then(connection => { | ||
const c = new ConnectionImplementation(connection); | ||
let released = false; | ||
return c.queryNodeStream(query, options).on('fields', fields => { | ||
stream.emit('fields', fields); | ||
}).on('error', err => { | ||
if (!released) { | ||
released = true; | ||
connection.release(); | ||
} | ||
stream.emit('error', err); | ||
}).on('end', () => { | ||
if (!released) { | ||
released = true; | ||
connection.release(); | ||
} | ||
stream.emit('end'); | ||
}).pipe(stream); | ||
}).catch(ex => stream.emit('error', ex)); | ||
return stream; | ||
} | ||
async task(fn) { | ||
const connection = await this.pool.getConnection(); | ||
try { | ||
const result = await fn(new ConnectionImplementation(connection)); | ||
return result; | ||
} finally { | ||
connection.release(); | ||
} | ||
task(fn) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const connection = yield this.pool.getConnection(); | ||
try { | ||
const result = yield fn(new ConnectionImplementation(connection)); | ||
return result; | ||
} finally { | ||
connection.release(); | ||
} | ||
}); | ||
} | ||
async tx(fn) { | ||
const connection = await this.pool.getConnection(); | ||
let completed = false; | ||
try { | ||
await connection.beginTransaction(); | ||
let result; | ||
try { | ||
result = await fn(new ConnectionImplementation(connection)); | ||
} catch (ex) { | ||
await connection.rollback(); | ||
completed = true; | ||
throw ex; | ||
} | ||
await connection.commit(); | ||
completed = true; | ||
return result; | ||
} finally { | ||
if (completed) { | ||
connection.release(); | ||
} else { | ||
connection.destroy(); | ||
} | ||
} | ||
tx(fn) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const connection = yield this.pool.getConnection(); | ||
let completed = false; | ||
try { | ||
yield connection.beginTransaction(); | ||
let result; | ||
try { | ||
result = yield fn(new ConnectionImplementation(connection)); | ||
} catch (ex) { | ||
yield connection.rollback(); | ||
completed = true; | ||
throw ex; | ||
} | ||
yield connection.commit(); | ||
completed = true; | ||
return result; | ||
} finally { | ||
if (completed) { | ||
connection.release(); | ||
} else { | ||
connection.destroy(); | ||
} | ||
} | ||
}); | ||
} | ||
dispose() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
yield this.pool.end(); | ||
}); | ||
} | ||
} | ||
async dispose() { | ||
await this.pool.end(); | ||
} | ||
} | ||
function connect(connectionConfig = process.env[connectionStringEnvironmentVariable]) { | ||
if (!connectionConfig) { | ||
throw new Error('You must provide a connection string for @databases/mysql. You can ' + 'either pass one directly to the createConnection call or set ' + `the ${connectionStringEnvironmentVariable} environment variable.`); | ||
} | ||
validateMySqlUrl(connectionConfig); | ||
const pool = raw_1.default({ | ||
uri: connectionConfig, | ||
authSwitchHandler({ pluginName, pluginData }, cb) { | ||
const err = new Error(`Unknown AuthSwitchRequest plugin name ${pluginName}`); | ||
err.fatal = true; | ||
cb(err); | ||
}, | ||
multipleStatements: true | ||
}); | ||
return new ConnectionPoolImplemenation(pool); | ||
if (!connectionConfig) { | ||
throw new Error('You must provide a connection string for @databases/mysql. You can ' + 'either pass one directly to the createConnection call or set ' + `the ${connectionStringEnvironmentVariable} environment variable.`); | ||
} | ||
validateMySqlUrl(connectionConfig); | ||
const pool = raw_1.default({ | ||
uri: connectionConfig, | ||
authSwitchHandler({ | ||
pluginName, | ||
pluginData | ||
}, cb) { | ||
const err = new Error(`Unknown AuthSwitchRequest plugin name ${pluginName}`); | ||
err.fatal = true; | ||
cb(err); | ||
}, | ||
multipleStatements: true | ||
}); | ||
return new ConnectionPoolImplemenation(pool); | ||
} | ||
exports.default = connect; | ||
function validateMySqlUrl(urlString) { | ||
let url; | ||
try { | ||
url = new url_1.URL(urlString); | ||
} catch (ex) { | ||
throw new Error('Invalid MySQL connection string, expected a URI: ' + urlString); | ||
} | ||
if (url.protocol !== 'mysqlx:' && url.protocol !== 'mysql:') { | ||
throw new Error('Invalid MySQL connection string, expected protocol to be "mysql" or "mysqlx": ' + urlString); | ||
} | ||
let url; | ||
try { | ||
url = new url_1.URL(urlString); | ||
} catch (ex) { | ||
throw new Error('Invalid MySQL connection string, expected a URI: ' + urlString); | ||
} | ||
if (url.protocol !== 'mysqlx:' && url.protocol !== 'mysql:') { | ||
throw new Error('Invalid MySQL connection string, expected protocol to be "mysql" or "mysqlx": ' + urlString); | ||
} | ||
} | ||
module.exports = connect; | ||
module.exports.default = connect; | ||
module.exports.sql = sql_1.default; | ||
module.exports.SQLQuery = sql_1.SQLQuery; | ||
//# sourceMappingURL=index.js.map | ||
module.exports = Object.assign(connect, { | ||
default: connect, | ||
sql: sql_1.default, | ||
isSqlQuery: sql_1.isSqlQuery | ||
}); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
const mysql = require('mysql2/promise'); | ||
exports.default = mysql.createPool; | ||
//# sourceMappingURL=raw.js.map | ||
exports.default = mysql.createPool; |
{ | ||
"name": "@databases/mysql", | ||
"version": "2.0.0", | ||
"version": "3.0.0", | ||
"description": "", | ||
@@ -9,5 +9,6 @@ "main": "./lib/index.js", | ||
"@babel/code-frame": "^7.0.0", | ||
"@databases/mysql-config": "^1.0.1", | ||
"@databases/push-to-async-iterable": "^1.0.0", | ||
"@databases/sql": "^2.0.0", | ||
"@databases/escape-identifier": "^1.0.0", | ||
"@databases/mysql-config": "^2.0.0", | ||
"@databases/push-to-async-iterable": "^2.0.0", | ||
"@databases/sql": "^3.0.0", | ||
"@types/mysql": "^2.15.5", | ||
@@ -14,0 +15,0 @@ "mysql2": "^1.6.4" |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
25982
7
429
1
+ Added@databases/escape-identifier@1.0.3(transitive)
+ Added@databases/mysql-config@2.1.0(transitive)
+ Added@databases/push-to-async-iterable@2.0.0(transitive)
+ Added@databases/sql@3.3.0(transitive)
+ Added@databases/validate-unicode@1.0.0(transitive)
+ Addedfuntypes@4.2.0(transitive)
- Removed@databases/mysql-config@1.0.1(transitive)
- Removed@databases/push-to-async-iterable@1.0.0(transitive)
- Removed@databases/sql@2.2.0(transitive)
- Removed@types/cosmiconfig@5.0.3(transitive)
- Removedajv@6.12.6(transitive)
- Removedfast-deep-equal@3.1.3(transitive)
- Removedfast-json-stable-stringify@2.1.0(transitive)
- Removedjson-schema-traverse@0.4.1(transitive)
- Removedpg-minify@0.5.5(transitive)
- Removedpunycode@2.3.1(transitive)
- Removeduri-js@4.4.1(transitive)
Updated@databases/sql@^3.0.0