1 | 'use strict'
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | var types = require('pg-types')
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | var 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 |
|
30 | var matchRegexp = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/
|
31 |
|
32 |
|
33 | Result.prototype.addCommandComplete = function (msg) {
|
34 | var match
|
35 | if (msg.text) {
|
36 |
|
37 | match = matchRegexp.exec(msg.text)
|
38 | } else {
|
39 |
|
40 | match = matchRegexp.exec(msg.command)
|
41 | }
|
42 | if (match) {
|
43 | this.command = match[1]
|
44 | if (match[3]) {
|
45 |
|
46 | this.oid = parseInt(match[2], 10)
|
47 | this.rowCount = parseInt(match[3], 10)
|
48 | } else if (match[2]) {
|
49 |
|
50 | this.rowCount = parseInt(match[2], 10)
|
51 | }
|
52 | }
|
53 | }
|
54 |
|
55 | Result.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 |
|
68 | Result.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 |
|
82 | Result.prototype.addRow = function (row) {
|
83 | this.rows.push(row)
|
84 | }
|
85 |
|
86 | Result.prototype.addFields = function (fieldDescriptions) {
|
87 |
|
88 |
|
89 |
|
90 |
|
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 |
|
105 | module.exports = Result
|