mssql 9.1.4 → 9.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +99 -5
- package/lib/datatypes.js +4 -2
- package/lib/msnodesqlv8/request.js +103 -11
- package/lib/table.js +19 -3
- package/lib/tedious/request.js +25 -5
- package/lib/tedious/transaction.js +31 -1
- package/lib/utils.js +26 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1008,7 +1008,7 @@ __Errors__
|
|
|
1008
1008
|
- ECONNCLOSED (`ConnectionError`) - Connection is closed.
|
|
1009
1009
|
- ENOTBEGUN (`TransactionError`) - Transaction has not begun.
|
|
1010
1010
|
- EABORT (`TransactionError`) - Transaction was aborted (by user or because of an error).
|
|
1011
|
-
- EINJECT (`RequestError`) -
|
|
1011
|
+
- EINJECT (`RequestError`) - Table name, column name or parameter type is not a valid identifier. See [Identifiers](#identifiers).
|
|
1012
1012
|
|
|
1013
1013
|
---------------------------------------
|
|
1014
1014
|
|
|
@@ -1099,6 +1099,16 @@ transaction.begin(err => {
|
|
|
1099
1099
|
})
|
|
1100
1100
|
```
|
|
1101
1101
|
|
|
1102
|
+
__Transaction name__
|
|
1103
|
+
|
|
1104
|
+
Set `transaction.name` before calling `begin` to give the transaction a name. The server shows it in `sys.dm_tran_active_transactions`. It must be a string of at most 32 characters, counted in UTF-16 code units, or `null` or `undefined` for no name. The `msnodesqlv8` driver doesn't send it. See [Transaction names](#transaction-names).
|
|
1105
|
+
|
|
1106
|
+
```javascript
|
|
1107
|
+
const transaction = new sql.Transaction(/* [pool] */)
|
|
1108
|
+
transaction.name = 'nightly import'
|
|
1109
|
+
await transaction.begin()
|
|
1110
|
+
```
|
|
1111
|
+
|
|
1102
1112
|
### Events
|
|
1103
1113
|
|
|
1104
1114
|
- **begin** - Dispatched when transaction begin.
|
|
@@ -1128,6 +1138,7 @@ transaction.begin(err => {
|
|
|
1128
1138
|
__Errors__
|
|
1129
1139
|
- ENOTOPEN (`ConnectionError`) - Connection not yet open.
|
|
1130
1140
|
- EALREADYBEGUN (`TransactionError`) - Transaction has already begun.
|
|
1141
|
+
- EINJECT (`TransactionError`) - Transaction name is not a string, or is longer than 32 characters (`tedious` driver). See [Transaction names](#transaction-names).
|
|
1131
1142
|
|
|
1132
1143
|
---------------------------------------
|
|
1133
1144
|
|
|
@@ -1837,9 +1848,9 @@ Results in:
|
|
|
1837
1848
|
## Identifiers
|
|
1838
1849
|
|
|
1839
1850
|
Values are sent to the server as parameters and may hold anything. A few things
|
|
1840
|
-
are not values, and cannot be: the name of a parameter, the name of a
|
|
1841
|
-
bulk load, the type a parameter is declared as,
|
|
1842
|
-
Those are *identifiers*, and
|
|
1851
|
+
are not values, and cannot be: the name of a parameter, the name of a table or a
|
|
1852
|
+
column in a bulk load, the type a parameter is declared as, the name of a stored
|
|
1853
|
+
procedure, and the name of a transaction. Those are *identifiers*, and
|
|
1843
1854
|
no SQL database can bind them, so this library builds them into the statement it
|
|
1844
1855
|
sends. It checks them, and rejects anything that could end the identifier and have
|
|
1845
1856
|
the rest of the value read as SQL.
|
|
@@ -1881,6 +1892,10 @@ table.columns.add('a]]b', sql.Int) // the column named a]b
|
|
|
1881
1892
|
A single `]` raises `EINJECT`. Column names are not otherwise restricted: spaces,
|
|
1882
1893
|
punctuation and reserved words are all fine, because the quoting handles them.
|
|
1883
1894
|
|
|
1895
|
+
With the `msnodesqlv8` driver, a bulk load into a column whose name holds a `]`
|
|
1896
|
+
raises `EINJECT`, because that driver cannot write such a name. See
|
|
1897
|
+
[Bulk load table names](#bulk-load-table-names).
|
|
1898
|
+
|
|
1884
1899
|
The keys of `options.order` are also identifiers, but the driver writes them into the bulk
|
|
1885
1900
|
statement's `ORDER (...)` clause *unquoted* rather than as `[name]`. They follow the type
|
|
1886
1901
|
name rule instead: bare, or quoted with brackets or double quotes.
|
|
@@ -1890,6 +1905,62 @@ request.bulk(table, { order: { created_at: 'ASC' } })
|
|
|
1890
1905
|
request.bulk(table, { order: { '[Created At]': 'DESC' } }) // quote a spaced name yourself
|
|
1891
1906
|
```
|
|
1892
1907
|
|
|
1908
|
+
### Bulk load table names
|
|
1909
|
+
|
|
1910
|
+
With the `msnodesqlv8` driver, a bulk load finds its table through the driver's table
|
|
1911
|
+
manager. The table manager writes the table name into a query of its own, and then
|
|
1912
|
+
writes an `INSERT` from what it found. This library gives it the name without its
|
|
1913
|
+
brackets, and the table manager splits that name on every `.`. Before a connection is
|
|
1914
|
+
taken, this library checks each part:
|
|
1915
|
+
|
|
1916
|
+
- The table and schema names are written into a quoted string, so they must not hold a
|
|
1917
|
+
single `'`. The table manager reads a doubled `''` as one `'`. The `tedious` driver
|
|
1918
|
+
does not, so there the same name is a different table.
|
|
1919
|
+
- The database name is written unquoted. It may hold the characters a parameter name
|
|
1920
|
+
may, with space around it, or it may be in double quotes. It must not hold a `'`. Any
|
|
1921
|
+
part before the database is checked in the same way. The table manager reads double
|
|
1922
|
+
quotes as quoting, but the `tedious` driver reads them as part of the name.
|
|
1923
|
+
- The name of a temporary table, one that starts with `#`, is written unquoted into the
|
|
1924
|
+
`INSERT`, so every part may hold only the characters a parameter name may.
|
|
1925
|
+
- No part may hold a `$` followed by a backtick, a `'` or a `&`. The table manager
|
|
1926
|
+
replaces each of these pairs with a part of its own query.
|
|
1927
|
+
|
|
1928
|
+
```javascript
|
|
1929
|
+
// what request.bulk(table) does with the msnodesqlv8 driver, for each of these tables
|
|
1930
|
+
new sql.Table('dbo.[My Table]') // fine
|
|
1931
|
+
new sql.Table("[O'Brien]") // EINJECT: a single ' in the table name
|
|
1932
|
+
new sql.Table('[my db].dbo.orders') // EINJECT: a space in an unquoted database name
|
|
1933
|
+
new sql.Table('[#my temp]') // EINJECT: a space in a temporary table name
|
|
1934
|
+
```
|
|
1935
|
+
|
|
1936
|
+
When the table manager has found the table, this library checks what it found. A
|
|
1937
|
+
failure here releases the connection:
|
|
1938
|
+
|
|
1939
|
+
- A table in `tempdb` is written into the `INSERT` as the name you gave, so each part of
|
|
1940
|
+
that name is checked as the database name is. This applies when the connection's own
|
|
1941
|
+
database is `tempdb`, too.
|
|
1942
|
+
- Any other table is written as `[database].[schema].[table]`, from the names the
|
|
1943
|
+
server reported, without doubling a `]`. A table whose database, schema or table name
|
|
1944
|
+
holds a `]` is rejected.
|
|
1945
|
+
- Each column the driver writes to is written as `[name]`, without doubling a `]`, so a
|
|
1946
|
+
column whose name holds one is rejected. The driver does not write to identity,
|
|
1947
|
+
computed and other read-only columns, so their names may hold one.
|
|
1948
|
+
|
|
1949
|
+
A name that fails one of these checks raises `EINJECT`. The `tedious` driver does not
|
|
1950
|
+
make these checks.
|
|
1951
|
+
|
|
1952
|
+
### Table paths
|
|
1953
|
+
|
|
1954
|
+
`new sql.Table(name)` builds the table's `path` from the name, with each part in
|
|
1955
|
+
brackets. `table.declare()` writes that path into a `create table` statement, which a bulk
|
|
1956
|
+
load with `create` set sends with either driver. The `tedious` driver also writes the path
|
|
1957
|
+
into the `insert bulk` statement of every bulk load. If you set `table.path` yourself, those
|
|
1958
|
+
statements need it to be a qualified name: parts separated by `.`, each either bare, holding
|
|
1959
|
+
only the characters a parameter name may, or in brackets or double quotes. A part between
|
|
1960
|
+
two others may be empty, as in `db..table`, and space around the whole path is removed.
|
|
1961
|
+
Anything else raises `EINJECT`. When `table.declare()` names a primary key constraint after
|
|
1962
|
+
`table.name`, a `]` in that name must be written as `]]`.
|
|
1963
|
+
|
|
1893
1964
|
### Type names and sizes
|
|
1894
1965
|
|
|
1895
1966
|
`sql.TVP()` takes the name of a table type, optionally qualified with a schema and
|
|
@@ -1906,6 +1977,12 @@ request.input('note', sql.VarChar('max'), value)
|
|
|
1906
1977
|
A size is checked wherever it is built into SQL, which includes the declaration a
|
|
1907
1978
|
bulk load sends and the parameter list a query sends, not only `sql.TVP()`.
|
|
1908
1979
|
|
|
1980
|
+
A type that is not one of `sql.TYPES` is declared with its own `declaration`. That
|
|
1981
|
+
declaration is checked by the same rule as the name of a table type, and may end with a
|
|
1982
|
+
size in parentheses: one or two numbers, or `max`, as in `nvarchar(50)` or
|
|
1983
|
+
`decimal(10, 2)`. A type given directly as a `tedious` type is declared by `tedious`
|
|
1984
|
+
itself, not by this library.
|
|
1985
|
+
|
|
1909
1986
|
### Procedure names
|
|
1910
1987
|
|
|
1911
1988
|
`request.execute()` takes the name of a stored procedure, optionally qualified with
|
|
@@ -1926,6 +2003,22 @@ Anything else raises `EINJECT`. Numbered procedures — the deprecated
|
|
|
1926
2003
|
`procedure;1` form — are rejected, because the `;` cannot be told apart from the
|
|
1927
2004
|
end of a statement.
|
|
1928
2005
|
|
|
2006
|
+
### Transaction names
|
|
2007
|
+
|
|
2008
|
+
With the `tedious` driver, `transaction.name` must be a string of at most 32
|
|
2009
|
+
characters, counted in UTF-16 code units, or `null` or `undefined` for no name;
|
|
2010
|
+
anything else raises `EINJECT` before a connection is taken. The server refuses a
|
|
2011
|
+
longer name. From TDS 7.2 (the default `tdsVersion` is `7_4`) the driver sends the
|
|
2012
|
+
name to the server as data, so it may hold any character. On a connection that uses
|
|
2013
|
+
TDS 7.1, because `options.tdsVersion`
|
|
2014
|
+
is `7_1` or because the server supports nothing newer, the driver builds the name
|
|
2015
|
+
into a `BEGIN TRAN` statement instead, so there it is sent as a quoted identifier
|
|
2016
|
+
with any `]` doubled. It cannot end the statement, and the server stores the name
|
|
2017
|
+
exactly as given, as it does on newer TDS versions, except that over TDS 7.1 it
|
|
2018
|
+
refuses a name containing a NUL character or U+FFFF.
|
|
2019
|
+
|
|
2020
|
+
The `msnodesqlv8` driver doesn't send the name.
|
|
2021
|
+
|
|
1929
2022
|
---------------------------------------
|
|
1930
2023
|
|
|
1931
2024
|
## Errors
|
|
@@ -1960,11 +2053,12 @@ Name | Code | Message
|
|
|
1960
2053
|
`TransactionError` | EALREADYBEGUN | Transaction has already begun.
|
|
1961
2054
|
`TransactionError` | EREQINPROG | Can't commit/rollback transaction. There is a request in progress.
|
|
1962
2055
|
`TransactionError` | EABORT | Transaction has been aborted.
|
|
2056
|
+
`TransactionError` | EINJECT | Transaction name is not a string, or is longer than 32 characters.
|
|
1963
2057
|
`RequestError` | EREQUEST | Message from SQL Server. Error object contains additional details.
|
|
1964
2058
|
`RequestError` | ECANCEL | Cancelled.
|
|
1965
2059
|
`RequestError` | ETIMEOUT | Request timeout.
|
|
1966
2060
|
`RequestError` | EARGS | Invalid number of arguments.
|
|
1967
|
-
`RequestError` | EINJECT | Parameter name, column name or type is not a valid identifier.
|
|
2061
|
+
`RequestError` | EINJECT | Parameter name, table name, column name or type is not a valid identifier.
|
|
1968
2062
|
`RequestError` | ENOCONN | No connection is specified for that request.
|
|
1969
2063
|
`PreparedStatementError` | EARGS | Invalid number of arguments.
|
|
1970
2064
|
`PreparedStatementError` | EINJECT | Parameter name is not a valid identifier.
|
package/lib/datatypes.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
'use strict'
|
|
2
|
-
const { objectHasProperty, assertSafeTypeName, assertSafeTypeSize } = require('./utils')
|
|
2
|
+
const { objectHasProperty, assertSafeTypeName, assertSafeTypeDeclaration, assertSafeTypeSize } = require('./utils')
|
|
3
3
|
const inspect = Symbol.for('nodejs.util.inspect.custom')
|
|
4
4
|
|
|
5
5
|
const TYPES = {
|
|
@@ -160,7 +160,9 @@ module.exports.declare = (type, options) => {
|
|
|
160
160
|
case TYPES.TVP:
|
|
161
161
|
return `${assertSafeTypeName(options.tvpType)} readonly`
|
|
162
162
|
default:
|
|
163
|
-
|
|
163
|
+
// Every type in TYPES has a declaration of one word. Any other object passed as a type
|
|
164
|
+
// writes its own, so it is checked, and read once.
|
|
165
|
+
return assertSafeTypeDeclaration(type.declaration)
|
|
164
166
|
}
|
|
165
167
|
}
|
|
166
168
|
|
|
@@ -4,7 +4,8 @@ const msnodesql = require('msnodesqlv8')
|
|
|
4
4
|
const debug = require('debug')('mssql:msv8')
|
|
5
5
|
const BaseRequest = require('../base/request')
|
|
6
6
|
const RequestError = require('../error/request-error')
|
|
7
|
-
const
|
|
7
|
+
const MSSQLError = require('../error/mssql-error')
|
|
8
|
+
const { IDS, objectHasProperty, isValidParameterName, assertSafeColumnName, assertSafeTableName, assertSafeTypeName, assertSafeTypeSize, assertSafeProcedureName } = require('../utils')
|
|
8
9
|
const { TYPES, DECLARATIONS, declare } = require('../datatypes')
|
|
9
10
|
const { PARSERS: UDT } = require('../udt')
|
|
10
11
|
const Table = require('../table')
|
|
@@ -14,6 +15,81 @@ const JSON_COLUMN_ID = 'JSON_F52E2B61-18A1-11d1-B105-00805F49916B'
|
|
|
14
15
|
const XML_COLUMN_ID = 'XML_F52E2B61-18A1-11d1-B105-00805F49916B'
|
|
15
16
|
const EMPTY_BUFFER = Buffer.alloc(0)
|
|
16
17
|
|
|
18
|
+
// msnodesqlv8 bulk loads through its table manager, which looks the table up by writing the
|
|
19
|
+
// name it is given into the text of a query of its own, splitting it on every `.` to do so.
|
|
20
|
+
// The last part, the table, and the one before it, the schema, are written inside quoted
|
|
21
|
+
// strings, which only a `'` can end, and a doubled one is how a string holds it. The part
|
|
22
|
+
// before the schema is the database, which is written bare, as an identifier, and also inside
|
|
23
|
+
// one of those strings. Any part before the database is held to the same rule, although the
|
|
24
|
+
// table manager drops it. The name of a table in tempdb is also written bare, whole, as the
|
|
25
|
+
// target of the INSERT that the table manager builds once it has found the table. A bare part
|
|
26
|
+
// may hold the characters a parameter name may (see lib/utils.js): those that cannot end an
|
|
27
|
+
// identifier.
|
|
28
|
+
const isBarePart = part => isValidParameterName(part)
|
|
29
|
+
// The database, and each part of the name of a table in tempdb, may also have space around it,
|
|
30
|
+
// which is read as space between words, or be in double quotes. In double quotes it is a quoted
|
|
31
|
+
// identifier, which only a `"` can end, or, with QUOTED_IDENTIFIER off, a string where no string
|
|
32
|
+
// is allowed, so the query does not compile and nothing in it runs. Neither form may hold a `'`.
|
|
33
|
+
// The database is also written inside a string, which a `'` would end, and in the INSERT a `'`
|
|
34
|
+
// would start one. The server reads NEL and ZERO WIDTH SPACE as space too, but `\s` does not
|
|
35
|
+
// match them.
|
|
36
|
+
const PADDING = /^[\s\u0085\u200b]+|[\s\u0085\u200b]+$/g
|
|
37
|
+
const isDatabasePart = part => {
|
|
38
|
+
const trimmed = part.replace(PADDING, '')
|
|
39
|
+
return isBarePart(trimmed) || /^"[^"']+"$/.test(trimmed)
|
|
40
|
+
}
|
|
41
|
+
const endsQuotedString = part => part.replace(/''/g, '').includes('\'')
|
|
42
|
+
// The table manager puts each part into its query with String.prototype.replace. That reads $`
|
|
43
|
+
// in the part as the text of the query before the placeholder, $' as the text after it, and $&
|
|
44
|
+
// as the placeholder. A name that holds one of these does not name the table it seems to. The
|
|
45
|
+
// text it copies brings the quotes of the query with it, so these are rejected in every part.
|
|
46
|
+
const COPIES_QUERY = /\$[`'&]/
|
|
47
|
+
|
|
48
|
+
// Takes the name the table manager is to be given, and returns what was read, so the name it
|
|
49
|
+
// is given is the one that was checked.
|
|
50
|
+
const assertSafeBulkTable = (name) => {
|
|
51
|
+
const table = String(name)
|
|
52
|
+
const parts = table.split('.')
|
|
53
|
+
if (parts[parts.length - 1].charAt(0) === '#') {
|
|
54
|
+
if (!parts.every(isBarePart)) {
|
|
55
|
+
throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 writes the name of a temporary table unquoted, so it may only contain identifier characters.`, 'EINJECT')
|
|
56
|
+
}
|
|
57
|
+
} else if (!parts.slice(0, -2).every(isDatabasePart)) {
|
|
58
|
+
throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 writes the database name unquoted, so it may only contain identifier characters, or be in double quotes and contain no '.`, 'EINJECT')
|
|
59
|
+
} else if (parts.slice(-2).some(endsQuotedString)) {
|
|
60
|
+
throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 writes the table and schema names into a quoted string, which a ' would end.`, 'EINJECT')
|
|
61
|
+
} else if (COPIES_QUERY.test(table)) {
|
|
62
|
+
throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 replaces $\`, $' and $& in a table name with parts of its own query.`, 'EINJECT')
|
|
63
|
+
}
|
|
64
|
+
return table
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Checked once the table manager has found the table, against what it found, since that is
|
|
68
|
+
// what it builds its INSERT from. A table in tempdb is written as the name it was given, so
|
|
69
|
+
// each part of that name is held to the database rule above. The connection's own database
|
|
70
|
+
// can be tempdb, so the name need not say so. Any other table is written as
|
|
71
|
+
// `[database].[schema].[table]`, from the names the server reported, and each column it writes
|
|
72
|
+
// to as `[name]`. In both, any `]` in a name is left as it is. The columns it writes to are
|
|
73
|
+
// those it does not count as read only. A driver without `isReadOnly()` on its columns, such
|
|
74
|
+
// as 2.0.0, counts these flags instead.
|
|
75
|
+
const isReadOnlyColumn = col => typeof col.isReadOnly === 'function'
|
|
76
|
+
? col.isReadOnly()
|
|
77
|
+
: (col.is_identity || col.is_computed || col.is_hidden || col.generated_always_type)
|
|
78
|
+
|
|
79
|
+
const assertSafeBulkInsert = (table, columns) => {
|
|
80
|
+
if (columns[0].table_catalog === 'tempdb' && !table.split('.').every(isDatabasePart)) {
|
|
81
|
+
throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 writes the name of a table in tempdb unquoted, so each part may only contain identifier characters, or be in double quotes and contain no '.`, 'EINJECT')
|
|
82
|
+
}
|
|
83
|
+
if (columns[0].table_catalog !== 'tempdb' && ['table_catalog', 'table_schema', 'table_name'].some(k => String(columns[0][k]).includes(']'))) {
|
|
84
|
+
throw new MSSQLError(`Invalid table name '${columns[0].table_catalog}.${columns[0].table_schema}.${columns[0].table_name}'. msnodesqlv8 cannot bulk load into a table whose name contains ']'.`, 'EINJECT')
|
|
85
|
+
}
|
|
86
|
+
for (const col of columns) {
|
|
87
|
+
if (!isReadOnlyColumn(col) && String(col.name).includes(']')) {
|
|
88
|
+
throw new MSSQLError(`Invalid column name '${col.name}'. msnodesqlv8 cannot bulk load into a column whose name contains ']'.`, 'EINJECT')
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
17
93
|
const castParameter = function (value, type) {
|
|
18
94
|
if (value == null) {
|
|
19
95
|
if ((type === TYPES.Binary) || (type === TYPES.VarBinary) || (type === TYPES.Image)) {
|
|
@@ -165,6 +241,9 @@ class Request extends BaseRequest {
|
|
|
165
241
|
assertSafeTypeSize(col.precision)
|
|
166
242
|
assertSafeTypeSize(col.scale)
|
|
167
243
|
})
|
|
244
|
+
// `create table` takes the table's path and name as they are; they are checked again
|
|
245
|
+
// where it is written. Without `create`, this driver writes neither into SQL.
|
|
246
|
+
if (table.create) table.declare()
|
|
168
247
|
// checked here too, so an ordering key is accepted or rejected the same way on
|
|
169
248
|
// either driver even though this one does not build the statement itself
|
|
170
249
|
if (options && options.order) {
|
|
@@ -182,6 +261,17 @@ class Request extends BaseRequest {
|
|
|
182
261
|
return setImmediate(callback, new RequestError("You can't use table variables for bulk insert.", 'ENAME'))
|
|
183
262
|
}
|
|
184
263
|
|
|
264
|
+
// The table manager is given the path with its brackets removed, as before, and it is
|
|
265
|
+
// given the string that is checked here. The check is made before a connection is
|
|
266
|
+
// borrowed, and on the path rather than where the table is built, because `path` is a
|
|
267
|
+
// plain property that can be changed after the table is built.
|
|
268
|
+
let target
|
|
269
|
+
try {
|
|
270
|
+
target = assertSafeBulkTable(table.path.replace(/\[|\]/g, ''))
|
|
271
|
+
} catch (e) {
|
|
272
|
+
return callback(new RequestError(e, 'EREQUEST'))
|
|
273
|
+
}
|
|
274
|
+
|
|
185
275
|
this.parent.acquire(this, (err, connection) => {
|
|
186
276
|
let hasReturned = false
|
|
187
277
|
if (!err) {
|
|
@@ -223,13 +313,20 @@ class Request extends BaseRequest {
|
|
|
223
313
|
|
|
224
314
|
const go = () => {
|
|
225
315
|
const tm = connection.tableMgr()
|
|
226
|
-
|
|
316
|
+
// the table manager reports a failed lookup as (null, err), not error first
|
|
317
|
+
return tm.bind(target, (mgr, err) => {
|
|
318
|
+
if (err) {
|
|
319
|
+
return done(err)
|
|
320
|
+
}
|
|
321
|
+
|
|
227
322
|
if (mgr.columns.length === 0) {
|
|
228
323
|
return done(new RequestError('Table was not found on the server.', 'ENAME'))
|
|
229
324
|
}
|
|
230
325
|
|
|
231
326
|
const rows = []
|
|
232
327
|
try {
|
|
328
|
+
assertSafeBulkInsert(target, mgr.columns)
|
|
329
|
+
|
|
233
330
|
for (const col of table.columns) {
|
|
234
331
|
// re-checked here for the same reason as the name below, in case the
|
|
235
332
|
// definition changed since it was checked above
|
|
@@ -259,17 +356,12 @@ class Request extends BaseRequest {
|
|
|
259
356
|
}
|
|
260
357
|
|
|
261
358
|
if (table.create) {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
objectid = `tempdb..[${table.name}]`
|
|
265
|
-
} else {
|
|
266
|
-
objectid = table.path
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
// A connection is held from here on, so a column name that changed since it
|
|
270
|
-
// was checked above must be reported through `done`, which releases it.
|
|
359
|
+
// A connection is held from here on, so a column name, or the path, that changed
|
|
360
|
+
// since it was checked above must be reported through `done`, which releases it.
|
|
271
361
|
let statement
|
|
272
362
|
try {
|
|
363
|
+
// the path as it is checked and written, so the table looked up is the one created
|
|
364
|
+
const objectid = table.temporary ? `tempdb..[${table.name}]` : assertSafeTableName(table.path)
|
|
273
365
|
statement = `if object_id('${objectid.replace(/'/g, '\'\'')}') is null ${table.declare()}`
|
|
274
366
|
} catch (e) {
|
|
275
367
|
return done(e)
|
package/lib/table.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
const TYPES = require('./datatypes').TYPES
|
|
4
4
|
const declareType = require('./datatypes').declare
|
|
5
|
-
const
|
|
5
|
+
const MSSQLError = require('./error/mssql-error')
|
|
6
|
+
const { objectHasProperty, assertSafeColumnName, assertSafeTableName } = require('./utils')
|
|
6
7
|
|
|
7
8
|
const MAX = 65535 // (1 << 16) - 1
|
|
8
9
|
const JSON_COLUMN_ID = 'JSON_F52E2B61-18A1-11d1-B105-00805F49916B'
|
|
@@ -99,6 +100,12 @@ Table.prototype._makeBulk = function _makeBulk () {
|
|
|
99
100
|
}
|
|
100
101
|
|
|
101
102
|
Table.prototype.declare = function declare () {
|
|
103
|
+
// The path and the name are written into the statement as they are. A table built from a name
|
|
104
|
+
// always has safe ones, but both are plain properties that can be changed after that, so they
|
|
105
|
+
// are checked here, where they are written: the path as a qualified name, and the name, which
|
|
106
|
+
// goes into the brackets of the primary key constraint's name, as a column name goes into its
|
|
107
|
+
// own brackets. Each is read once, so the value checked is the value written.
|
|
108
|
+
const path = assertSafeTableName(this.path)
|
|
102
109
|
const pkey = this.columns.filter(col => col.primary === true).map(col => `[${assertSafeColumnName(col.name)}]`)
|
|
103
110
|
const cols = this.columns.map(col => {
|
|
104
111
|
const def = [`[${assertSafeColumnName(col.name)}] ${declareType(col.type, col)}`]
|
|
@@ -116,8 +123,17 @@ Table.prototype.declare = function declare () {
|
|
|
116
123
|
return def.join(' ')
|
|
117
124
|
})
|
|
118
125
|
|
|
119
|
-
|
|
120
|
-
|
|
126
|
+
let constraint = ''
|
|
127
|
+
if (pkey.length > 1) {
|
|
128
|
+
const name = String(this.name)
|
|
129
|
+
// checked as it is written, after the `#` of a temporary table's name is dropped
|
|
130
|
+
const constraintName = `PK_${this.temporary ? name.substr(1) : name}`
|
|
131
|
+
if (constraintName.replace(/]]/g, '').includes(']')) {
|
|
132
|
+
throw new MSSQLError(`Invalid table name '${name}'. A ']' in a table name must be written as ']]'.`, 'EINJECT')
|
|
133
|
+
}
|
|
134
|
+
constraint = `, constraint [${constraintName}] primary key (${pkey.join(', ')})`
|
|
135
|
+
}
|
|
136
|
+
return `create table ${path} (${cols.join(', ')}${constraint})`
|
|
121
137
|
}
|
|
122
138
|
|
|
123
139
|
Table.fromRecordset = function fromRecordset (recordset, name) {
|
package/lib/tedious/request.js
CHANGED
|
@@ -4,7 +4,7 @@ const tds = require('tedious')
|
|
|
4
4
|
const debug = require('debug')('mssql:tedi')
|
|
5
5
|
const BaseRequest = require('../base/request')
|
|
6
6
|
const RequestError = require('../error/request-error')
|
|
7
|
-
const { IDS, objectHasProperty, assertSafeColumnName, assertSafeTypeName, assertSafeTypeSize, assertSafeProcedureName } = require('../utils')
|
|
7
|
+
const { IDS, objectHasProperty, assertSafeColumnName, assertSafeTableName, assertSafeTypeName, assertSafeTypeSize, assertSafeProcedureName } = require('../utils')
|
|
8
8
|
const { TYPES, DECLARATIONS, declare, cast } = require('../datatypes')
|
|
9
9
|
const Table = require('../table')
|
|
10
10
|
const { PARSERS: UDT } = require('../udt')
|
|
@@ -23,6 +23,18 @@ const N_TYPES = {
|
|
|
23
23
|
NumericN: 0x6C
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
+
// A bulk load needs a tedious type for every column: one of sql.TYPES, which maps to one, or a
|
|
27
|
+
// tedious type given directly. tedious calls the type's declaration() when it writes the
|
|
28
|
+
// statement, after a connection has been taken, and would throw for anything else, so anything
|
|
29
|
+
// else is refused first.
|
|
30
|
+
const getTediousBulkType = function (col) {
|
|
31
|
+
const type = getTediousType(col.type)
|
|
32
|
+
if (!type || typeof type.declaration !== 'function') {
|
|
33
|
+
throw new Error(`Column '${col.name}' has a type that the tedious driver cannot bulk load.`)
|
|
34
|
+
}
|
|
35
|
+
return type
|
|
36
|
+
}
|
|
37
|
+
|
|
26
38
|
const getTediousType = function (type) {
|
|
27
39
|
switch (type) {
|
|
28
40
|
case TYPES.VarChar: return tds.TYPES.VarChar
|
|
@@ -221,7 +233,14 @@ class Request extends BaseRequest {
|
|
|
221
233
|
table._makeBulk()
|
|
222
234
|
// Checked before a connection is borrowed, so that a rejected name cannot leave
|
|
223
235
|
// the pool short of one.
|
|
224
|
-
table.columns.forEach(col =>
|
|
236
|
+
table.columns.forEach(col => {
|
|
237
|
+
assertSafeColumnName(col.name)
|
|
238
|
+
getTediousBulkType(col)
|
|
239
|
+
})
|
|
240
|
+
// tedious writes the path as it is into `insert bulk`, and so does `create table`, which
|
|
241
|
+
// also takes the table's name; both are checked again where they are written.
|
|
242
|
+
assertSafeTableName(table.path)
|
|
243
|
+
if (table.create) table.declare()
|
|
225
244
|
// tedious writes these into `insert bulk ... WITH (ORDER (<key> <direction>))`
|
|
226
245
|
// UNQUOTED — unlike a column name, which it emits as `[name]`. So the quoted-identifier
|
|
227
246
|
// rule does not apply here: what matters is that the key cannot end the clause. It is
|
|
@@ -355,16 +374,17 @@ class Request extends BaseRequest {
|
|
|
355
374
|
.map(([key, direction]) => [assertSafeTypeName(key), direction]))
|
|
356
375
|
})
|
|
357
376
|
}
|
|
358
|
-
bulk = connection.newBulkLoad(table.path, bulkOptions, done)
|
|
377
|
+
bulk = connection.newBulkLoad(assertSafeTableName(table.path), bulkOptions, done)
|
|
359
378
|
for (const col of table.columns) {
|
|
360
379
|
// tedious emits this name as a quoted identifier of its own when it builds
|
|
361
380
|
// the `insert bulk` statement, so it is checked here as well as in
|
|
362
381
|
// Table#declare, in case the name changed since it was checked above.
|
|
363
|
-
bulk.addColumn(assertSafeColumnName(col.name),
|
|
382
|
+
bulk.addColumn(assertSafeColumnName(col.name), getTediousBulkType(col), { nullable: col.nullable, length: assertSafeTypeSize(col.length), scale: assertSafeTypeSize(col.scale), precision: assertSafeTypeSize(col.precision) })
|
|
364
383
|
}
|
|
365
384
|
|
|
366
385
|
if (table.create) {
|
|
367
|
-
|
|
386
|
+
// the path as it is checked and written, so the table looked up is the one created
|
|
387
|
+
const objectid = table.temporary ? `tempdb..[${table.name}]` : assertSafeTableName(table.path)
|
|
368
388
|
statement = `if object_id('${objectid.replace(/'/g, '\'\'')}') is null ${table.declare()}`
|
|
369
389
|
}
|
|
370
390
|
} catch (e) {
|
|
@@ -5,6 +5,15 @@ const BaseTransaction = require('../base/transaction')
|
|
|
5
5
|
const { IDS } = require('../utils')
|
|
6
6
|
const TransactionError = require('../error/transaction-error')
|
|
7
7
|
|
|
8
|
+
// From TDS 7.2 the driver sends the transaction name in a transaction manager request, where it
|
|
9
|
+
// is data. Before 7.2 it writes `BEGIN TRAN <name>` into a SQL batch instead, and there a bare
|
|
10
|
+
// name is read as SQL: whitespace, `;`, `:` or a comment ends it, and even a lone keyword such as
|
|
11
|
+
// `commit` runs as a statement of its own. So on those versions the name is sent as a quoted
|
|
12
|
+
// identifier, with `]`, the only character that can end it, doubled. The server then stores
|
|
13
|
+
// exactly the name given, as it does on the newer versions. An empty name means no name, and an
|
|
14
|
+
// empty quoted identifier is not allowed, so it is sent as it is.
|
|
15
|
+
const quoteTransactionName = (name) => name === '' ? name : `[${name.replace(/]/g, ']]')}]`
|
|
16
|
+
|
|
8
17
|
class Transaction extends BaseTransaction {
|
|
9
18
|
constructor (parent) {
|
|
10
19
|
super(parent)
|
|
@@ -32,6 +41,23 @@ class Transaction extends BaseTransaction {
|
|
|
32
41
|
super._begin(isolationLevel, err => {
|
|
33
42
|
if (err) return callback(err)
|
|
34
43
|
|
|
44
|
+
// Read once: the name checked here is the name sent, whatever a later read would return.
|
|
45
|
+
let name
|
|
46
|
+
try {
|
|
47
|
+
name = this.name
|
|
48
|
+
} catch (err) {
|
|
49
|
+
return callback(err)
|
|
50
|
+
}
|
|
51
|
+
if (name == null) name = ''
|
|
52
|
+
if (typeof name !== 'string') {
|
|
53
|
+
return callback(new TransactionError('Invalid transaction name. A transaction name must be a string.', 'EINJECT'))
|
|
54
|
+
}
|
|
55
|
+
// The server refuses a name longer than 32 UTF-16 code units, which is what length counts.
|
|
56
|
+
// Refuse it here, before a connection is taken, so that a name cannot cost one.
|
|
57
|
+
if (name.length > 32) {
|
|
58
|
+
return callback(new TransactionError('Invalid transaction name. A transaction name may be at most 32 characters long.', 'EINJECT'))
|
|
59
|
+
}
|
|
60
|
+
|
|
35
61
|
debug('transaction(%d): begin', IDS.get(this))
|
|
36
62
|
|
|
37
63
|
this.parent.acquire(this, (err, connection, config) => {
|
|
@@ -41,13 +67,17 @@ class Transaction extends BaseTransaction {
|
|
|
41
67
|
this._acquiredConnection.on('rollbackTransaction', this._abort)
|
|
42
68
|
this._acquiredConfig = config
|
|
43
69
|
|
|
70
|
+
// The driver records the TDS version the server agreed at login here, and makes the same
|
|
71
|
+
// comparison to decide how to send the name.
|
|
72
|
+
const sentName = connection.config.options.tdsVersion < '7_2' ? quoteTransactionName(name) : name
|
|
73
|
+
|
|
44
74
|
connection.beginTransaction(err => {
|
|
45
75
|
if (err) err = new TransactionError(err)
|
|
46
76
|
|
|
47
77
|
debug('transaction(%d): begun', IDS.get(this))
|
|
48
78
|
|
|
49
79
|
callback(err)
|
|
50
|
-
},
|
|
80
|
+
}, sentName, this.isolationLevel)
|
|
51
81
|
})
|
|
52
82
|
})
|
|
53
83
|
}
|
package/lib/utils.js
CHANGED
|
@@ -30,6 +30,13 @@ const QUALIFIED_NAME_PART = '(?:\\[(?:[^\\]]|\\]\\])*\\]|"(?:[^"]|"")*"|[\\p{L}\
|
|
|
30
30
|
// T-SQL — but the first and last parts must be present, so a bare `.`, a leading `.proc`
|
|
31
31
|
// and a trailing `db..` are still refused. An empty part cannot end the identifier.
|
|
32
32
|
const QUALIFIED_NAME = new RegExp(`^(?:${QUALIFIED_NAME_PART}(?:\\.${QUALIFIED_NAME_PART}?)*\\.)?${QUALIFIED_NAME_PART}$`, 'u')
|
|
33
|
+
// A type that is not one of sql.TYPES declares itself, and its declaration takes the same form,
|
|
34
|
+
// optionally with a size after it: one or two numbers, or the word `max`, in parentheses.
|
|
35
|
+
const TYPE_DECLARATION = new RegExp(`^(?:${QUALIFIED_NAME_PART}(?:\\.${QUALIFIED_NAME_PART}?)*\\.)?${QUALIFIED_NAME_PART}(?:\\s*\\(\\s*(?:\\d+|max)\\s*(?:,\\s*\\d+\\s*)?\\))?$`, 'iu')
|
|
36
|
+
// A table's path has the same form, but a bare part may hold every character a parameter name
|
|
37
|
+
// may (see PARAM_NAME above), which the server reads as part of an identifier.
|
|
38
|
+
const TABLE_NAME_PART = '(?:\\[(?:[^\\]]|\\]\\])*\\]|"(?:[^"]|"")*"|(?:[\\p{L}\\p{N}\\p{M}\\p{Pc}@#$・・]|\\u200C|\\u200D)+)'
|
|
39
|
+
const TABLE_NAME = new RegExp(`^(?:${TABLE_NAME_PART}(?:\\.${TABLE_NAME_PART}?)*\\.)?${TABLE_NAME_PART}$`, 'u')
|
|
33
40
|
|
|
34
41
|
// A length, precision or scale is emitted into the same declaration. `max` is the only
|
|
35
42
|
// word the declaration takes there; everything else the server wants is a number.
|
|
@@ -74,6 +81,25 @@ module.exports = {
|
|
|
74
81
|
}
|
|
75
82
|
return procedure
|
|
76
83
|
},
|
|
84
|
+
assertSafeTypeDeclaration: (declaration) => {
|
|
85
|
+
// Read once, and return what was read, for the same reason as the type name.
|
|
86
|
+
const type = String(declaration).trim()
|
|
87
|
+
if (!TYPE_DECLARATION.test(type)) {
|
|
88
|
+
throw new MSSQLError(`Invalid type declaration '${type}'. A type may only be declared with identifier characters, unless a part is in brackets or double quotes, and a size in parentheses.`, 'EINJECT')
|
|
89
|
+
}
|
|
90
|
+
return type
|
|
91
|
+
},
|
|
92
|
+
assertSafeTableName: (name) => {
|
|
93
|
+
// A table's path is written as it is into `create table` and into tedious's `insert bulk`.
|
|
94
|
+
// A table built from a name always has a path whose parts are in brackets, but `path` is a
|
|
95
|
+
// plain property that can be changed after that, so it is checked where it is written.
|
|
96
|
+
// Read once, and return what was read, for the same reason as the type name.
|
|
97
|
+
const table = String(name).trim()
|
|
98
|
+
if (!TABLE_NAME.test(table)) {
|
|
99
|
+
throw new MSSQLError(`Invalid table name '${table}'. A table name may only contain identifier characters, unless a part is in brackets or double quotes.`, 'EINJECT')
|
|
100
|
+
}
|
|
101
|
+
return table
|
|
102
|
+
},
|
|
77
103
|
assertSafeTypeSize: (value) => {
|
|
78
104
|
if (value == null || typeof value === 'number') {
|
|
79
105
|
return value
|