forked from typeorm/typeorm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlServerDriver.ts
More file actions
575 lines (476 loc) · 19.1 KB
/
SqlServerDriver.ts
File metadata and controls
575 lines (476 loc) · 19.1 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
import {Driver} from "../Driver";
import {ConnectionIsNotSetError} from "../../error/ConnectionIsNotSetError";
import {DriverPackageNotInstalledError} from "../../error/DriverPackageNotInstalledError";
import {DriverUtils} from "../DriverUtils";
import {SqlServerQueryRunner} from "./SqlServerQueryRunner";
import {ObjectLiteral} from "../../common/ObjectLiteral";
import {ColumnMetadata} from "../../metadata/ColumnMetadata";
import {DateUtils} from "../../util/DateUtils";
import {PlatformTools} from "../../platform/PlatformTools";
import {Connection} from "../../connection/Connection";
import {RdbmsSchemaBuilder} from "../../schema-builder/RdbmsSchemaBuilder";
import {SqlServerConnectionOptions} from "./SqlServerConnectionOptions";
import {MappedColumnTypes} from "../types/MappedColumnTypes";
import {ColumnType} from "../types/ColumnTypes";
import {DataTypeDefaults} from "../types/DataTypeDefaults";
import {MssqlParameter} from "./MssqlParameter";
import {TableColumn} from "../../schema-builder/schema/TableColumn";
import {SqlServerConnectionCredentialsOptions} from "./SqlServerConnectionCredentialsOptions";
/**
* Organizes communication with SQL Server DBMS.
*/
export class SqlServerDriver implements Driver {
// -------------------------------------------------------------------------
// Public Properties
// -------------------------------------------------------------------------
/**
* Connection used by driver.
*/
connection: Connection;
/**
* SQL Server library.
*/
mssql: any;
/**
* Pool for master database.
*/
master: any;
/**
* Pool for slave databases.
* Used in replication.
*/
slaves: any[] = [];
// -------------------------------------------------------------------------
// Public Implemented Properties
// -------------------------------------------------------------------------
/**
* Connection options.
*/
options: SqlServerConnectionOptions;
/**
* Master database used to perform all write queries.
*/
database?: string;
/**
* Indicates if replication is enabled.
*/
isReplicated: boolean = false;
/**
* Indicates if tree tables are supported by this driver.
*/
treeSupport = true;
/**
* Gets list of supported column data types by a driver.
*
* @see https://docs.microsoft.com/en-us/sql/t-sql/data-types/data-types-transact-sql
*/
supportedDataTypes: ColumnType[] = [
"bigint",
"bit",
"decimal",
"int",
"money",
"numeric",
"smallint",
"smallmoney",
"tinyint",
"float",
"real",
"date",
"datetime2",
"datetime",
"datetimeoffset",
"smalldatetime",
"time",
"char",
"text",
"varchar",
"nchar",
"ntext",
"nvarchar",
"binary",
"image",
"varbinary",
"cursor",
"hierarchyid",
"sql_variant",
"table",
"timestamp",
"uniqueidentifier",
"xml"
];
/**
* Gets list of column data types that support length by a driver.
*/
withLengthColumnTypes: ColumnType[] = [
"char",
"varchar",
"nchar",
"nvarchar",
"binary",
"varbinary"
];
/**
* Orm has special columns and we need to know what database column types should be for those types.
* Column types are driver dependant.
*/
mappedDataTypes: MappedColumnTypes = {
createDate: "datetime2",
createDateDefault: "getdate()",
updateDate: "datetime2",
updateDateDefault: "getdate()",
version: "int",
treeLevel: "int",
migrationName: "varchar",
migrationTimestamp: "bigint",
cacheId: "int",
cacheIdentifier: "nvarchar",
cacheTime: "bigint",
cacheDuration: "int",
cacheQuery: "nvarchar(MAX)" as any,
cacheResult: "nvarchar(MAX)" as any,
};
/**
* Default values of length, precision and scale depends on column data type.
* Used in the cases when length/precision/scale is not specified by user.
*/
dataTypeDefaults: DataTypeDefaults = {
varchar: { length: 255 },
nvarchar: { length: 255 }
};
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(connection: Connection) {
this.connection = connection;
this.options = connection.options as SqlServerConnectionOptions;
this.isReplicated = this.options.replication ? true : false;
// load mssql package
this.loadDependencies();
// Object.assign(connection.options, DriverUtils.buildDriverOptions(connection.options)); // todo: do it better way
// validate options to make sure everything is set
// if (!this.options.host)
// throw new DriverOptionNotSetError("host");
// if (!this.options.username)
// throw new DriverOptionNotSetError("username");
// if (!this.options.database)
// throw new DriverOptionNotSetError("database");
}
// -------------------------------------------------------------------------
// Public Implemented Methods
// -------------------------------------------------------------------------
/**
* Performs connection to the database.
* Based on pooling options, it can either create connection immediately,
* either create a pool and create connection when needed.
*/
async connect(): Promise<void> {
if (this.options.replication) {
this.slaves = await Promise.all(this.options.replication.slaves.map(slave => {
return this.createPool(this.options, slave);
}));
this.master = await this.createPool(this.options, this.options.replication.master);
this.database = this.options.replication.master.database;
} else {
this.master = await this.createPool(this.options, this.options);
this.database = this.options.database;
}
}
/**
* Makes any action after connection (e.g. create extensions in Postgres driver).
*/
afterConnect(): Promise<void> {
return Promise.resolve();
}
/**
* Closes connection with the database.
*/
async disconnect(): Promise<void> {
if (!this.master)
return Promise.reject(new ConnectionIsNotSetError("mssql"));
this.master.close();
this.slaves.forEach(slave => slave.close());
this.master = undefined;
this.slaves = [];
}
/**
* Creates a schema builder used to build and sync a schema.
*/
createSchemaBuilder() {
return new RdbmsSchemaBuilder(this.connection);
}
/**
* Creates a query runner used to execute database queries.
*/
createQueryRunner(mode: "master"|"slave" = "master") {
return new SqlServerQueryRunner(this, mode);
}
/**
* Replaces parameters in the given sql with special escaping character
* and an array of parameter names to be passed to a query.
*/
escapeQueryWithParameters(sql: string, parameters: ObjectLiteral): [string, any[]] {
if (!parameters || !Object.keys(parameters).length)
return [sql, []];
const escapedParameters: any[] = [];
const keys = Object.keys(parameters).map(parameter => "(:" + parameter + "\\b)").join("|");
sql = sql.replace(new RegExp(keys, "g"), (key: string) => {
const value = parameters[key.substr(1)];
if (value instanceof Array) {
return value.map((v: any) => {
escapedParameters.push(v);
return "@" + (escapedParameters.length - 1);
}).join(", ");
} else if (value instanceof Function) {
return value();
} else {
escapedParameters.push(value);
return "@" + (escapedParameters.length - 1);
}
}); // todo: make replace only in value statements, otherwise problems
return [sql, escapedParameters];
}
/**
* Escapes a column name.
*/
escape(columnName: string): string {
return `"${columnName}"`;
}
/**
* Prepares given value to a value to be persisted, based on its column type and metadata.
*/
preparePersistentValue(value: any, columnMetadata: ColumnMetadata): any {
if (columnMetadata.transformer)
value = columnMetadata.transformer.to(value);
if (value === null || value === undefined)
return value;
if (columnMetadata.type === Boolean) {
return value === true ? 1 : 0;
} else if (columnMetadata.type === "date") {
return DateUtils.mixedDateToDate(value);
} else if (columnMetadata.type === "time") {
return DateUtils.mixedTimeToDate(value);
} else if (columnMetadata.type === "datetime"
|| columnMetadata.type === "smalldatetime"
|| columnMetadata.type === Date) {
return DateUtils.mixedDateToDate(value, true, false);
} else if (columnMetadata.type === "datetime2"
|| columnMetadata.type === "datetimeoffset") {
return DateUtils.mixedDateToDate(value, true, true);
} else if (columnMetadata.type === "simple-array") {
return DateUtils.simpleArrayToString(value);
}
return value;
}
/**
* Prepares given value to a value to be persisted, based on its column type or metadata.
*/
prepareHydratedValue(value: any, columnMetadata: ColumnMetadata): any {
if (columnMetadata.transformer)
value = columnMetadata.transformer.from(value);
if (value === null || value === undefined)
return value;
if (columnMetadata.type === Boolean) {
return value ? true : false;
} else if (columnMetadata.type === "datetime"
|| columnMetadata.type === Date
|| columnMetadata.type === "datetime2"
|| columnMetadata.type === "smalldatetime"
|| columnMetadata.type === "datetimeoffset") {
return DateUtils.normalizeHydratedDate(value);
} else if (columnMetadata.type === "date") {
return DateUtils.mixedDateToDateString(value);
} else if (columnMetadata.type === "time") {
return DateUtils.mixedTimeToString(value);
} else if (columnMetadata.type === "simple-array") {
return DateUtils.stringToSimpleArray(value);
}
return value;
}
/**
* Creates a database type from a given column metadata.
*/
normalizeType(column: { type?: ColumnType, length?: number | string, precision?: number, scale?: number }): string {
if (column.type === Number) {
return "int";
} else if (column.type === String) {
return "nvarchar";
} else if (column.type === Date) {
return "datetime";
} else if (column.type === Boolean) {
return "bit";
} else if ((column.type as any) === Buffer) {
return "binary";
} else if (column.type === "uuid") {
return "uniqueidentifier";
} else if (column.type === "simple-array") {
return "ntext";
} else if (column.type === "integer") {
return "int";
} else if (column.type === "dec") {
return "decimal";
} else if (column.type === "float" && (column.precision && (column.precision! >= 1 && column.precision! < 25))) {
return "real";
} else if (column.type === "double precision") {
return "float";
} else {
return column.type as string || "";
}
}
/**
* Normalizes "default" value of the column.
*/
normalizeDefault(column: ColumnMetadata): string {
if (typeof column.default === "number") {
return "" + column.default;
} else if (typeof column.default === "boolean") {
return column.default === true ? "1" : "0";
} else if (typeof column.default === "function") {
return "(" + column.default() + ")";
} else if (typeof column.default === "string") {
return `'${column.default}'`;
} else {
return column.default;
}
}
/**
* Normalizes "isUnique" value of the column.
*/
normalizeIsUnique(column: ColumnMetadata): boolean {
return column.isUnique;
}
/**
* Calculates column length taking into account the default length values.
*/
getColumnLength(column: ColumnMetadata): string {
if (column.length)
return column.length;
const normalizedType = this.normalizeType(column) as string;
if (this.dataTypeDefaults && this.dataTypeDefaults[normalizedType] && this.dataTypeDefaults[normalizedType].length)
return this.dataTypeDefaults[normalizedType].length!.toString();
return "";
}
createFullType(column: TableColumn): string {
let type = column.type;
if (column.length) {
type += "(" + column.length + ")";
} else if (column.precision && column.scale) {
type += "(" + column.precision + "," + column.scale + ")";
} else if (column.precision && column.type !== "real") {
type += "(" + column.precision + ")";
} else if (column.scale) {
type += "(" + column.scale + ")";
} else if (this.dataTypeDefaults && this.dataTypeDefaults[column.type] && this.dataTypeDefaults[column.type].length) {
type += "(" + this.dataTypeDefaults[column.type].length!.toString() + ")";
}
if (column.isArray)
type += " array";
return type;
}
/**
* Obtains a new database connection to a master server.
* Used for replication.
* If replication is not setup then returns default connection's database connection.
*/
obtainMasterConnection(): Promise<any> {
return Promise.resolve(this.master);
}
/**
* Obtains a new database connection to a slave server.
* Used for replication.
* If replication is not setup then returns master (default) connection's database connection.
*/
obtainSlaveConnection(): Promise<any> {
if (!this.slaves.length)
return this.obtainMasterConnection();
const random = Math.floor(Math.random() * this.slaves.length);
return Promise.resolve(this.slaves[random]);
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Sql server's parameters needs to be wrapped into special object with type information about this value.
* This method wraps given value into MssqlParameter based on its column definition.
*/
parametrizeValue(column: ColumnMetadata, value: any) {
// if its already MssqlParameter then simply return it
if (value instanceof MssqlParameter)
return value;
const normalizedType = this.normalizeType({ type: column.type });
if (column.length) {
return new MssqlParameter(value, normalizedType as any, column.length as any);
} else if (column.precision && column.scale) {
return new MssqlParameter(value, normalizedType as any, column.precision, column.scale);
} else if (column.precision) {
return new MssqlParameter(value, normalizedType as any, column.precision);
} else if (column.scale) {
return new MssqlParameter(value, normalizedType as any, column.scale);
}
return new MssqlParameter(value, normalizedType as any);
}
/**
* Sql server's parameters needs to be wrapped into special object with type information about this value.
* This method wraps all values of the given object into MssqlParameter based on their column definitions in the given table.
*/
parametrizeMap(tablePath: string, map: ObjectLiteral): ObjectLiteral {
// find metadata for the given table
if (!this.connection.hasMetadata(tablePath)) // if no metadata found then we can't proceed because we don't have columns and their types
return map;
const metadata = this.connection.getMetadata(tablePath);
return Object.keys(map).reduce((newMap, key) => {
const value = map[key];
// find column metadata
const column = metadata.findColumnWithDatabaseName(key);
if (!column) // if we didn't find a column then we can't proceed because we don't have a column type
return value;
newMap[key] = this.parametrizeValue(column, value);
return newMap;
}, {} as ObjectLiteral);
}
// -------------------------------------------------------------------------
// Protected Methods
// -------------------------------------------------------------------------
/**
* If driver dependency is not given explicitly, then try to load it via "require".
*/
protected loadDependencies(): void {
try {
this.mssql = PlatformTools.load("mssql");
} catch (e) { // todo: better error for browser env
throw new DriverPackageNotInstalledError("SQL Server", "mssql");
}
}
/**
* Creates a new connection pool for a given database credentials.
*/
protected createPool(options: SqlServerConnectionOptions, credentials: SqlServerConnectionCredentialsOptions): Promise<any> {
credentials = Object.assign(credentials, DriverUtils.buildDriverOptions(credentials)); // todo: do it better way
// build connection options for the driver
const connectionOptions = Object.assign({}, {
connectionTimeout: this.options.connectionTimeout,
requestTimeout: this.options.requestTimeout,
stream: this.options.stream,
pool: this.options.pool,
options: this.options.options,
}, {
server: credentials.host,
user: credentials.username,
password: credentials.password,
database: credentials.database,
port: credentials.port,
domain: credentials.domain,
}, options.extra || {});
// set default useUTC option if it hasn't been set
if (!connectionOptions.options) connectionOptions.options = { useUTC: false };
else if (!connectionOptions.options.useUTC) connectionOptions.options.useUTC = false;
// pooling is enabled either when its set explicitly to true,
// either when its not defined at all (e.g. enabled by default)
return new Promise<void>((ok, fail) => {
const connection = new this.mssql.ConnectionPool(connectionOptions).connect((err: any) => {
if (err) return fail(err);
ok(connection);
});
});
}
}