prepared-statement.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. 'use strict'
  2. const debug = require('debug')('mssql:base')
  3. const { EventEmitter } = require('events')
  4. const { IDS, objectHasProperty } = require('../utils')
  5. const globalConnection = require('../global-connection')
  6. const { TransactionError, PreparedStatementError } = require('../error')
  7. const shared = require('../shared')
  8. const { TYPES, declare } = require('../datatypes')
  9. /**
  10. * Class PreparedStatement.
  11. *
  12. * IMPORTANT: Rememeber that each prepared statement means one reserved connection from the pool. Don't forget to unprepare a prepared statement!
  13. *
  14. * @property {String} statement Prepared SQL statement.
  15. */
  16. class PreparedStatement extends EventEmitter {
  17. /**
  18. * Creates a new Prepared Statement.
  19. *
  20. * @param {ConnectionPool|Transaction} [holder]
  21. */
  22. constructor (parent) {
  23. super()
  24. IDS.add(this, 'PreparedStatement')
  25. debug('ps(%d): created', IDS.get(this))
  26. this.parent = parent || globalConnection.pool
  27. this._handle = 0
  28. this.prepared = false
  29. this.parameters = {}
  30. }
  31. get connected () {
  32. return this.parent.connected
  33. }
  34. /**
  35. * Acquire connection from connection pool.
  36. *
  37. * @param {Request} request Request.
  38. * @param {ConnectionPool~acquireCallback} [callback] A callback which is called after connection has established, or an error has occurred. If omited, method returns Promise.
  39. * @return {PreparedStatement|Promise}
  40. */
  41. acquire (request, callback) {
  42. if (!this._acquiredConnection) {
  43. setImmediate(callback, new PreparedStatementError('Statement is not prepared. Call prepare() first.', 'ENOTPREPARED'))
  44. return this
  45. }
  46. if (this._activeRequest) {
  47. setImmediate(callback, new TransactionError("Can't acquire connection for the request. There is another request in progress.", 'EREQINPROG'))
  48. return this
  49. }
  50. this._activeRequest = request
  51. setImmediate(callback, null, this._acquiredConnection, this._acquiredConfig)
  52. return this
  53. }
  54. /**
  55. * Release connection back to the pool.
  56. *
  57. * @param {Connection} connection Previously acquired connection.
  58. * @return {PreparedStatement}
  59. */
  60. release (connection) {
  61. if (connection === this._acquiredConnection) {
  62. this._activeRequest = null
  63. }
  64. return this
  65. }
  66. /**
  67. * Add an input parameter to the prepared statement.
  68. *
  69. * @param {String} name Name of the input parameter without @ char.
  70. * @param {*} type SQL data type of input parameter.
  71. * @return {PreparedStatement}
  72. */
  73. input (name, type) {
  74. if ((/(--| |\/\*|\*\/|')/).test(name)) {
  75. throw new PreparedStatementError(`SQL injection warning for param '${name}'`, 'EINJECT')
  76. }
  77. if (arguments.length < 2) {
  78. throw new PreparedStatementError('Invalid number of arguments. 2 arguments expected.', 'EARGS')
  79. }
  80. if (type instanceof Function) {
  81. type = type()
  82. }
  83. if (objectHasProperty(this.parameters, name)) {
  84. throw new PreparedStatementError(`The parameter name ${name} has already been declared. Parameter names must be unique`, 'EDUPEPARAM')
  85. }
  86. this.parameters[name] = {
  87. name,
  88. type: type.type,
  89. io: 1,
  90. length: type.length,
  91. scale: type.scale,
  92. precision: type.precision,
  93. tvpType: type.tvpType
  94. }
  95. return this
  96. }
  97. /**
  98. * Replace an input parameter on the request.
  99. *
  100. * @param {String} name Name of the input parameter without @ char.
  101. * @param {*} [type] SQL data type of input parameter. If you omit type, module automaticaly decide which SQL data type should be used based on JS data type.
  102. * @param {*} value Input parameter value. `undefined` and `NaN` values are automatically converted to `null` values.
  103. * @return {Request}
  104. */
  105. replaceInput (name, type, value) {
  106. delete this.parameters[name]
  107. return this.input(name, type, value)
  108. }
  109. /**
  110. * Add an output parameter to the prepared statement.
  111. *
  112. * @param {String} name Name of the output parameter without @ char.
  113. * @param {*} type SQL data type of output parameter.
  114. * @return {PreparedStatement}
  115. */
  116. output (name, type) {
  117. if (/(--| |\/\*|\*\/|')/.test(name)) {
  118. throw new PreparedStatementError(`SQL injection warning for param '${name}'`, 'EINJECT')
  119. }
  120. if (arguments.length < 2) {
  121. throw new PreparedStatementError('Invalid number of arguments. 2 arguments expected.', 'EARGS')
  122. }
  123. if (type instanceof Function) type = type()
  124. if (objectHasProperty(this.parameters, name)) {
  125. throw new PreparedStatementError(`The parameter name ${name} has already been declared. Parameter names must be unique`, 'EDUPEPARAM')
  126. }
  127. this.parameters[name] = {
  128. name,
  129. type: type.type,
  130. io: 2,
  131. length: type.length,
  132. scale: type.scale,
  133. precision: type.precision
  134. }
  135. return this
  136. }
  137. /**
  138. * Replace an output parameter on the request.
  139. *
  140. * @param {String} name Name of the output parameter without @ char.
  141. * @param {*} type SQL data type of output parameter.
  142. * @return {PreparedStatement}
  143. */
  144. replaceOutput (name, type) {
  145. delete this.parameters[name]
  146. return this.output(name, type)
  147. }
  148. /**
  149. * Prepare a statement.
  150. *
  151. * @param {String} statement SQL statement to prepare.
  152. * @param {basicCallback} [callback] A callback which is called after preparation has completed, or an error has occurred. If omited, method returns Promise.
  153. * @return {PreparedStatement|Promise}
  154. */
  155. prepare (statement, callback) {
  156. if (typeof callback === 'function') {
  157. this._prepare(statement, callback)
  158. return this
  159. }
  160. return new shared.Promise((resolve, reject) => {
  161. this._prepare(statement, err => {
  162. if (err) return reject(err)
  163. resolve(this)
  164. })
  165. })
  166. }
  167. /**
  168. * @private
  169. * @param {String} statement
  170. * @param {basicCallback} callback
  171. */
  172. _prepare (statement, callback) {
  173. debug('ps(%d): prepare', IDS.get(this))
  174. if (typeof statement === 'function') {
  175. callback = statement
  176. statement = undefined
  177. }
  178. if (this.prepared) {
  179. return setImmediate(callback, new PreparedStatementError('Statement is already prepared.', 'EALREADYPREPARED'))
  180. }
  181. this.statement = statement || this.statement
  182. this.parent.acquire(this, (err, connection, config) => {
  183. if (err) return callback(err)
  184. this._acquiredConnection = connection
  185. this._acquiredConfig = config
  186. const req = new shared.driver.Request(this)
  187. req.stream = false
  188. req.output('handle', TYPES.Int)
  189. req.input('params', TYPES.NVarChar, ((() => {
  190. const result = []
  191. for (const name in this.parameters) {
  192. if (!objectHasProperty(this.parameters, name)) {
  193. continue
  194. }
  195. const param = this.parameters[name]
  196. result.push(`@${name} ${declare(param.type, param)}${param.io === 2 ? ' output' : ''}`)
  197. }
  198. return result
  199. })()).join(','))
  200. req.input('stmt', TYPES.NVarChar, this.statement)
  201. req.execute('sp_prepare', (err, result) => {
  202. if (err) {
  203. this.parent.release(this._acquiredConnection)
  204. this._acquiredConnection = null
  205. this._acquiredConfig = null
  206. return callback(err)
  207. }
  208. debug('ps(%d): prepared', IDS.get(this))
  209. this._handle = result.output.handle
  210. this.prepared = true
  211. callback(null)
  212. })
  213. })
  214. }
  215. /**
  216. * Execute a prepared statement.
  217. *
  218. * @param {Object} values An object whose names correspond to the names of parameters that were added to the prepared statement before it was prepared.
  219. * @param {basicCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
  220. * @return {Request|Promise}
  221. */
  222. execute (values, callback) {
  223. if (this.stream || (typeof callback === 'function')) {
  224. return this._execute(values, callback)
  225. }
  226. return new shared.Promise((resolve, reject) => {
  227. this._execute(values, (err, recordset) => {
  228. if (err) return reject(err)
  229. resolve(recordset)
  230. })
  231. })
  232. }
  233. /**
  234. * @private
  235. * @param {Object} values
  236. * @param {basicCallback} callback
  237. */
  238. _execute (values, callback) {
  239. const req = new shared.driver.Request(this)
  240. req.stream = this.stream
  241. req.input('handle', TYPES.Int, this._handle)
  242. // copy parameters with new values
  243. for (const name in this.parameters) {
  244. if (!objectHasProperty(this.parameters, name)) {
  245. continue
  246. }
  247. const param = this.parameters[name]
  248. req.parameters[name] = {
  249. name,
  250. type: param.type,
  251. io: param.io,
  252. value: values[name],
  253. length: param.length,
  254. scale: param.scale,
  255. precision: param.precision
  256. }
  257. }
  258. req.execute('sp_execute', (err, result) => {
  259. if (err) return callback(err)
  260. callback(null, result)
  261. })
  262. return req
  263. }
  264. /**
  265. * Unprepare a prepared statement.
  266. *
  267. * @param {basicCallback} [callback] A callback which is called after unpreparation has completed, or an error has occurred. If omited, method returns Promise.
  268. * @return {PreparedStatement|Promise}
  269. */
  270. unprepare (callback) {
  271. if (typeof callback === 'function') {
  272. this._unprepare(callback)
  273. return this
  274. }
  275. return new shared.Promise((resolve, reject) => {
  276. this._unprepare(err => {
  277. if (err) return reject(err)
  278. resolve()
  279. })
  280. })
  281. }
  282. /**
  283. * @private
  284. * @param {basicCallback} callback
  285. */
  286. _unprepare (callback) {
  287. debug('ps(%d): unprepare', IDS.get(this))
  288. if (!this.prepared) {
  289. return setImmediate(callback, new PreparedStatementError('Statement is not prepared. Call prepare() first.', 'ENOTPREPARED'))
  290. }
  291. if (this._activeRequest) {
  292. return setImmediate(callback, new TransactionError("Can't unprepare the statement. There is a request in progress.", 'EREQINPROG'))
  293. }
  294. const req = new shared.driver.Request(this)
  295. req.stream = false
  296. req.input('handle', TYPES.Int, this._handle)
  297. req.execute('sp_unprepare', err => {
  298. if (err) return callback(err)
  299. this.parent.release(this._acquiredConnection)
  300. this._acquiredConnection = null
  301. this._acquiredConfig = null
  302. this._handle = 0
  303. this.prepared = false
  304. debug('ps(%d): unprepared', IDS.get(this))
  305. return callback(null)
  306. })
  307. }
  308. }
  309. module.exports = PreparedStatement