PageRenderTime 26ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/node_modules/knex/src/dialects/postgres/index.js

https://gitlab.com/jonnyforney/beerbowerpainting
JavaScript | 197 lines | 182 code | 13 blank | 2 comment | 4 complexity | b4f12c582c509800338beaea33adacae MD5 | raw file
  1. // PostgreSQL
  2. // -------
  3. var _ = require('lodash')
  4. var inherits = require('inherits')
  5. var Client = require('../../client')
  6. var Promise = require('../../promise')
  7. var utils = require('./utils')
  8. var assign = require('lodash/object/assign')
  9. var QueryCompiler = require('./query/compiler')
  10. var ColumnCompiler = require('./schema/columncompiler')
  11. var TableCompiler = require('./schema/tablecompiler')
  12. var SchemaCompiler = require('./schema/compiler')
  13. var PGQueryStream;
  14. function Client_PG(config) {
  15. Client.apply(this, arguments)
  16. if (config.returning) {
  17. this.defaultReturning = config.returning;
  18. }
  19. if (config.searchPath) {
  20. this.searchPath = config.searchPath;
  21. }
  22. }
  23. inherits(Client_PG, Client)
  24. assign(Client_PG.prototype, {
  25. QueryCompiler: QueryCompiler,
  26. ColumnCompiler: ColumnCompiler,
  27. SchemaCompiler: SchemaCompiler,
  28. TableCompiler: TableCompiler,
  29. dialect: 'postgresql',
  30. driverName: 'pg',
  31. _driver: function() {
  32. return require('pg')
  33. },
  34. wrapIdentifier: function(value) {
  35. if (value === '*') return value;
  36. var matched = value.match(/(.*?)(\[[0-9]\])/);
  37. if (matched) return this.wrapIdentifier(matched[1]) + matched[2];
  38. return '"' + value.replace(/"/g, '""') + '"';
  39. },
  40. // Prep the bindings as needed by PostgreSQL.
  41. prepBindings: function(bindings, tz) {
  42. return _.map(bindings, function(binding) {
  43. return utils.prepareValue(binding, tz, this.valueForUndefined)
  44. }, this);
  45. },
  46. // Get a raw connection, called by the `pool` whenever a new
  47. // connection needs to be added to the pool.
  48. acquireRawConnection: function() {
  49. var client = this;
  50. return new Promise(function(resolver, rejecter) {
  51. var connection = new client.driver.Client(client.connectionSettings);
  52. connection.connect(function(err, connection) {
  53. if (err) return rejecter(err);
  54. connection.on('error', client.__endConnection.bind(client, connection));
  55. connection.on('end', client.__endConnection.bind(client, connection));
  56. if (!client.version) {
  57. return client.checkVersion(connection).then(function(version) {
  58. client.version = version;
  59. resolver(connection);
  60. });
  61. }
  62. resolver(connection);
  63. });
  64. }).tap(function setSearchPath(connection) {
  65. return client.setSchemaSearchPath(connection);
  66. });
  67. },
  68. // Used to explicitly close a connection, called internally by the pool
  69. // when a connection times out or the pool is shutdown.
  70. destroyRawConnection: function(connection, cb) {
  71. connection.end()
  72. cb()
  73. },
  74. // In PostgreSQL, we need to do a version check to do some feature
  75. // checking on the database.
  76. checkVersion: function(connection) {
  77. return new Promise(function(resolver, rejecter) {
  78. connection.query('select version();', function(err, resp) {
  79. if (err) return rejecter(err);
  80. resolver(/^PostgreSQL (.*?) /.exec(resp.rows[0].version)[1]);
  81. });
  82. });
  83. },
  84. // Position the bindings for the query. The escape sequence for question mark
  85. // is \? (e.g. knex.raw("\\?") since javascript requires '\' to be escaped too...)
  86. positionBindings: function(sql) {
  87. var questionCount = 0;
  88. return sql.replace(/(\\*)(\?)/g, function (match, escapes) {
  89. if (escapes.length % 2) {
  90. return '?';
  91. } else {
  92. questionCount++;
  93. return '$' + questionCount;
  94. }
  95. });
  96. },
  97. setSchemaSearchPath: function(connection, searchPath) {
  98. var path = (searchPath || this.searchPath);
  99. if (!path) return Promise.resolve(true);
  100. return new Promise(function(resolver, rejecter) {
  101. connection.query('set search_path to ' + path, function(err) {
  102. if (err) return rejecter(err);
  103. resolver(true);
  104. });
  105. });
  106. },
  107. _stream: function(connection, obj, stream, options) {
  108. PGQueryStream = process.browser ? undefined : require('pg-query-stream');
  109. var sql = obj.sql = this.positionBindings(obj.sql)
  110. return new Promise(function(resolver, rejecter) {
  111. var queryStream = connection.query(new PGQueryStream(sql, obj.bindings, options));
  112. queryStream.on('error', rejecter);
  113. // 'error' is not propagated by .pipe, but it breaks the pipe
  114. stream.on('error', rejecter);
  115. // 'end' IS propagated by .pipe, by default
  116. stream.on('end', resolver);
  117. queryStream.pipe(stream);
  118. });
  119. },
  120. // Runs the query on the specified connection, providing the bindings
  121. // and any other necessary prep work.
  122. _query: function(connection, obj) {
  123. var sql = obj.sql = this.positionBindings(obj.sql)
  124. if (obj.options) sql = _.extend({text: sql}, obj.options);
  125. return new Promise(function(resolver, rejecter) {
  126. connection.query(sql, obj.bindings, function(err, response) {
  127. if (err) return rejecter(err);
  128. obj.response = response;
  129. resolver(obj);
  130. });
  131. });
  132. },
  133. // Ensures the response is returned in the same format as other clients.
  134. processResponse: function(obj, runner) {
  135. var resp = obj.response;
  136. if (obj.output) return obj.output.call(runner, resp);
  137. if (obj.method === 'raw') return resp;
  138. var returning = obj.returning;
  139. if (resp.command === 'SELECT') {
  140. if (obj.method === 'first') return resp.rows[0];
  141. if (obj.method === 'pluck') return _.pluck(resp.rows, obj.pluck);
  142. return resp.rows;
  143. }
  144. if (returning) {
  145. var returns = [];
  146. for (var i = 0, l = resp.rows.length; i < l; i++) {
  147. var row = resp.rows[i];
  148. if (returning === '*' || Array.isArray(returning)) {
  149. returns[i] = row;
  150. } else {
  151. returns[i] = row[returning];
  152. }
  153. }
  154. return returns;
  155. }
  156. if (resp.command === 'UPDATE' || resp.command === 'DELETE') {
  157. return resp.rowCount;
  158. }
  159. return resp;
  160. },
  161. __endConnection: function(connection) {
  162. if (!connection || connection.__knex__disposed) return;
  163. if (this.pool) {
  164. connection.__knex__disposed = true;
  165. this.pool.destroy(connection);
  166. }
  167. },
  168. })
  169. module.exports = Client_PG