-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsession.js
94 lines (76 loc) · 2.31 KB
/
session.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const Query = require('./query');
const Factory = require('async-factory');
const connectionFactory = new Factory();
const kConnections = Symbol('connections');
let sessionNextId = 0;
class Session {
constructor ({ manager, options = {} }) {
this.id = `session-${sessionNextId++}`;
this.manager = manager;
this.state = { ...options.state };
this[kConnections] = {};
}
factory (name, criteria) {
const [connection, schema] = this.parse(name);
return new Query({ session: this, connection, schema, criteria });
}
async acquire (name) {
const pool = this.manager.getPool(name);
if (!this[kConnections][pool.name]) {
const id = `${this.id}-${pool.name}`;
this[kConnections][pool.name] = await connectionFactory.singleton(id, () => pool.acquire());
await this[kConnections][pool.name].begin();
}
return this[kConnections][pool.name];
}
async dispose () {
await this.rollback();
await Promise.all(Object.keys(this[kConnections]).map(name => {
return this.manager.getPool(name).release(this[kConnections][name]);
}));
this[kConnections] = {};
}
close () {
return this.commit();
}
async commit () {
await Promise.all(Object.keys(this[kConnections]).map(async name => {
const connection = this[kConnections][name];
await connection.commit();
}));
}
async rollback () {
await Promise.all(Object.keys(this[kConnections]).map(async name => {
const connection = this[kConnections][name];
await connection.rollback();
}));
}
async begin () {
await Promise.all(Object.keys(this[kConnections]).map(async name => {
const connection = this[kConnections][name];
await connection.begin();
}));
}
async flush () {
await this.commit();
await this.begin();
}
parse (name) {
let connection;
let schema;
if (Array.isArray(name)) {
if (name.length < 2) {
throw new Error('Malformed schema name tupple');
}
[connection, schema] = name;
} else if (name.indexOf('.') !== -1) {
[connection, schema] = name.split('.');
} else {
connection = this.manager.getPool().name;
schema = name;
}
const pool = this.manager.getPool(connection);
return [pool.name, pool.getSchema(schema)];
}
}
module.exports = Session;