result.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. 'use strict'
  2. var types = require('pg-types')
  3. var matchRegexp = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/
  4. // result object returned from query
  5. // in the 'end' event and also
  6. // passed as second argument to provided callback
  7. class Result {
  8. constructor(rowMode, types) {
  9. this.command = null
  10. this.rowCount = null
  11. this.oid = null
  12. this.rows = []
  13. this.fields = []
  14. this._parsers = undefined
  15. this._types = types
  16. this.RowCtor = null
  17. this.rowAsArray = rowMode === 'array'
  18. if (this.rowAsArray) {
  19. this.parseRow = this._parseRowAsArray
  20. }
  21. }
  22. // adds a command complete message
  23. addCommandComplete(msg) {
  24. var match
  25. if (msg.text) {
  26. // pure javascript
  27. match = matchRegexp.exec(msg.text)
  28. } else {
  29. // native bindings
  30. match = matchRegexp.exec(msg.command)
  31. }
  32. if (match) {
  33. this.command = match[1]
  34. if (match[3]) {
  35. // COMMMAND OID ROWS
  36. this.oid = parseInt(match[2], 10)
  37. this.rowCount = parseInt(match[3], 10)
  38. } else if (match[2]) {
  39. // COMMAND ROWS
  40. this.rowCount = parseInt(match[2], 10)
  41. }
  42. }
  43. }
  44. _parseRowAsArray(rowData) {
  45. var row = new Array(rowData.length)
  46. for (var i = 0, len = rowData.length; i < len; i++) {
  47. var rawValue = rowData[i]
  48. if (rawValue !== null) {
  49. row[i] = this._parsers[i](rawValue)
  50. } else {
  51. row[i] = null
  52. }
  53. }
  54. return row
  55. }
  56. parseRow(rowData) {
  57. var row = {}
  58. for (var i = 0, len = rowData.length; i < len; i++) {
  59. var rawValue = rowData[i]
  60. var field = this.fields[i].name
  61. if (rawValue !== null) {
  62. row[field] = this._parsers[i](rawValue)
  63. } else {
  64. row[field] = null
  65. }
  66. }
  67. return row
  68. }
  69. addRow(row) {
  70. this.rows.push(row)
  71. }
  72. addFields(fieldDescriptions) {
  73. // clears field definitions
  74. // multiple query statements in 1 action can result in multiple sets
  75. // of rowDescriptions...eg: 'select NOW(); select 1::int;'
  76. // you need to reset the fields
  77. this.fields = fieldDescriptions
  78. if (this.fields.length) {
  79. this._parsers = new Array(fieldDescriptions.length)
  80. }
  81. for (var i = 0; i < fieldDescriptions.length; i++) {
  82. var desc = fieldDescriptions[i]
  83. if (this._types) {
  84. this._parsers[i] = this._types.getTypeParser(desc.dataTypeID, desc.format || 'text')
  85. } else {
  86. this._parsers[i] = types.getTypeParser(desc.dataTypeID, desc.format || 'text')
  87. }
  88. }
  89. }
  90. }
  91. module.exports = Result