UNPKG

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