query.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. 'use strict'
  2. const { EventEmitter } = require('events')
  3. const Result = require('./result')
  4. const utils = require('./utils')
  5. class Query extends EventEmitter {
  6. constructor(config, values, callback) {
  7. super()
  8. config = utils.normalizeQueryConfig(config, values, callback)
  9. this.text = config.text
  10. this.values = config.values
  11. this.rows = config.rows
  12. this.types = config.types
  13. this.name = config.name
  14. this.binary = config.binary
  15. // use unique portal name each time
  16. this.portal = config.portal || ''
  17. this.callback = config.callback
  18. this._rowMode = config.rowMode
  19. if (process.domain && config.callback) {
  20. this.callback = process.domain.bind(config.callback)
  21. }
  22. this._result = new Result(this._rowMode, this.types)
  23. // potential for multiple results
  24. this._results = this._result
  25. this.isPreparedStatement = false
  26. this._canceledDueToError = false
  27. this._promise = null
  28. }
  29. requiresPreparation() {
  30. // named queries must always be prepared
  31. if (this.name) {
  32. return true
  33. }
  34. // always prepare if there are max number of rows expected per
  35. // portal execution
  36. if (this.rows) {
  37. return true
  38. }
  39. // don't prepare empty text queries
  40. if (!this.text) {
  41. return false
  42. }
  43. // prepare if there are values
  44. if (!this.values) {
  45. return false
  46. }
  47. return this.values.length > 0
  48. }
  49. _checkForMultirow() {
  50. // if we already have a result with a command property
  51. // then we've already executed one query in a multi-statement simple query
  52. // turn our results into an array of results
  53. if (this._result.command) {
  54. if (!Array.isArray(this._results)) {
  55. this._results = [this._result]
  56. }
  57. this._result = new Result(this._rowMode, this.types)
  58. this._results.push(this._result)
  59. }
  60. }
  61. // associates row metadata from the supplied
  62. // message with this query object
  63. // metadata used when parsing row results
  64. handleRowDescription(msg) {
  65. this._checkForMultirow()
  66. this._result.addFields(msg.fields)
  67. this._accumulateRows = this.callback || !this.listeners('row').length
  68. }
  69. handleDataRow(msg) {
  70. let row
  71. if (this._canceledDueToError) {
  72. return
  73. }
  74. try {
  75. row = this._result.parseRow(msg.fields)
  76. } catch (err) {
  77. this._canceledDueToError = err
  78. return
  79. }
  80. this.emit('row', row, this._result)
  81. if (this._accumulateRows) {
  82. this._result.addRow(row)
  83. }
  84. }
  85. handleCommandComplete(msg, connection) {
  86. this._checkForMultirow()
  87. this._result.addCommandComplete(msg)
  88. // need to sync after each command complete of a prepared statement
  89. // if we were using a row count which results in multiple calls to _getRows
  90. if (this.rows) {
  91. connection.sync()
  92. }
  93. }
  94. // if a named prepared statement is created with empty query text
  95. // the backend will send an emptyQuery message but *not* a command complete message
  96. // since we pipeline sync immediately after execute we don't need to do anything here
  97. // unless we have rows specified, in which case we did not pipeline the intial sync call
  98. handleEmptyQuery(connection) {
  99. if (this.rows) {
  100. connection.sync()
  101. }
  102. }
  103. handleError(err, connection) {
  104. // need to sync after error during a prepared statement
  105. if (this._canceledDueToError) {
  106. err = this._canceledDueToError
  107. this._canceledDueToError = false
  108. }
  109. // if callback supplied do not emit error event as uncaught error
  110. // events will bubble up to node process
  111. if (this.callback) {
  112. return this.callback(err)
  113. }
  114. this.emit('error', err)
  115. }
  116. handleReadyForQuery(con) {
  117. if (this._canceledDueToError) {
  118. return this.handleError(this._canceledDueToError, con)
  119. }
  120. if (this.callback) {
  121. this.callback(null, this._results)
  122. }
  123. this.emit('end', this._results)
  124. }
  125. submit(connection) {
  126. if (typeof this.text !== 'string' && typeof this.name !== 'string') {
  127. return new Error('A query must have either text or a name. Supplying neither is unsupported.')
  128. }
  129. const previous = connection.parsedStatements[this.name]
  130. if (this.text && previous && this.text !== previous) {
  131. return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`)
  132. }
  133. if (this.values && !Array.isArray(this.values)) {
  134. return new Error('Query values must be an array')
  135. }
  136. if (this.requiresPreparation()) {
  137. this.prepare(connection)
  138. } else {
  139. connection.query(this.text)
  140. }
  141. return null
  142. }
  143. hasBeenParsed(connection) {
  144. return this.name && connection.parsedStatements[this.name]
  145. }
  146. handlePortalSuspended(connection) {
  147. this._getRows(connection, this.rows)
  148. }
  149. _getRows(connection, rows) {
  150. connection.execute({
  151. portal: this.portal,
  152. rows: rows,
  153. })
  154. // if we're not reading pages of rows send the sync command
  155. // to indicate the pipeline is finished
  156. if (!rows) {
  157. connection.sync()
  158. } else {
  159. // otherwise flush the call out to read more rows
  160. connection.flush()
  161. }
  162. }
  163. // http://developer.postgresql.org/pgdocs/postgres/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY
  164. prepare(connection) {
  165. // prepared statements need sync to be called after each command
  166. // complete or when an error is encountered
  167. this.isPreparedStatement = true
  168. // TODO refactor this poor encapsulation
  169. if (!this.hasBeenParsed(connection)) {
  170. connection.parse({
  171. text: this.text,
  172. name: this.name,
  173. types: this.types,
  174. })
  175. }
  176. // because we're mapping user supplied values to
  177. // postgres wire protocol compatible values it could
  178. // throw an exception, so try/catch this section
  179. try {
  180. connection.bind({
  181. portal: this.portal,
  182. statement: this.name,
  183. values: this.values,
  184. binary: this.binary,
  185. valueMapper: utils.prepareValue,
  186. })
  187. } catch (err) {
  188. this.handleError(err, connection)
  189. return
  190. }
  191. connection.describe({
  192. type: 'P',
  193. name: this.portal || '',
  194. })
  195. this._getRows(connection, this.rows)
  196. }
  197. handleCopyInResponse(connection) {
  198. connection.sendCopyFail('No source stream defined')
  199. }
  200. // eslint-disable-next-line no-unused-vars
  201. handleCopyData(msg, connection) {
  202. // noop
  203. }
  204. }
  205. module.exports = Query