Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@databases/mysql

Package Overview
Dependencies
Maintainers
1
Versions
23
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@databases/mysql - npm Package Compare versions

Comparing version 5.0.0 to 5.1.0

lib/tsconfig.tsbuildinfo

117

lib/__tests__/bigint.test.mysql.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const __1 = require("..");
jest.setTimeout(30000);
beforeAll(async () => {
const db = __1.default();
await db.query(__1.sql`CREATE TABLE bigint_test_bigints (id INT NOT NULL PRIMARY KEY, test_value BIGINT NOT NULL);`);
await db.query(__1.sql`
const db = __1.default();
await db.query(__1.sql `CREATE TABLE bigint_test_bigints (id INT NOT NULL PRIMARY KEY, test_value BIGINT NOT NULL);`);
await db.query(__1.sql `
INSERT INTO bigint_test_bigints (id, test_value)

@@ -22,82 +16,47 @@ VALUES (1, ${1}),

`);
await db.dispose();
await db.dispose();
});
test('bigints as number', async () => {
const db = __1.default({
bigIntMode: 'number'
});
const result = await db.query(__1.sql`
const db = __1.default({ bigIntMode: 'number' });
const result = await db.query(__1.sql `
SELECT id, test_value from bigint_test_bigints;
`);
expect(result).toEqual([{
id: 1,
test_value: 1
}, {
id: 2,
test_value: 2
}, {
id: 3,
test_value: 2000
}, {
id: 4,
test_value: Number.MAX_SAFE_INTEGER
}, // N.B. this value is inexact:
{
id: 5,
test_value: 10000000000000000
}]);
await db.dispose();
expect(result).toEqual([
{ id: 1, test_value: 1 },
{ id: 2, test_value: 2 },
{ id: 3, test_value: 2000 },
{ id: 4, test_value: Number.MAX_SAFE_INTEGER },
// N.B. this value is inexact:
{ id: 5, test_value: 10000000000000000 },
]);
await db.dispose();
});
test('bigints as string', async () => {
const db = __1.default({
bigIntMode: 'string'
});
const result = await db.query(__1.sql`
const db = __1.default({ bigIntMode: 'string' });
const result = await db.query(__1.sql `
SELECT id, test_value from bigint_test_bigints;
`);
expect(result).toEqual([{
id: 1,
test_value: '1'
}, {
id: 2,
test_value: '2'
}, {
id: 3,
test_value: '2000'
}, {
id: 4,
test_value: Number.MAX_SAFE_INTEGER.toString()
}, {
id: 5,
test_value: '9999999999999999'
}]);
await db.dispose();
expect(result).toEqual([
{ id: 1, test_value: '1' },
{ id: 2, test_value: '2' },
{ id: 3, test_value: '2000' },
{ id: 4, test_value: Number.MAX_SAFE_INTEGER.toString() },
{ id: 5, test_value: '9999999999999999' },
]);
await db.dispose();
});
test('bigints as BigInt', async () => {
const db = __1.default({
bigIntMode: 'bigint'
});
const result = await db.query(__1.sql`
const db = __1.default({ bigIntMode: 'bigint' });
const result = await db.query(__1.sql `
SELECT id, test_value from bigint_test_bigints;
`);
expect(result).toEqual([{
id: 1,
test_value: BigInt('1')
}, {
id: 2,
test_value: BigInt('2')
}, {
id: 3,
test_value: BigInt('2000')
}, {
id: 4,
test_value: BigInt(Number.MAX_SAFE_INTEGER.toString())
}, {
id: 5,
test_value: BigInt('9999999999999999')
}]);
await db.dispose();
});
expect(result).toEqual([
{ id: 1, test_value: BigInt('1') },
{ id: 2, test_value: BigInt('2') },
{ id: 3, test_value: BigInt('2000') },
{ id: 4, test_value: BigInt(Number.MAX_SAFE_INTEGER.toString()) },
{ id: 5, test_value: BigInt('9999999999999999') },
]);
await db.dispose();
});
//# sourceMappingURL=bigint.test.mysql.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const __1 = require("..");
jest.setTimeout(30000);
beforeAll(async () => {
const db = __1.default();
await db.query(__1.sql`CREATE TABLE booleans_test_booleans (id INT NOT NULL PRIMARY KEY, test_value BOOLEAN NOT NULL);`);
await db.query(__1.sql`
const db = __1.default();
await db.query(__1.sql `CREATE TABLE booleans_test_booleans (id INT NOT NULL PRIMARY KEY, test_value BOOLEAN NOT NULL);`);
await db.query(__1.sql `
INSERT INTO booleans_test_booleans (id, test_value)

@@ -20,43 +14,28 @@ VALUES (1, ${true}),

`);
await db.dispose();
await db.dispose();
});
test('booleans as number', async () => {
const db = __1.default({
tinyIntMode: 'number'
});
const result = await db.query(__1.sql`
const db = __1.default({ tinyIntMode: 'number' });
const result = await db.query(__1.sql `
SELECT id, test_value from booleans_test_booleans;
`);
expect(result).toEqual([{
id: 1,
test_value: 1
}, {
id: 2,
test_value: 0
}, {
id: 3,
test_value: 42
}]);
await db.dispose();
expect(result).toEqual([
{ id: 1, test_value: 1 },
{ id: 2, test_value: 0 },
{ id: 3, test_value: 42 },
]);
await db.dispose();
});
test('booleans as boolean', async () => {
const db = __1.default({
tinyIntMode: 'boolean'
});
const result = await db.query(__1.sql`
const db = __1.default({ tinyIntMode: 'boolean' });
const result = await db.query(__1.sql `
SELECT id, test_value from booleans_test_booleans;
`);
expect(result).toEqual([{
id: 1,
test_value: true
}, {
id: 2,
test_value: false
}, {
id: 3,
test_value: true
}]);
await db.dispose();
});
expect(result).toEqual([
{ id: 1, test_value: true },
{ id: 2, test_value: false },
{ id: 3, test_value: true },
]);
await db.dispose();
});
//# sourceMappingURL=booleans.test.mysql.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const __1 = require("..");
const mysql = require('mysql2/promise');
jest.setTimeout(30000);
const db = __1.default();
const rawConnection = mysql.createConnection({
uri: process.env.MYSQL_URL,
dateStrings: true
uri: process.env.MYSQL_URL,
dateStrings: true,
});
const rawConnection2 = mysql.createConnection({
uri: process.env.MYSQL_URL,
dateStrings: true
uri: process.env.MYSQL_URL,
dateStrings: true,
});
beforeAll(async () => {
await (await rawConnection).query(`SET time_zone = "+00:00";`);
await (await rawConnection).query(`SET time_zone = "+00:00";`);
});
afterAll(async () => {
await db.dispose();
(await rawConnection).close();
(await rawConnection2).close();
await db.dispose();
(await rawConnection).close();
(await rawConnection2).close();
});
test('dates', async () => {
await db.task(async db => {
await db.query(__1.sql`SET time_zone = "+00:00";`);
await db.query(__1.sql`
await db.task(async (db) => {
await db.query(__1.sql `SET time_zone = "+00:00";`);
await db.query(__1.sql `
DROP TABLE IF EXISTS dates_test_dates;

@@ -49,4 +41,4 @@ CREATE TABLE dates_test_dates (

`);
const sampleDate = new Date('2000-06-03T05:40:10.123Z');
await db.query(__1.sql`
const sampleDate = new Date('2000-06-03T05:40:10.123Z');
await db.query(__1.sql `
INSERT INTO dates_test_dates (id, a, b, c, d)

@@ -56,3 +48,3 @@ VALUES (1, ${sampleDate}, ${sampleDate}, ${sampleDate}, ${2000}),

`);
await db.query(__1.sql`
await db.query(__1.sql `
INSERT INTO dates_test_pure_dates (id, date_value)

@@ -64,75 +56,87 @@ VALUES (1, ${'2000-06-03'}),

`);
expect((await (await rawConnection).query(`SELECT * from dates_test_dates`))[0]).toEqual([{
a: '2000-06-03 15:10:10',
b: '2000-06-03 15:10:10',
c: '15:10:10',
d: 2000,
id: 1
}, {
a: '2000-06-03 05:40:10',
b: '2000-06-03 05:40:10',
c: '05:40:10',
d: 2000,
id: 2
}]);
expect((await (await rawConnection).query(`SELECT * from dates_test_pure_dates`))[0]).toEqual([{
date_value: '2000-06-03',
id: 1
}, {
date_value: '2000-06-03',
id: 2
}, {
date_value: '2000-06-03',
id: 3
}, {
date_value: '2000-06-04',
id: 4
}]);
const result = await db.query(__1.sql`
expect((await (await rawConnection).query(`SELECT * from dates_test_dates`))[0]).toEqual([
{
a: '2000-06-03 15:10:10',
b: '2000-06-03 15:10:10',
c: '15:10:10',
d: 2000,
id: 1,
},
{
a: '2000-06-03 05:40:10',
b: '2000-06-03 05:40:10',
c: '05:40:10',
d: 2000,
id: 2,
},
]);
expect((await (await rawConnection).query(`SELECT * from dates_test_pure_dates`))[0]).toEqual([
{
date_value: '2000-06-03',
id: 1,
},
{
date_value: '2000-06-03',
id: 2,
},
{
date_value: '2000-06-03',
id: 3,
},
{
date_value: '2000-06-04',
id: 4,
},
]);
const result = await db.query(__1.sql `
SELECT * from dates_test_dates;
`);
expect(result).toEqual([{
a: new Date('2000-06-03T05:40:10.000Z'),
b: new Date('2000-06-03T05:40:10.000Z'),
c: '15:10:10',
d: 2000,
id: 1
}, {
a: new Date('2000-06-02T20:10:10.000Z'),
b: new Date('2000-06-02T20:10:10.000Z'),
c: '05:40:10',
d: 2000,
id: 2
}]);
expect(await db.query(__1.sql`
expect(result).toEqual([
{
a: new Date('2000-06-03T05:40:10.000Z'),
b: new Date('2000-06-03T05:40:10.000Z'),
c: '15:10:10',
d: 2000,
id: 1,
},
{
a: new Date('2000-06-02T20:10:10.000Z'),
b: new Date('2000-06-02T20:10:10.000Z'),
c: '05:40:10',
d: 2000,
id: 2,
},
]);
expect(await db.query(__1.sql `
SELECT * from dates_test_pure_dates;
`)).toEqual([{
date_value: new Date('2000-06-02T14:30:00.000Z'),
id: 1
}, {
date_value: new Date('2000-06-02T14:30:00.000Z'),
id: 2
}, {
date_value: new Date('2000-06-02T14:30:00.000Z'),
id: 3
}, {
date_value: new Date('2000-06-03T14:30:00.000Z'),
id: 4
}]);
});
`)).toEqual([
{
date_value: new Date('2000-06-02T14:30:00.000Z'),
id: 1,
},
{
date_value: new Date('2000-06-02T14:30:00.000Z'),
id: 2,
},
{
date_value: new Date('2000-06-02T14:30:00.000Z'),
id: 3,
},
{
date_value: new Date('2000-06-03T14:30:00.000Z'),
id: 4,
},
]);
});
});
test('dates with timezone set to local', async () => {
// setting timezone on another connection has no impact
await (await rawConnection2).query(`SET time_zone = "+03:00";`);
const db = __1.default({
timeZone: 'local'
});
await db.task(async db => {
// Setting timezone to match our local timezone means that fields of type `TIMESTAMP` are stored
// as UTC, and then returned as local time. This means we are now storing the correct times for
// `TIMESTAMP` fields.
// The `rawConnection` is still set to UTC, so you can see the actual UTC values being stored.
await db.query(__1.sql`
// setting timezone on another connection has no impact
await (await rawConnection2).query(`SET time_zone = "+03:00";`);
const db = __1.default({ timeZone: 'local' });
await db.task(async (db) => {
// Setting timezone to match our local timezone means that fields of type `TIMESTAMP` are stored
// as UTC, and then returned as local time. This means we are now storing the correct times for
// `TIMESTAMP` fields.
// The `rawConnection` is still set to UTC, so you can see the actual UTC values being stored.
await db.query(__1.sql `
DROP TABLE IF EXISTS dates_test_dates;

@@ -152,4 +156,4 @@ CREATE TABLE dates_test_dates (

`);
const sampleDate = new Date('2000-06-03T05:40:10.123Z');
await db.query(__1.sql`
const sampleDate = new Date('2000-06-03T05:40:10.123Z');
await db.query(__1.sql `
INSERT INTO dates_test_dates (id, a, b, c, d)

@@ -159,3 +163,3 @@ VALUES (1, ${sampleDate}, ${sampleDate}, ${sampleDate}, ${2000}),

`);
await db.query(__1.sql`
await db.query(__1.sql `
INSERT INTO dates_test_pure_dates (id, date_value)

@@ -167,72 +171,84 @@ VALUES (1, ${'2000-06-03'}),

`);
expect((await (await rawConnection).query(`SELECT * from dates_test_dates`))[0]).toEqual([{
a: '2000-06-03 15:10:10',
b: '2000-06-03 05:40:10',
c: '15:10:10',
d: 2000,
id: 1
}, {
a: '2000-06-03 05:40:10',
b: '2000-06-02 20:10:10',
c: '05:40:10',
d: 2000,
id: 2
}]);
expect((await (await rawConnection).query(`SELECT * from dates_test_pure_dates`))[0]).toEqual([{
date_value: '2000-06-03',
id: 1
}, {
date_value: '2000-06-03',
id: 2
}, {
date_value: '2000-06-03',
id: 3
}, {
date_value: '2000-06-04',
id: 4
}]);
const result = await db.query(__1.sql`
expect((await (await rawConnection).query(`SELECT * from dates_test_dates`))[0]).toEqual([
{
a: '2000-06-03 15:10:10',
b: '2000-06-03 05:40:10',
c: '15:10:10',
d: 2000,
id: 1,
},
{
a: '2000-06-03 05:40:10',
b: '2000-06-02 20:10:10',
c: '05:40:10',
d: 2000,
id: 2,
},
]);
expect((await (await rawConnection).query(`SELECT * from dates_test_pure_dates`))[0]).toEqual([
{
date_value: '2000-06-03',
id: 1,
},
{
date_value: '2000-06-03',
id: 2,
},
{
date_value: '2000-06-03',
id: 3,
},
{
date_value: '2000-06-04',
id: 4,
},
]);
const result = await db.query(__1.sql `
SELECT * from dates_test_dates;
`);
expect(result).toEqual([{
a: new Date('2000-06-03T05:40:10.000Z'),
b: new Date('2000-06-03T05:40:10.000Z'),
c: '15:10:10',
d: 2000,
id: 1
}, {
a: new Date('2000-06-02T20:10:10.000Z'),
b: new Date('2000-06-02T20:10:10.000Z'),
c: '05:40:10',
d: 2000,
id: 2
}]);
expect(await db.query(__1.sql`
expect(result).toEqual([
{
a: new Date('2000-06-03T05:40:10.000Z'),
b: new Date('2000-06-03T05:40:10.000Z'),
c: '15:10:10',
d: 2000,
id: 1,
},
{
a: new Date('2000-06-02T20:10:10.000Z'),
b: new Date('2000-06-02T20:10:10.000Z'),
c: '05:40:10',
d: 2000,
id: 2,
},
]);
expect(await db.query(__1.sql `
SELECT * from dates_test_pure_dates;
`)).toEqual([{
date_value: new Date('2000-06-02T14:30:00.000Z'),
id: 1
}, {
date_value: new Date('2000-06-02T14:30:00.000Z'),
id: 2
}, {
date_value: new Date('2000-06-02T14:30:00.000Z'),
id: 3
}, {
date_value: new Date('2000-06-03T14:30:00.000Z'),
id: 4
}]);
});
await db.dispose();
`)).toEqual([
{
date_value: new Date('2000-06-02T14:30:00.000Z'),
id: 1,
},
{
date_value: new Date('2000-06-02T14:30:00.000Z'),
id: 2,
},
{
date_value: new Date('2000-06-02T14:30:00.000Z'),
id: 3,
},
{
date_value: new Date('2000-06-03T14:30:00.000Z'),
id: 4,
},
]);
});
await db.dispose();
});
test('dates with timezone set to utc', async () => {
// setting timezone on another connection has no impact
await (await rawConnection2).query(`SET time_zone = "+04:00";`);
const db = __1.default({
timeZone: 'utc'
});
await db.task(async db => {
await db.query(__1.sql`
// setting timezone on another connection has no impact
await (await rawConnection2).query(`SET time_zone = "+04:00";`);
const db = __1.default({ timeZone: 'utc' });
await db.task(async (db) => {
await db.query(__1.sql `
DROP TABLE IF EXISTS dates_test_dates;

@@ -252,4 +268,4 @@ CREATE TABLE dates_test_dates (

`);
const sampleDate = new Date('2000-06-03T05:40:10.123Z');
await db.query(__1.sql`
const sampleDate = new Date('2000-06-03T05:40:10.123Z');
await db.query(__1.sql `
INSERT INTO dates_test_dates (id, a, b, c, d)

@@ -259,3 +275,3 @@ VALUES (1, ${sampleDate}, ${sampleDate}, ${sampleDate}, ${2000}),

`);
await db.query(__1.sql`
await db.query(__1.sql `
INSERT INTO dates_test_pure_dates (id, date_value)

@@ -267,68 +283,81 @@ VALUES (1, ${'2000-06-03'}),

`);
expect((await (await rawConnection).query(`SELECT * from dates_test_dates`))[0]).toEqual([{
a: '2000-06-03 05:40:10',
b: '2000-06-03 05:40:10',
c: '05:40:10',
d: 2000,
id: 1
}, {
a: '2000-06-03 05:40:10',
b: '2000-06-03 05:40:10',
c: '05:40:10',
d: 2000,
id: 2
}]);
expect((await (await rawConnection).query(`SELECT * from dates_test_pure_dates`))[0]).toEqual([{
date_value: '2000-06-03',
id: 1
}, {
date_value: '2000-06-03',
id: 2
}, {
date_value: '2000-06-03',
id: 3
}, {
date_value: '2000-06-03',
id: 4
}]);
const result = await db.query(__1.sql`
expect((await (await rawConnection).query(`SELECT * from dates_test_dates`))[0]).toEqual([
{
a: '2000-06-03 05:40:10',
b: '2000-06-03 05:40:10',
c: '05:40:10',
d: 2000,
id: 1,
},
{
a: '2000-06-03 05:40:10',
b: '2000-06-03 05:40:10',
c: '05:40:10',
d: 2000,
id: 2,
},
]);
expect((await (await rawConnection).query(`SELECT * from dates_test_pure_dates`))[0]).toEqual([
{
date_value: '2000-06-03',
id: 1,
},
{
date_value: '2000-06-03',
id: 2,
},
{
date_value: '2000-06-03',
id: 3,
},
{
date_value: '2000-06-03',
id: 4,
},
]);
const result = await db.query(__1.sql `
SELECT * from dates_test_dates;
`);
expect(result).toEqual([{
a: new Date('2000-06-03T05:40:10.000Z'),
b: new Date('2000-06-03T05:40:10.000Z'),
c: '05:40:10',
d: 2000,
id: 1
}, {
a: new Date('2000-06-03T05:40:10.000Z'),
b: new Date('2000-06-03T05:40:10.000Z'),
c: '05:40:10',
d: 2000,
id: 2
}]);
expect(await db.query(__1.sql`
expect(result).toEqual([
{
a: new Date('2000-06-03T05:40:10.000Z'),
b: new Date('2000-06-03T05:40:10.000Z'),
c: '05:40:10',
d: 2000,
id: 1,
},
{
a: new Date('2000-06-03T05:40:10.000Z'),
b: new Date('2000-06-03T05:40:10.000Z'),
c: '05:40:10',
d: 2000,
id: 2,
},
]);
expect(await db.query(__1.sql `
SELECT * from dates_test_pure_dates;
`)).toEqual([{
date_value: new Date('2000-06-03T00:00:00.000Z'),
id: 1
}, {
date_value: new Date('2000-06-03T00:00:00.000Z'),
id: 2
}, {
date_value: new Date('2000-06-03T00:00:00.000Z'),
id: 3
}, {
date_value: new Date('2000-06-03T00:00:00.000Z'),
id: 4
}]);
});
await db.dispose();
`)).toEqual([
{
date_value: new Date('2000-06-03T00:00:00.000Z'),
id: 1,
},
{
date_value: new Date('2000-06-03T00:00:00.000Z'),
id: 2,
},
{
date_value: new Date('2000-06-03T00:00:00.000Z'),
id: 3,
},
{
date_value: new Date('2000-06-03T00:00:00.000Z'),
id: 4,
},
]);
});
await db.dispose();
});
test('DATE as string', async () => {
const db = __1.default({
dateMode: 'string'
});
await db.query(__1.sql`
const db = __1.default({ dateMode: 'string' });
await db.query(__1.sql `
DROP TABLE IF EXISTS dates_test_pure_dates;

@@ -343,19 +372,17 @@ CREATE TABLE dates_test_pure_dates (

`);
expect(await db.query(__1.sql`SELECT * from dates_test_pure_dates`)).toEqual([{
date_value: '2000-06-03',
id: 1
}, {
date_value: '2000-06-04',
id: 2
}]);
await db.dispose();
expect(await db.query(__1.sql `SELECT * from dates_test_pure_dates`)).toEqual([
{
date_value: '2000-06-03',
id: 1,
},
{
date_value: '2000-06-04',
id: 2,
},
]);
await db.dispose();
});
test('DATE as utc', async () => {
const db = __1.default({
timeZone: {
client: 'utc'
}
});
await db.query(__1.sql`
const db = __1.default({ timeZone: { client: 'utc' } });
await db.query(__1.sql `
DROP TABLE IF EXISTS dates_test_pure_dates;

@@ -370,10 +397,14 @@ CREATE TABLE dates_test_pure_dates (

`);
expect(await db.query(__1.sql`SELECT * from dates_test_pure_dates`)).toEqual([{
date_value: new Date('2000-06-03T00:00:00.000Z'),
id: 1
}, {
date_value: new Date('2000-06-04T00:00:00.000Z'),
id: 2
}]);
await db.dispose();
});
expect(await db.query(__1.sql `SELECT * from dates_test_pure_dates`)).toEqual([
{
date_value: new Date('2000-06-03T00:00:00.000Z'),
id: 1,
},
{
date_value: new Date('2000-06-04T00:00:00.000Z'),
id: 2,
},
]);
await db.dispose();
});
//# sourceMappingURL=dates.test.mysql.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const __1 = require("..");
jest.setTimeout(30000);
const db = __1.default();
afterAll(async () => {
await db.dispose();
await db.dispose();
});
test('error messages', async () => {
try {
const s = __1.sql;
await db.query(s`
try {
const s = __1.sql;
await db.query(s `
SELECT 1 + ${1} as foo;

@@ -25,4 +18,5 @@ SELECT 1 + 42 as bar;

`);
} catch (ex) {
expect(ex.message).toMatchInlineSnapshot(`
}
catch (ex) {
expect(ex.message).toMatchInlineSnapshot(`
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near:

@@ -36,18 +30,14 @@

`);
return;
}
expect(false).toBe(true);
return;
}
expect(false).toBe(true);
});
test('query', async () => {
const [{
foo
}] = await db.query(__1.sql`SELECT 1 + 1 as foo`);
expect(foo).toBe(2);
const [{ foo }] = await db.query(__1.sql `SELECT 1 + 1 as foo`);
expect(foo).toBe(2);
});
test('query with params', async () => {
const [{
foo
}] = await db.query(__1.sql`SELECT 1 + ${41} as ${__1.sql.ident('foo')}`);
expect(foo).toBe(42);
});
const [{ foo }] = await db.query(__1.sql `SELECT 1 + ${41} as ${__1.sql.ident('foo')}`);
expect(foo).toBe(42);
});
//# sourceMappingURL=index.test.mysql.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const __1 = require("..");
jest.setTimeout(30000);
const db = __1.default();
afterAll(async () => {
await db.dispose();
await db.dispose();
});
const allValues = [];
beforeAll(async () => {
await db.query(__1.sql`CREATE TABLE streaming_test_values (id BIGINT NOT NULL PRIMARY KEY);`);
for (let batch = 0; batch < 10; batch++) {
const batchValues = [];
for (let i = 0; i < 1000; i++) {
const value = batch * 1000 + i;
batchValues.push(value);
allValues.push(value);
}
await db.query(__1.sql`
await db.query(__1.sql `CREATE TABLE streaming_test_values (id BIGINT NOT NULL PRIMARY KEY);`);
for (let batch = 0; batch < 10; batch++) {
const batchValues = [];
for (let i = 0; i < 1000; i++) {
const value = batch * 1000 + i;
batchValues.push(value);
allValues.push(value);
}
await db.query(__1.sql `
INSERT INTO streaming_test_values (id)
VALUES ${__1.sql.join(batchValues.map(v => __1.sql`(${v})`), __1.sql`,`)};
VALUES ${__1.sql.join(batchValues.map((v) => __1.sql `(${v})`), __1.sql `,`)};
`);
}
}
});
test('node streaming', async () => {
const results = await new Promise((resolve, reject) => {
const results = await new Promise((resolve, reject) => {
const results = [];
db.queryNodeStream(__1.sql `SELECT * FROM streaming_test_values`, {
highWaterMark: 1,
})
.on('data', (data) => results.push(data.id))
.on('error', reject)
.on('end', () => resolve(results));
});
expect(results).toEqual(allValues);
});
test('await streaming', async () => {
const results = [];
db.queryNodeStream(__1.sql`SELECT * FROM streaming_test_values`, {
highWaterMark: 1
}).on('data', data => results.push(data.id)).on('error', reject).on('end', () => resolve(results));
});
expect(results).toEqual(allValues);
for await (const { id } of db.queryStream(__1.sql `SELECT * FROM streaming_test_values`, {
highWaterMark: 1,
})) {
results.push(id);
}
expect(results).toEqual(allValues);
});
test('await streaming', async () => {
const results = [];
for await (const {
id
} of db.queryStream(__1.sql`SELECT * FROM streaming_test_values`, {
highWaterMark: 1
})) {
results.push(id);
}
expect(results).toEqual(allValues);
});
//# sourceMappingURL=stream.test.mysql.js.map

@@ -9,2 +9,3 @@ /// <reference types="node" />

export default class Connection extends BaseConnection<Transaction, MySqlDriver> implements IConnection {
readonly sql: import("@databases/sql").SQL;
queryNodeStream(query: SQLQuery, options?: {

@@ -11,0 +12,0 @@ highWaterMark?: number;

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const shared_1 = require("@databases/shared");
const sql_1 = require("@databases/sql");
class Connection extends shared_1.BaseConnection {
queryNodeStream(query, options = {}) {
return this._driver.queryNodeStream(query, options);
}
constructor() {
super(...arguments);
this.sql = sql_1.default;
}
queryNodeStream(query, options = {}) {
return this._driver.queryNodeStream(query, options);
}
}
exports.default = Connection;
exports.default = Connection;
//# sourceMappingURL=Connection.js.map

@@ -26,2 +26,3 @@ /// <reference types="node" />

export default class ConnectionPool extends BaseConnectionPool<Connection, Transaction, MySqlDriver> implements IConnectionPool {
readonly sql: import("@databases/sql").SQL;
constructor(srcConfig: MySqlConnectionOptions, poolOptions: Omit<PoolOptions<MySqlDriver>, 'openConnection' | 'closeConnection'>, handlers: EventHandlers, onError: (err: Error) => void, acquireLockTimeoutMilliseconds: number, serverTimeZone: 'local' | 'utc' | undefined);

@@ -28,0 +29,0 @@ queryNodeStream(query: SQLQuery, options?: {

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const stream_1 = require("stream");
const shared_1 = require("@databases/shared");
const sql_1 = require("@databases/sql");
const promise_1 = require("mysql2/promise");
const Connection_1 = require("./Connection");
const Transaction_1 = require("./Transaction");
const MySqlDriver_1 = require("./MySqlDriver");
const factories = {
createTransaction(driver) {
return new Transaction_1.default(driver, factories);
},
createConnection(driver) {
return new Connection_1.default(driver, factories);
}
};
const getConnectionPoolOptions = (srcConfig, poolOptions, handlers, onError, acquireLockTimeoutMilliseconds, serverTimeZone) => {
return { ...poolOptions,
openConnection: async removeFromPool => {
const client = await promise_1.createConnection(srcConfig);
const driver = new MySqlDriver_1.default(client, handlers, acquireLockTimeoutMilliseconds);
try {
if (serverTimeZone === 'utc') {
await driver.client.query(`SET time_zone = "+00:00";`);
} else if (serverTimeZone === 'local') {
await driver.client.query(`SET time_zone = ?;`, [Intl.DateTimeFormat().resolvedOptions().timeZone]);
}
} catch (ex) {
void driver.dispose();
throw ex;
}
driver.onAddingToPool(removeFromPool, onError);
if (handlers.onConnectionOpened) {
handlers.onConnectionOpened();
}
return driver;
createTransaction(driver, transactionParentContext) {
return new Transaction_1.default(driver, factories, transactionParentContext);
},
closeConnection: async driver => {
try {
await driver.dispose();
if (handlers.onConnectionClosed) {
handlers.onConnectionClosed();
}
} catch (ex) {
console.warn(ex.message);
}
createConnection(driver) {
return new Connection_1.default(driver, factories);
},
onActive(driver) {
driver.onActive();
},
onIdle(driver) {
driver.onIdle();
}
};
};
const getConnectionPoolOptions = (srcConfig, poolOptions, handlers, onError, acquireLockTimeoutMilliseconds, serverTimeZone) => {
return {
...poolOptions,
openConnection: async (removeFromPool) => {
const client = await promise_1.createConnection(srcConfig);
const driver = new MySqlDriver_1.default(client, handlers, acquireLockTimeoutMilliseconds);
try {
if (serverTimeZone === 'utc') {
await driver.client.query(`SET time_zone = "+00:00";`);
}
else if (serverTimeZone === 'local') {
await driver.client.query(`SET time_zone = ?;`, [
Intl.DateTimeFormat().resolvedOptions().timeZone,
]);
}
}
catch (ex) {
void driver.dispose();
throw ex;
}
driver.onAddingToPool(removeFromPool, onError);
if (handlers.onConnectionOpened) {
handlers.onConnectionOpened();
}
return driver;
},
closeConnection: async (driver) => {
try {
await driver.dispose();
if (handlers.onConnectionClosed) {
handlers.onConnectionClosed();
}
}
catch (ex) {
console.warn(ex.message);
}
},
onActive(driver) {
driver.onActive();
},
onIdle(driver) {
driver.onIdle();
},
};
};
class ConnectionPool extends shared_1.BaseConnectionPool {
constructor(srcConfig, poolOptions, handlers, onError, acquireLockTimeoutMilliseconds, serverTimeZone) {
super(getConnectionPoolOptions(srcConfig, poolOptions, handlers, onError, acquireLockTimeoutMilliseconds, serverTimeZone), factories);
}
queryNodeStream(query, options = {}) {
this._throwIfDisposed();
const stream = new stream_1.PassThrough({
objectMode: true
});
this._pool.getConnection().then(async driver => {
let released = false;
const connectionStream = driver.connection.queryNodeStream(query, options);
return connectionStream.on('fields', fields => {
stream.emit('fields', fields);
}).on('error', err => {
if (!released) {
released = true;
driver.dispose();
}
stream.emit('error', err);
}).on('end', () => {
if (!released) {
released = true;
driver.release();
}
stream.emit('end');
}).pipe(stream);
}).catch(ex => stream.emit('error', ex));
return stream;
}
constructor(srcConfig, poolOptions, handlers, onError, acquireLockTimeoutMilliseconds, serverTimeZone) {
super(getConnectionPoolOptions(srcConfig, poolOptions, handlers, onError, acquireLockTimeoutMilliseconds, serverTimeZone), factories);
this.sql = sql_1.default;
}
queryNodeStream(query, options = {}) {
this._throwIfDisposed();
const stream = new stream_1.PassThrough({
objectMode: true,
});
this._pool
.getConnection()
.then(async (driver) => {
let released = false;
const connectionStream = driver.connection.queryNodeStream(query, options);
return connectionStream
.on('fields', (fields) => {
stream.emit('fields', fields);
})
.on('error', (err) => {
if (!released) {
released = true;
driver.dispose();
}
stream.emit('error', err);
})
.on('end', () => {
if (!released) {
released = true;
driver.release();
}
stream.emit('end');
})
.pipe(stream);
})
.catch((ex) => stream.emit('error', ex));
return stream;
}
}
exports.default = ConnectionPool;
exports.default = ConnectionPool;
//# sourceMappingURL=ConnectionPool.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
exports.isSqlQuery = exports.sql = void 0;
const url_1 = require("url");
const mysql_config_1 = require("@databases/mysql-config");
const sql_1 = require("@databases/sql");
exports.sql = sql_1.default;
Object.defineProperty(exports, "isSqlQuery", {
enumerable: true,
get: function () {
return sql_1.isSqlQuery;
}
});
Object.defineProperty(exports, "isSqlQuery", { enumerable: true, get: function () { return sql_1.isSqlQuery; } });
const ConnectionPool_1 = require("./ConnectionPool");
const {
connectionStringEnvironmentVariable
} = mysql_config_1.getMySqlConfigSync();
const { connectionStringEnvironmentVariable } = mysql_config_1.getMySqlConfigSync();
function createConnectionPool(connectionConfig = process.env[connectionStringEnvironmentVariable]) {
const connectionConfigObject = typeof connectionConfig === 'object' ? connectionConfig : {
connectionString: connectionConfig
};
const {
connectionString = process.env[connectionStringEnvironmentVariable]
} = connectionConfigObject;
if (!connectionString) {
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(connectionString);
const {
tinyIntMode = 'number',
bigIntMode = 'number',
dateMode = 'date-object',
dateTimeMode = 'date-object',
timeStampMode = 'date-object',
timeZone = {
client: 'local'
},
poolSize = 10,
maxUses = Infinity,
idleTimeoutMilliseconds = 30000,
queueTimeoutMilliseconds = 60000,
acquireLockTimeoutMilliseconds = 60000,
onConnectionClosed,
onConnectionOpened,
onQueryStart,
onQueryResults,
onQueryError,
onError = err => {
console.warn(`Error in MySQL ConnectionPool: ${err.message}`);
const connectionConfigObject = typeof connectionConfig === 'object'
? connectionConfig
: { connectionString: connectionConfig };
const { connectionString = process.env[connectionStringEnvironmentVariable], } = connectionConfigObject;
if (!connectionString) {
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.`);
}
} = connectionConfigObject;
const serverTimeZone = typeof timeZone === 'string' ? timeZone : timeZone.server;
const clientTimeZone = typeof timeZone === 'string' ? timeZone : timeZone.client;
const tinyIntParser = getTinyIntParser(tinyIntMode);
const bigIntParser = getBigIntParser(bigIntMode);
const dateParer = getDateParser(dateMode, clientTimeZone);
const dateTimeParser = getDateTimeParser(dateTimeMode, clientTimeZone);
const timeStampParser = getDateTimeParser(timeStampMode, clientTimeZone);
return new ConnectionPool_1.default({
uri: connectionString,
multipleStatements: true,
timezone: clientTimeZone === 'utc' ? 'Z' : clientTimeZone,
typeCast: (field, next) => {
switch (field.type) {
case 'TINY':
return tinyIntParser(field);
case 'LONGLONG':
return bigIntParser(field);
case 'DATE':
return dateParer(field);
case 'DATETIME':
return dateTimeParser(field);
case 'TIMESTAMP':
return timeStampParser(field);
}
return next();
}
}, {
maxSize: poolSize,
maxUses,
idleTimeoutMilliseconds,
queueTimeoutMilliseconds
}, {
onConnectionClosed,
onConnectionOpened,
onQueryStart,
onQueryResults,
onQueryError
}, onError, acquireLockTimeoutMilliseconds, serverTimeZone);
validateMySqlUrl(connectionString);
const { tinyIntMode = 'number', bigIntMode = 'number', dateMode = 'date-object', dateTimeMode = 'date-object', timeStampMode = 'date-object', timeZone = { client: 'local' }, poolSize = 10, maxUses = Infinity, idleTimeoutMilliseconds = 30000, queueTimeoutMilliseconds = 60000, acquireLockTimeoutMilliseconds = 60000, onConnectionClosed, onConnectionOpened, onQueryStart, onQueryResults, onQueryError, onError = (err) => {
console.warn(`Error in MySQL ConnectionPool: ${err.message}`);
}, } = connectionConfigObject;
const serverTimeZone = typeof timeZone === 'string' ? timeZone : timeZone.server;
const clientTimeZone = typeof timeZone === 'string' ? timeZone : timeZone.client;
const tinyIntParser = getTinyIntParser(tinyIntMode);
const bigIntParser = getBigIntParser(bigIntMode);
const dateParer = getDateParser(dateMode, clientTimeZone);
const dateTimeParser = getDateTimeParser(dateTimeMode, clientTimeZone);
const timeStampParser = getDateTimeParser(timeStampMode, clientTimeZone);
return new ConnectionPool_1.default({
uri: connectionString,
multipleStatements: true,
timezone: clientTimeZone === 'utc' ? 'Z' : clientTimeZone,
typeCast: (field, next) => {
switch (field.type) {
case 'TINY':
return tinyIntParser(field);
case 'LONGLONG':
return bigIntParser(field);
case 'DATE':
return dateParer(field);
case 'DATETIME':
return dateTimeParser(field);
case 'TIMESTAMP':
return timeStampParser(field);
}
return next();
},
}, {
maxSize: poolSize,
maxUses,
idleTimeoutMilliseconds,
queueTimeoutMilliseconds,
}, {
onConnectionClosed,
onConnectionOpened,
onQueryStart,
onQueryResults,
onQueryError,
}, onError, acquireLockTimeoutMilliseconds, serverTimeZone);
}
exports.default = createConnectionPool;
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);
}
}
function getTinyIntParser(mode) {
switch (mode) {
case 'number':
return f => parseInt(f.string(), 10);
case 'boolean':
return f => f.string() !== '0';
}
switch (mode) {
case 'number':
return (f) => parseInt(f.string(), 10);
case 'boolean':
return (f) => f.string() !== '0';
}
}
function getBigIntParser(mode) {
switch (mode) {
case 'number':
return f => parseInt(f.string(), 10);
case 'string':
return f => f.string();
case 'bigint':
return f => BigInt(f.string());
}
switch (mode) {
case 'number':
return (f) => parseInt(f.string(), 10);
case 'string':
return (f) => f.string();
case 'bigint':
return (f) => BigInt(f.string());
}
}
function getDateParser(mode, timeZone) {
switch (mode) {
case 'string':
return f => f.string();
case 'date-object':
return f => {
const match = /^(\d{4})\-(\d{2})\-(\d{2})$/.exec(f.string());
if (!match) {
throw new Error('Expected yyyy-mm-dd');
}
if (timeZone === 'utc') {
return new Date(Date.UTC(parseInt(match[1], 10), parseInt(match[2], 10) - 1, parseInt(match[3], 10), 0, 0, 0, 0));
} else {
return new Date(parseInt(match[1], 10), parseInt(match[2], 10) - 1, parseInt(match[3], 10), 0, 0, 0, 0);
}
};
}
switch (mode) {
case 'string':
return (f) => f.string();
case 'date-object':
return (f) => {
const match = /^(\d{4})\-(\d{2})\-(\d{2})$/.exec(f.string());
if (!match) {
throw new Error('Expected yyyy-mm-dd');
}
if (timeZone === 'utc') {
return new Date(Date.UTC(parseInt(match[1], 10), parseInt(match[2], 10) - 1, parseInt(match[3], 10), 0, 0, 0, 0));
}
else {
return new Date(parseInt(match[1], 10), parseInt(match[2], 10) - 1, parseInt(match[3], 10), 0, 0, 0, 0);
}
};
}
}
function getDateTimeParser(mode, timeZone) {
switch (mode) {
case 'string':
return f => f.string();
case 'date-object':
return f => {
var _a, _b;
const match = /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})\:(\d{2})\:(\d{2})(?:\.(\d+))?$/.exec(f.string());
if (!match) {
throw new Error('Expected yyyy-mm-dd HH:MM:SS');
}
let ms = match[7] ? parseInt(match[7].length > 3 ? match[7].substr(0, 3) : match[7], 10) : 0;
if (((_a = match[7]) === null || _a === void 0 ? void 0 : _a.length) === 2) {
ms = ms * 10;
}
if (((_b = match[7]) === null || _b === void 0 ? void 0 : _b.length) === 1) {
ms = ms * 100;
}
if (timeZone === 'utc') {
return new Date(Date.UTC(parseInt(match[1], 10), parseInt(match[2], 10) - 1, parseInt(match[3], 10), parseInt(match[4], 10), // hours
parseInt(match[5], 10), // minutes
parseInt(match[6], 10), // seconds
ms));
} else {
return new Date(parseInt(match[1], 10), parseInt(match[2], 10) - 1, parseInt(match[3], 10), parseInt(match[4], 10), // hours
parseInt(match[5], 10), // minutes
parseInt(match[6], 10), // seconds
ms);
}
};
}
switch (mode) {
case 'string':
return (f) => f.string();
case 'date-object':
return (f) => {
var _a, _b;
const match = /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})\:(\d{2})\:(\d{2})(?:\.(\d+))?$/.exec(f.string());
if (!match) {
throw new Error('Expected yyyy-mm-dd HH:MM:SS');
}
let ms = match[7]
? parseInt(match[7].length > 3 ? match[7].substr(0, 3) : match[7], 10)
: 0;
if (((_a = match[7]) === null || _a === void 0 ? void 0 : _a.length) === 2) {
ms = ms * 10;
}
if (((_b = match[7]) === null || _b === void 0 ? void 0 : _b.length) === 1) {
ms = ms * 100;
}
if (timeZone === 'utc') {
return new Date(Date.UTC(parseInt(match[1], 10), parseInt(match[2], 10) - 1, parseInt(match[3], 10), parseInt(match[4], 10), // hours
parseInt(match[5], 10), // minutes
parseInt(match[6], 10), // seconds
ms));
}
else {
return new Date(parseInt(match[1], 10), parseInt(match[2], 10) - 1, parseInt(match[3], 10), parseInt(match[4], 10), // hours
parseInt(match[5], 10), // minutes
parseInt(match[6], 10), // seconds
ms);
}
};
}
}
module.exports = Object.assign(createConnectionPool, {
default: createConnectionPool,
sql: sql_1.default,
isSqlQuery: sql_1.isSqlQuery
});
default: createConnectionPool,
sql: sql_1.default,
isSqlQuery: sql_1.isSqlQuery,
});
//# sourceMappingURL=index.js.map
"use strict";
/* tslint:disable:no-void-expression */
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const escape_identifier_1 = require("@databases/escape-identifier");
const sql_1 = require("@databases/sql");
const push_to_async_iterable_1 = require("@databases/push-to-async-iterable");
const {
codeFrameColumns
} = require('@babel/code-frame');
const { codeFrameColumns } = require('@babel/code-frame');
const mysqlFormat = {
escapeIdentifier: str => escape_identifier_1.escapeMySqlIdentifier(str),
formatValue: value => ({
placeholder: '?',
value
})
escapeIdentifier: (str) => escape_identifier_1.escapeMySqlIdentifier(str),
formatValue: (value) => ({ placeholder: '?', value }),
};
class MySqlDriver {
constructor(client, handlers, acquireLockTimeoutMilliseconds) {
this._endCalled = false;
this._onIdleError = err => {
if (this._disposed) {
return;
}
this.client.removeListener('error', this._onIdleError);
if (this._removeFromPool) {
this._removeFromPool();
}
if (this._idleErrorEventHandler) {
this._idleErrorEventHandler(err);
}
};
this.acquireLockTimeoutMilliseconds = acquireLockTimeoutMilliseconds;
this._disposed = new Promise(resolve => {
client.on('end', resolve);
});
this.client = client;
this._handlers = handlers;
}
onAddingToPool(removeFromPool, idleErrorEventHandler) {
this._removeFromPool = removeFromPool;
this._idleErrorEventHandler = idleErrorEventHandler;
}
onActive() {
this.client.removeListener('error', this._onIdleError);
}
onIdle() {
this.client.on('error', this._onIdleError);
}
async dispose() {
if (!this._endCalled) {
this._endCalled = true;
this.client.on('error', this._onIdleError);
this.client.destroy();
constructor(client, handlers, acquireLockTimeoutMilliseconds) {
this._endCalled = false;
this._onIdleError = (err) => {
if (this._disposed) {
return;
}
this.client.removeListener('error', this._onIdleError);
if (this._removeFromPool) {
this._removeFromPool();
}
if (this._idleErrorEventHandler) {
this._idleErrorEventHandler(err);
}
};
this.acquireLockTimeoutMilliseconds = acquireLockTimeoutMilliseconds;
this._disposed = new Promise((resolve) => {
client.on('end', resolve);
});
this.client = client;
this._handlers = handlers;
}
}
async canRecycleConnectionAfterError(_err) {
var _a, _b, _c;
try {
let timeout;
const result = await Promise.race([this.client.query('BEGIN TRANSACTION READ ONLY;SELECT 1 AS result;COMMIT;'), new Promise(r => {
timeout = setTimeout(r, 100);
})]);
if (timeout !== undefined) {
clearTimeout(timeout);
}
return ((_c = (_b = (_a = result === null || result === void 0 ? void 0 : result[1]) === null || _a === void 0 ? void 0 : _a.rows) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.result) === 1;
} catch (ex) {
return false;
onAddingToPool(removeFromPool, idleErrorEventHandler) {
this._removeFromPool = removeFromPool;
this._idleErrorEventHandler = idleErrorEventHandler;
}
}
async beginTransaction(options) {
const parameters = [];
if (options) {
if (options.readOnly) {
parameters.push('READ ONLY');
} else if (options.readOnly === false) {
parameters.push('READ WRITE');
}
if (options.withConsistentSnapshot) {
parameters.push('WITH CONSISTENT SNAPSHOT');
}
onActive() {
this.client.removeListener('error', this._onIdleError);
}
if (parameters.length) {
await execute(this.client, `START TRANSACTION ${parameters.join(', ')}`);
} else {
await execute(this.client, `BEGIN`);
onIdle() {
this.client.on('error', this._onIdleError);
}
}
async commitTransaction() {
await execute(this.client, `COMMIT`);
}
async rollbackTransaction() {
await execute(this.client, `ROLLBACK`);
}
async shouldRetryTransactionFailure(_transactionOptions, _ex, _failureCount) {
return false;
}
async createSavepoint(savepointName) {
await execute(this.client, `SAVEPOINT ${savepointName}`);
}
async releaseSavepoint(savepointName) {
await execute(this.client, `RELEASE SAVEPOINT ${savepointName}`);
}
async rollbackToSavepoint(savepointName) {
await execute(this.client, `ROLLBACK TO SAVEPOINT ${savepointName}`);
}
async _executeQuery(query) {
const q = query.format(mysqlFormat);
if (this._handlers.onQueryStart) {
enforceUndefined(this._handlers.onQueryStart(query, q));
async dispose() {
if (!this._endCalled) {
this._endCalled = true;
this.client.on('error', this._onIdleError);
this.client.destroy();
}
}
const results = await executeQueryInternal(this.client, query, q, this._handlers);
if (this._handlers.onQueryResults) {
enforceUndefined(this._handlers.onQueryResults(query, q, results));
async canRecycleConnectionAfterError(_err) {
var _a, _b, _c;
try {
let timeout;
const result = await Promise.race([
this.client.query('BEGIN TRANSACTION READ ONLY;SELECT 1 AS result;COMMIT;'),
new Promise((r) => {
timeout = setTimeout(r, 100);
}),
]);
if (timeout !== undefined) {
clearTimeout(timeout);
}
return ((_c = (_b = (_a = result === null || result === void 0 ? void 0 : result[1]) === null || _a === void 0 ? void 0 : _a.rows) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.result) === 1;
}
catch (ex) {
return false;
}
}
return results;
}
async executeAndReturnAll(queries) {
const results = new Array(queries.length);
for (let i = 0; i < queries.length; i++) {
results[i] = await this._executeQuery(queries[i]);
async beginTransaction(options) {
const parameters = [];
if (options) {
if (options.readOnly) {
parameters.push('READ ONLY');
}
else if (options.readOnly === false) {
parameters.push('READ WRITE');
}
if (options.withConsistentSnapshot) {
parameters.push('WITH CONSISTENT SNAPSHOT');
}
}
if (parameters.length) {
await execute(this.client, `START TRANSACTION ${parameters.join(', ')}`);
}
else {
await execute(this.client, `BEGIN`);
}
}
return results;
}
async executeAndReturnLast(queries) {
if (queries.length === 0) {
return [];
async commitTransaction() {
await execute(this.client, `COMMIT`);
}
for (let i = 0; i < queries.length - 1; i++) {
await this._executeQuery(queries[i]);
async rollbackTransaction() {
await execute(this.client, `ROLLBACK`);
}
return await this._executeQuery(queries[queries.length - 1]);
}
queryStream(query, options) {
if (!sql_1.isSqlQuery(query)) {
throw new Error('Invalid query, you must use @databases/sql to create your queries.');
async shouldRetryTransactionFailure(_transactionOptions, _ex, _failureCount) {
return false;
}
const {
text,
values
} = query.format(mysqlFormat);
const highWaterMark = options && options.highWaterMark || 5;
const connection = this.client.connection;
return push_to_async_iterable_1.default(handlers => {
const stream = connection.query(text, values);
stream.on('result', handlers.onData);
stream.on('error', handlers.onError);
stream.on('end', handlers.onEnd);
return {
dispose: () => {
connection.resume();
},
pause: () => {
connection.pause();
},
resume: () => {
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.');
async createSavepoint(savepointName) {
await execute(this.client, `SAVEPOINT ${savepointName}`);
}
const {
text,
values
} = query.format(mysqlFormat);
const connection = this.client.connection;
const result = connection.query(text, values).stream(options); // tslint:disable-next-line:no-unbound-method
const on = result.on;
const handlers = this._handlers;
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
try {
handleError(ex, query, {
text,
values
}, handlers);
} catch (ex) {
cb(ex);
}
async releaseSavepoint(savepointName) {
await execute(this.client, `RELEASE SAVEPOINT ${savepointName}`);
}
async rollbackToSavepoint(savepointName) {
await execute(this.client, `ROLLBACK TO SAVEPOINT ${savepointName}`);
}
async _executeQuery(query) {
const q = query.format(mysqlFormat);
if (this._handlers.onQueryStart) {
enforceUndefined(this._handlers.onQueryStart(query, q));
}
const results = await executeQueryInternal(this.client, query, q, this._handlers);
if (this._handlers.onQueryResults) {
enforceUndefined(this._handlers.onQueryResults(query, q, results));
}
return results;
}
async executeAndReturnAll(queries) {
const results = new Array(queries.length);
for (let i = 0; i < queries.length; i++) {
results[i] = await this._executeQuery(queries[i]);
}
return results;
}
async executeAndReturnLast(queries) {
if (queries.length === 0) {
return [];
}
for (let i = 0; i < queries.length - 1; i++) {
await this._executeQuery(queries[i]);
}
return await this._executeQuery(queries[queries.length - 1]);
}
queryStream(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 highWaterMark = (options && options.highWaterMark) || 5;
const connection = this.client.connection;
return push_to_async_iterable_1.default((handlers) => {
const stream = connection.query(text, values);
stream.on('result', handlers.onData);
stream.on('error', handlers.onError);
stream.on('end', handlers.onEnd);
return {
dispose: () => {
connection.resume();
},
pause: () => {
connection.pause();
},
resume: () => {
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 connection = this.client.connection;
const result = connection.query(text, values).stream(options);
// tslint:disable-next-line:no-unbound-method
const on = result.on;
const handlers = this._handlers;
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
try {
handleError(ex, query, { text, values }, handlers);
}
catch (ex) {
cb(ex);
}
});
},
});
}
}
exports.default = MySqlDriver;
async function execute(client, query) {
try {
await client.query(query);
} catch (ex) {
throw Object.assign(new Error(ex.message), ex);
}
try {
await client.query(query);
}
catch (ex) {
throw Object.assign(new Error(ex.message), ex);
}
}
async function executeQueryInternal(client, query, q, handlers) {
try {
// const result: [RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[] | ResultSetHeader, FieldPacket[]]
const [result] = await client.query(q.text, q.values);
return result;
} catch (ex) {
handleError(ex, query, q, handlers);
}
try {
// const result: [RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[] | ResultSetHeader, FieldPacket[]]
const [result] = await client.query(q.text, q.values);
return result;
}
catch (ex) {
handleError(ex, query, q, handlers);
}
}
function handleError(ex, query, q, handlers) {
let err;
const mySqlError = parseMySqlError(ex, q.text);
if (mySqlError) {
const {
start,
end,
message: oldMessage
} = mySqlError;
const message = oldMessage.replace(/ near \'((?:.|\n)+)\' at line (\d+)$/, ` near:\n\n${codeFrameColumns(q.text, {
start,
end
})}\n`);
err = Object.assign(new Error(message), ex, {
message
});
} else {
err = Object.assign(new Error(isError(ex) ? ex.message : `${ex}`), ex);
}
if (handlers.onQueryError) {
enforceUndefined(handlers.onQueryError(query, q, err));
}
throw err;
let err;
const mySqlError = parseMySqlError(ex, q.text);
if (mySqlError) {
const { start, end, message: oldMessage } = mySqlError;
const message = oldMessage.replace(/ near \'((?:.|\n)+)\' at line (\d+)$/, ` near:\n\n${codeFrameColumns(q.text, { start, end })}\n`);
err = Object.assign(new Error(message), ex, { message });
}
else {
err = Object.assign(new Error(isError(ex) ? ex.message : `${ex}`), ex);
}
if (handlers.onQueryError) {
enforceUndefined(handlers.onQueryError(query, q, err));
}
throw err;
}
function parseMySqlError(ex, queryText) {
if (isMySqlError(ex)) {
const match = / near \'((?:.|\n)+)\' at line (\d+)$/.exec(ex.sqlMessage);
if (match) {
const index = queryText.indexOf(match[1]);
if (index === queryText.lastIndexOf(match[1])) {
const linesUptoStart = queryText.substr(0, index).split('\n');
const line = linesUptoStart.length;
const start = {
line,
column: linesUptoStart[linesUptoStart.length - 1].length + 1
};
const linesUptoEnd = queryText.substr(0, index + match[1].length).split('\n');
const end = {
line: linesUptoEnd.length,
column: linesUptoEnd[linesUptoEnd.length - 1].length + 1
};
return {
start,
end,
message: ex.message
};
}
if (isMySqlError(ex)) {
const match = / near \'((?:.|\n)+)\' at line (\d+)$/.exec(ex.sqlMessage);
if (match) {
const index = queryText.indexOf(match[1]);
if (index === queryText.lastIndexOf(match[1])) {
const linesUptoStart = queryText.substr(0, index).split('\n');
const line = linesUptoStart.length;
const start = {
line,
column: linesUptoStart[linesUptoStart.length - 1].length + 1,
};
const linesUptoEnd = queryText
.substr(0, index + match[1].length)
.split('\n');
const end = {
line: linesUptoEnd.length,
column: linesUptoEnd[linesUptoEnd.length - 1].length + 1,
};
return { start, end, message: ex.message };
}
}
}
}
return null;
return null;
}
function isError(ex) {
return typeof ex === 'object' && ex !== null && 'message' in ex && typeof ex.message === 'string';
return (typeof ex === 'object' &&
ex !== null &&
'message' in ex &&
typeof ex.message === 'string');
}
function isMySqlError(ex) {
return typeof ex === 'object' && ex !== null && ex.code === 'ER_PARSE_ERROR' && ex.sqlState === '42000' && typeof ex.sqlMessage === 'string' && typeof ex.message === 'string';
return (typeof ex === 'object' &&
ex !== null &&
ex.code === 'ER_PARSE_ERROR' &&
ex.sqlState === '42000' &&
typeof ex.sqlMessage === 'string' &&
typeof ex.message === 'string');
}
function enforceUndefined(value) {
if (value !== undefined) {
throw new Error(`Your event handlers must return "undefined". This is to allow for the possibility of event handlers being used as hooks with more advanced functionality in the future.`);
}
}
if (value !== undefined) {
throw new Error(`Your event handlers must return "undefined". This is to allow for the possibility of event handlers being used as hooks with more advanced functionality in the future.`);
}
}
//# sourceMappingURL=MySqlDriver.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=raw.js.map

@@ -9,3 +9,4 @@ /// <reference types="node" />

export default class Transaction extends BaseTransaction<Transaction, MySqlDriver> implements ITransaction {
readonly sql: import("@databases/sql").SQL;
queryNodeStream(query: SQLQuery, options?: QueryStreamOptions): Readable;
}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const shared_1 = require("@databases/shared");
const sql_1 = require("@databases/sql");
class Transaction extends shared_1.BaseTransaction {
queryNodeStream(query, options) {
return this._driver.queryNodeStream(query, options);
}
constructor() {
super(...arguments);
this.sql = sql_1.default;
}
queryNodeStream(query, options) {
return this._driver.queryNodeStream(query, options);
}
}
exports.default = Transaction;
exports.default = Transaction;
//# sourceMappingURL=Transaction.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=EventHandlers.js.map

@@ -16,2 +16,3 @@ /// <reference types="node" />

tx<T>(fn: (connection: Transaction) => Promise<T>, options?: TransactionOptions): Promise<T>;
addPostCommitStep(fn: () => Promise<void>): Promise<void>;
}

@@ -18,0 +19,0 @@ /**

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
exports.isTransaction = exports.isConnection = exports.isConnectionPool = void 0;
const shared_1 = require("@databases/shared");
function isConnectionPool(queryable) {
return queryable.type === shared_1.QueryableType.ConnectionPool;
return queryable.type === shared_1.QueryableType.ConnectionPool;
}
exports.isConnectionPool = isConnectionPool;
function isConnection(queryable) {
return queryable.type === shared_1.QueryableType.Connection;
return queryable.type === shared_1.QueryableType.Connection;
}
exports.isConnection = isConnection;
function isTransaction(queryable) {
return queryable.type === shared_1.QueryableType.Transaction;
return queryable.type === shared_1.QueryableType.Transaction;
}
exports.isTransaction = isTransaction;
exports.isTransaction = isTransaction;
//# sourceMappingURL=Queryable.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=QueryStreamOptions.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=TransactionOptions.js.map
{
"name": "@databases/mysql",
"version": "5.0.0",
"version": "5.1.0",
"description": "",

@@ -12,3 +12,3 @@ "main": "./lib/index.js",

"@databases/push-to-async-iterable": "^3.0.0",
"@databases/shared": "^2.0.0",
"@databases/shared": "^3.0.0",
"@databases/sql": "^3.0.0",

@@ -15,0 +15,0 @@ "@types/mysql": "^2.15.5",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc