index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict'
  2. const Client = require('./client')
  3. const defaults = require('./defaults')
  4. const Connection = require('./connection')
  5. const Result = require('./result')
  6. const utils = require('./utils')
  7. const Pool = require('pg-pool')
  8. const TypeOverrides = require('./type-overrides')
  9. const { DatabaseError } = require('pg-protocol')
  10. const { escapeIdentifier, escapeLiteral } = require('./utils')
  11. const poolFactory = (Client) => {
  12. return class BoundPool extends Pool {
  13. constructor(options) {
  14. super(options, Client)
  15. }
  16. }
  17. }
  18. const PG = function (clientConstructor) {
  19. this.defaults = defaults
  20. this.Client = clientConstructor
  21. this.Query = this.Client.Query
  22. this.Pool = poolFactory(this.Client)
  23. this._pools = []
  24. this.Connection = Connection
  25. this.types = require('pg-types')
  26. this.DatabaseError = DatabaseError
  27. this.TypeOverrides = TypeOverrides
  28. this.escapeIdentifier = escapeIdentifier
  29. this.escapeLiteral = escapeLiteral
  30. this.Result = Result
  31. this.utils = utils
  32. }
  33. let clientConstructor = Client
  34. let forceNative = false
  35. try {
  36. forceNative = !!process.env.NODE_PG_FORCE_NATIVE
  37. } catch {
  38. // ignore, e.g., Deno without --allow-env
  39. }
  40. if (forceNative) {
  41. clientConstructor = require('./native')
  42. }
  43. module.exports = new PG(clientConstructor)
  44. // lazy require native module...the native module may not have installed
  45. Object.defineProperty(module.exports, 'native', {
  46. configurable: true,
  47. enumerable: false,
  48. get() {
  49. let native = null
  50. try {
  51. native = new PG(require('./native'))
  52. } catch (err) {
  53. if (err.code !== 'MODULE_NOT_FOUND') {
  54. throw err
  55. }
  56. }
  57. // overwrite module.exports.native so that getter is never called again
  58. Object.defineProperty(module.exports, 'native', {
  59. value: native,
  60. })
  61. return native
  62. },
  63. })