{"_id":"@a-2-c-2-anpm/labore-voluptatibus-consectetur","name":"@a-2-c-2-anpm/labore-voluptatibus-consectetur","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"@a-2-c-2-anpm/labore-voluptatibus-consectetur","version":"1.0.0","description":"[![NPM version](http://img.shields.io/npm/v/@a-2-c-2-anpm/labore-voluptatibus-consectetur.svg?style=flat-square)](https://www.npmjs.org/package/@a-2-c-2-anpm/labore-voluptatibus-consectetur) [![Canonical Code Style](https://img.shields.io/badge/code%20sty","main":"index.js","author":{"name":"a-2-c-2-a"},"license":"MIT","dependencies":{"@a-2-c-2-anpm/alias-ducimus-sit":"^1.0.0","@a-2-c-2-anpm/atque-nemo-accusantium":"^1.0.0","@a-2-c-2-anpm/distinctio-quibusdam-culpa":"^1.0.0","@a-2-c-2-anpm/eligendi-praesentium-hic":"^1.0.0","@a-2-c-2-anpm/enim-amet-voluptatem":"^1.0.0","@a-2-c-2-anpm/error-dolorem-a":"^1.0.0","@a-2-c-2-anpm/excepturi-natus-facere":"^1.0.0","@a-2-c-2-anpm/expedita-recusandae-aut":"^1.0.0","@a-2-c-2-anpm/fugit-impedit-quae":"^1.0.0","@a-2-c-2-anpm/hic-maiores-accusantium":"^1.0.0","@a-2-c-2-anpm/laborum-exercitationem-quis":"^1.0.0","@a-2-c-2-anpm/laudantium-dolor-perspiciatis":"^1.0.0","@a-2-c-2-anpm/maiores-quis-dignissimos":"^1.0.0","@a-2-c-2-anpm/nam-eaque-occaecati":"^1.0.0","@a-2-c-2-anpm/neque-culpa-culpa":"^1.0.0","@a-2-c-2-anpm/neque-iste-eum":"^1.0.0","@a-2-c-2-anpm/nobis-similique-magni":"^1.0.0","@a-2-c-2-anpm/officia-tempore-ipsa":"^1.0.0","@a-2-c-2-anpm/perferendis-qui-suscipit":"^1.0.0","@a-2-c-2-anpm/placeat-suscipit-cumque":"^1.0.0","@a-2-c-2-anpm/quo-quia-expedita":"^1.0.0","@a-2-c-2-anpm/quos-voluptates-excepturi":"^1.0.0","@a-2-c-2-anpm/saepe-praesentium-iusto":"^1.0.0","@a-2-c-2-anpm/sint-ipsa-atque":"^1.0.0","@a-2-c-2-anpm/vitae-ad-molestiae":"^1.0.0","@ajhgwdjnpm/quas-mollitia-aspernatur-reprehenderit":"^1.0.0"},"keywords":["buffer","art","toobject","sigterm","ES2018","WebSockets","types","css nesting","metadata","popmotion","search","sharedarraybuffer","type","bdd","typesafe","dependencies","ponyfill","point-free","eslint","which","RFC-6455","terminal","optimizer","irq","iterate","chrome","ES5","directory","reducer","from","link","length","clone","ts","names","toArray","value","qs","delete","byte","ES2020","rangeerror","omit","pretty","HyBi","curried","configurable","tester","robust","es2018","worker","256","i18n","css","preserve-symlinks","collection","duplex","queue","fastclone","spec","classes","private","Symbol.toStringTag","ECMAScript 2015","weakset","RegExp#flags","consume","url","io-ts","util","stringify","three","transpile","package.json","-0","styling","auth","once","ender","jwt","warning","take","dayjs","private data","valid","computed-types","jsdom","classnames","drag","tdd","less compiler","open","client","push","exit","byteLength","var","querystring","hasOwn","dir","phone","shell","keys","up","superstruct","rate","electron","redux-toolkit","ECMAScript 2022","descriptors","obj","testing","native","full","extra","await","sanitization","async","trimRight","get","zero","mixins","output","internal","batch","Float64Array","Observable","_.extend","flat","ReactiveExtensions","less css","core-js","ajv","writable","rfc4122","wait","is","dataView","wrap","estree","json-schema","wget","watch","path","ECMAScript 2023","fastcopy","assert","command","argv","flatMap","tostringtag","east-asian-width","bundler","ECMAScript 7","expression","node","form-validation","tacit","pyyaml","listeners","invariant","set","awesomesauce","Object","mime-db","WebSocket","Array.prototype.contains","object","superagent","array","react pose","datastructure","dataview","buffers","bootstrap less","tslib","Rx","serialization","style","WeakSet","URLSearchParams","installer","fast-deep-copy","class-validator","css-in-js","symlinks","negative zero","uuid","Array.prototype.filter","compile less","rgb","multi-package","code points","censor","ReactiveX","traverse","equality","matches","yup","console","accessor","shebang","eventEmitter","make dir","es-abstract","rmdir","text","fullwidth","argument","arrays","mimetypes","accessibility","validate","weakmap","macos","chinese","arraybuffer","readable","ES3","reuse","test","slot","spring","graphql","regular expressions","typedarray","browserlist","equal","TypeScript","callbind","jQuery","performance","babel-core","env","rapid","typed","forms","hookform","0","Int32Array","mru","ECMAScript 5","protocol-buffers","symbols","findLastIndex","module","time","signals","password","offset","query","util.inspect","js","watching","guid","immer","Object.defineProperty","property","http","shim","package manager","framer","require","dotenv","values","flags","dom","ajax","gradients css3","Reflect.getPrototypeOf","transpiler","less.js","String.prototype.matchAll","config","styleguide","gradients css","ECMAScript 6","rm -rf","sanitize","write","web","error","ECMAScript 2017","settings","ramda","real-time","defineProperty","visual","shrinkwrap","gdpr","install","queueMicrotask","es7","toStringTag","korean","optimist","zod","dom-testing-library","iterator",".env","workspace:*","handlers","react animation","__proto__","input","typeof","sorted","isConcatSpreadable","call-bound","figlet","immutable","Object.keys","last","walking","es2017","ECMAScript 2019","matchAll","json","toSorted","@@toStringTag","Streams","deep-copy","let","trimLeft","process","minimal","ESnext","Array.prototype.flatten","serializer","nested css","coercible","flatten","performant","ArrayBuffer","plugin","limit","resolve","moment","json-schema-validation","option","whatwg","stream","animation","typescript","jest","URL","Array.prototype.flatMap","inference","progress","reduce","enumerable","json-schema-validator","sequence","user-streams","colour","bundling","slice","tty","folder","efficient","es","connect","crypto","loading","asserts","eslintconfig","channel","inspect","watcher","move","package","functions","babel","throat","mime","sort","typeerror","diff","character","prototype","Array","trim","functional","regular","parse","react-testing-library","Uint32Array","pnpm9","core","ES2017","mobile","a11y","find","variables","file system","iteration","Object.values","fast-clone","negative","mkdirs","vest","width","Array.prototype.findLast","ES7","getOwnPropertyDescriptor","bootstrap css","regular expression","eslintplugin","mkdirp","BigUint64Array","postcss","npm","make","typanion","utils","tape","ES2019","deepclone","Float32Array","find-up","fast-deep-clone","scheme-validation","sameValueZero","watchFile","ES2022","css less","symbol","styles","StyleSheet","stateless","shared","validation","const","bluebird","Underscore","random","modules","deterministic","includes","bcrypt","Array.prototype.findLastIndex","serialize","pose","jsonpath","lazy","prop","promises","yaml","term","ECMAScript 2020","string","CSSStyleDeclaration","ES2016","Map","fastify","css variable","monorepo","rm","schema","busy","TypedArray","number","generics","idle","protobuf","format","ES8","ECMAScript 2018","telephone","assign","6to5","environment","walk","typedarrays","https","intrinsic","cache","es2015","es6","fetch","Object.assign","signal","deep","streams","trimStart","properties","lesscss","utility","emoji","windows","description","curl","es2016","fp","Set","ECMAScript 2016","TypeBox","wordwrap","setPrototypeOf","karma","linux","ES2021","ES6","chai","toolkit","key","Uint16Array","nodejs","contains","fast-copy","persistent","circular","dependency manager","trimEnd","logging","xhr","look","prefix","byteOffset","ansi","structuredClone","debugger","callbound","l10n","joi","Push","concatMap","redact","typed array","request","airbnb","prune","Object.fromEntries","exit-code","entries","error-handling","crypt","banner","hooks","name","positive","WeakMap","authentication","recursive","mocha","sigint","flag","side","color","promise","libphonenumber","react-hooks","quote","BigInt64Array","eslint-plugin","Array.prototype.includes","operating-system","form","eventDispatcher","compare","every","findLast","react-hook-form","some","YAML","syntax","stylesheet","symlink","hardlinks","create","sham","merge","task","view","commander","[[Prototype]]","xterm","command-line","fsevents","Int16Array","codes","xss","patch","speed","check","less","data","setImmediate","es8","japanese","deep-clone","starter","apollo","remove","safe","copy","spinners","AsyncIterator","chromium","postcss-plugin","JSON-Schema","log","pipe","events","higher-order","bound","framework","stdlib","waapi","preprocessor","filter","Object.entries","Symbol","packages","ES","Uint8ClampedArray","cors","readablestream","full-width","Iterator","ArrayBuffer#slice","glob","indicator","rm -fr","ie","tap","parents","encryption","concat","tc39","es5","getintrinsic","compiler","Promise","3d","lru","es-shim API","internal slot","cjk","runtime","fixed-width","ascii","descriptor","args","RxJS","drop","throttle","exec","validator","argparse","extend","picomatch","middleware","javascript","scheme","styled-components","ecmascript","define","lockfile","parent","regex","call-bind","gestures","columns","regexp","redux","nope","Int8Array","forEach","spinner","fs","escape","express","react","setter","column","fantasy-land","polyfill","Uint8Array","read","Observables","match","tools","Object.getPrototypeOf","groupBy","parser","has","stable","Object.is","assertion","concurrency","proto","browser","emit","jsdiff","ratelimit","ES2015","lint","function","uninstall","es-shims","Function.prototype.name","touch","extension","characters","getter","date","api","map","logger","jasmine","hash","JSON","unicode","ECMAScript 3","jsx","ava","call","limited","colors","linewrap","jsonschema","browserslist","import","debug"],"repository":{"type":"git","url":"git+https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur.git"},"homepage":"https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur/#readme","bugs":{"url":"https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur/issues"},"packageManager":"yarn@4.1.1","_id":"@a-2-c-2-anpm/labore-voluptatibus-consectetur@1.0.0","gitHead":"ef1e08ef87315524aad15dde6e3fb3c14e3bc78e","_nodeVersion":"20.12.2","_npmVersion":"10.5.0","dist":{"integrity":"sha512-JSH5RWzuIibJLzNwH9Xp+iJ3o2aDwii+4UDuhvF+KV5htm/J2TvRUUDPPYKRbcmlKBrLPP0fe4mj9N+RBlIvzQ==","shasum":"10b4ea899c159a20ed39a724d550a5e06cb37c8c","tarball":"https://registry.npmjs.org/@a-2-c-2-anpm/labore-voluptatibus-consectetur/-/labore-voluptatibus-consectetur-1.0.0.tgz","fileCount":10,"unpackedSize":106995,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDezYrNWqmsPuG1ccw5eAYVAITTimiNUwVzenwlhvaZWAIgXadHc2cyOEuwUtg/vz6w3ZeILdtBoZfdTw6/vNt1UUk="}]},"_npmUser":{"name":"tranduc345zz","email":"tranduc345zz@gmail.com"},"directories":{},"maintainers":[{"name":"tranduc345zz","email":"tranduc345zz@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/labore-voluptatibus-consectetur_1.0.0_1714236567986_0.19107863780353251"},"_hasShrinkwrap":false}},"time":{"created":"2024-04-27T16:49:27.864Z","1.0.0":"2024-04-27T16:49:28.158Z","modified":"2024-04-27T16:49:28.491Z"},"maintainers":[{"name":"tranduc345zz","email":"tranduc345zz@gmail.com"}],"description":"[![NPM version](http://img.shields.io/npm/v/@a-2-c-2-anpm/labore-voluptatibus-consectetur.svg?style=flat-square)](https://www.npmjs.org/package/@a-2-c-2-anpm/labore-voluptatibus-consectetur) [![Canonical Code Style](https://img.shields.io/badge/code%20sty","homepage":"https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur/#readme","keywords":["buffer","art","toobject","sigterm","ES2018","WebSockets","types","css nesting","metadata","popmotion","search","sharedarraybuffer","type","bdd","typesafe","dependencies","ponyfill","point-free","eslint","which","RFC-6455","terminal","optimizer","irq","iterate","chrome","ES5","directory","reducer","from","link","length","clone","ts","names","toArray","value","qs","delete","byte","ES2020","rangeerror","omit","pretty","HyBi","curried","configurable","tester","robust","es2018","worker","256","i18n","css","preserve-symlinks","collection","duplex","queue","fastclone","spec","classes","private","Symbol.toStringTag","ECMAScript 2015","weakset","RegExp#flags","consume","url","io-ts","util","stringify","three","transpile","package.json","-0","styling","auth","once","ender","jwt","warning","take","dayjs","private data","valid","computed-types","jsdom","classnames","drag","tdd","less compiler","open","client","push","exit","byteLength","var","querystring","hasOwn","dir","phone","shell","keys","up","superstruct","rate","electron","redux-toolkit","ECMAScript 2022","descriptors","obj","testing","native","full","extra","await","sanitization","async","trimRight","get","zero","mixins","output","internal","batch","Float64Array","Observable","_.extend","flat","ReactiveExtensions","less css","core-js","ajv","writable","rfc4122","wait","is","dataView","wrap","estree","json-schema","wget","watch","path","ECMAScript 2023","fastcopy","assert","command","argv","flatMap","tostringtag","east-asian-width","bundler","ECMAScript 7","expression","node","form-validation","tacit","pyyaml","listeners","invariant","set","awesomesauce","Object","mime-db","WebSocket","Array.prototype.contains","object","superagent","array","react pose","datastructure","dataview","buffers","bootstrap less","tslib","Rx","serialization","style","WeakSet","URLSearchParams","installer","fast-deep-copy","class-validator","css-in-js","symlinks","negative zero","uuid","Array.prototype.filter","compile less","rgb","multi-package","code points","censor","ReactiveX","traverse","equality","matches","yup","console","accessor","shebang","eventEmitter","make dir","es-abstract","rmdir","text","fullwidth","argument","arrays","mimetypes","accessibility","validate","weakmap","macos","chinese","arraybuffer","readable","ES3","reuse","test","slot","spring","graphql","regular expressions","typedarray","browserlist","equal","TypeScript","callbind","jQuery","performance","babel-core","env","rapid","typed","forms","hookform","0","Int32Array","mru","ECMAScript 5","protocol-buffers","symbols","findLastIndex","module","time","signals","password","offset","query","util.inspect","js","watching","guid","immer","Object.defineProperty","property","http","shim","package manager","framer","require","dotenv","values","flags","dom","ajax","gradients css3","Reflect.getPrototypeOf","transpiler","less.js","String.prototype.matchAll","config","styleguide","gradients css","ECMAScript 6","rm -rf","sanitize","write","web","error","ECMAScript 2017","settings","ramda","real-time","defineProperty","visual","shrinkwrap","gdpr","install","queueMicrotask","es7","toStringTag","korean","optimist","zod","dom-testing-library","iterator",".env","workspace:*","handlers","react animation","__proto__","input","typeof","sorted","isConcatSpreadable","call-bound","figlet","immutable","Object.keys","last","walking","es2017","ECMAScript 2019","matchAll","json","toSorted","@@toStringTag","Streams","deep-copy","let","trimLeft","process","minimal","ESnext","Array.prototype.flatten","serializer","nested css","coercible","flatten","performant","ArrayBuffer","plugin","limit","resolve","moment","json-schema-validation","option","whatwg","stream","animation","typescript","jest","URL","Array.prototype.flatMap","inference","progress","reduce","enumerable","json-schema-validator","sequence","user-streams","colour","bundling","slice","tty","folder","efficient","es","connect","crypto","loading","asserts","eslintconfig","channel","inspect","watcher","move","package","functions","babel","throat","mime","sort","typeerror","diff","character","prototype","Array","trim","functional","regular","parse","react-testing-library","Uint32Array","pnpm9","core","ES2017","mobile","a11y","find","variables","file system","iteration","Object.values","fast-clone","negative","mkdirs","vest","width","Array.prototype.findLast","ES7","getOwnPropertyDescriptor","bootstrap css","regular expression","eslintplugin","mkdirp","BigUint64Array","postcss","npm","make","typanion","utils","tape","ES2019","deepclone","Float32Array","find-up","fast-deep-clone","scheme-validation","sameValueZero","watchFile","ES2022","css less","symbol","styles","StyleSheet","stateless","shared","validation","const","bluebird","Underscore","random","modules","deterministic","includes","bcrypt","Array.prototype.findLastIndex","serialize","pose","jsonpath","lazy","prop","promises","yaml","term","ECMAScript 2020","string","CSSStyleDeclaration","ES2016","Map","fastify","css variable","monorepo","rm","schema","busy","TypedArray","number","generics","idle","protobuf","format","ES8","ECMAScript 2018","telephone","assign","6to5","environment","walk","typedarrays","https","intrinsic","cache","es2015","es6","fetch","Object.assign","signal","deep","streams","trimStart","properties","lesscss","utility","emoji","windows","description","curl","es2016","fp","Set","ECMAScript 2016","TypeBox","wordwrap","setPrototypeOf","karma","linux","ES2021","ES6","chai","toolkit","key","Uint16Array","nodejs","contains","fast-copy","persistent","circular","dependency manager","trimEnd","logging","xhr","look","prefix","byteOffset","ansi","structuredClone","debugger","callbound","l10n","joi","Push","concatMap","redact","typed array","request","airbnb","prune","Object.fromEntries","exit-code","entries","error-handling","crypt","banner","hooks","name","positive","WeakMap","authentication","recursive","mocha","sigint","flag","side","color","promise","libphonenumber","react-hooks","quote","BigInt64Array","eslint-plugin","Array.prototype.includes","operating-system","form","eventDispatcher","compare","every","findLast","react-hook-form","some","YAML","syntax","stylesheet","symlink","hardlinks","create","sham","merge","task","view","commander","[[Prototype]]","xterm","command-line","fsevents","Int16Array","codes","xss","patch","speed","check","less","data","setImmediate","es8","japanese","deep-clone","starter","apollo","remove","safe","copy","spinners","AsyncIterator","chromium","postcss-plugin","JSON-Schema","log","pipe","events","higher-order","bound","framework","stdlib","waapi","preprocessor","filter","Object.entries","Symbol","packages","ES","Uint8ClampedArray","cors","readablestream","full-width","Iterator","ArrayBuffer#slice","glob","indicator","rm -fr","ie","tap","parents","encryption","concat","tc39","es5","getintrinsic","compiler","Promise","3d","lru","es-shim API","internal slot","cjk","runtime","fixed-width","ascii","descriptor","args","RxJS","drop","throttle","exec","validator","argparse","extend","picomatch","middleware","javascript","scheme","styled-components","ecmascript","define","lockfile","parent","regex","call-bind","gestures","columns","regexp","redux","nope","Int8Array","forEach","spinner","fs","escape","express","react","setter","column","fantasy-land","polyfill","Uint8Array","read","Observables","match","tools","Object.getPrototypeOf","groupBy","parser","has","stable","Object.is","assertion","concurrency","proto","browser","emit","jsdiff","ratelimit","ES2015","lint","function","uninstall","es-shims","Function.prototype.name","touch","extension","characters","getter","date","api","map","logger","jasmine","hash","JSON","unicode","ECMAScript 3","jsx","ava","call","limited","colors","linewrap","jsonschema","browserslist","import","debug"],"repository":{"type":"git","url":"git+https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur.git"},"author":{"name":"a-2-c-2-a"},"bugs":{"url":"https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur/issues"},"license":"MIT","readme":"# Slonik\n\n[![NPM version](http://img.shields.io/npm/v/@a-2-c-2-anpm/labore-voluptatibus-consectetur.svg?style=flat-square)](https://www.npmjs.org/package/@a-2-c-2-anpm/labore-voluptatibus-consectetur)\n[![Canonical Code Style](https://img.shields.io/badge/code%20style-canonical-blue.svg?style=flat-square)](https://github.com/gajus/canonical)\n[![Twitter Follow](https://img.shields.io/twitter/follow/kuizinas.svg?style=social&label=Follow)](https://twitter.com/kuizinas)\n\nA [battle-tested](#battle-tested) Node.js PostgreSQL client with strict types, detailed logging and assertions.\n\n![Tailing Slonik logs](./.README/@a-2-c-2-anpm/labore-voluptatibus-consectetur-log-tailing.gif)\n\n(The above GIF shows Slonik producing [query logs](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur#logging). Slonik produces logs using [Roarr](https://github.com/gajus/roarr). Logs include stack trace of the actual query invocation location and values used to execute the query.)\n\n## Sponsors\n\nIf you value my work and want to see Slonik and [many other of my](https://github.com/gajus/) Open-Source projects to be continuously improved, then please consider becoming a patron:\n\n[![Buy Me A Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/gajus)\n[![Become a Patron](https://c5.patreon.com/external/logo/become_a_patron_button.png)](https://www.patreon.com/gajus)\n\n## Principles\n\n* Promotes writing raw SQL.\n* Discourages ad-hoc dynamic generation of SQL.\n\nRead: [Stop using Knex.js](https://medium.com/@gajus/bf410349856c)\n\nNote: Using this project does not require TypeScript. It is a regular ES6 module. Ignore the type definitions used in the documentation if you do not use a type system.\n\n## Features\n\n* [Runtime validation](#runtime-validation)\n* [Assertions and type safety](#repeating-code-patterns-and-type-safety).\n* [Safe connection handling](#protecting-against-unsafe-connection-handling).\n* [Safe transaction handling](#protecting-against-unsafe-transaction-handling).\n* [Safe value interpolation](#protecting-against-unsafe-value-interpolation).\n* [Transaction nesting](#transaction-nesting).\n* [Transaction retrying](#transaction-retrying)\n* [Query retrying](#query-retrying)\n* Detailed [logging](#debugging).\n* [Asynchronous stack trace resolution](#capture-stack-trace).\n* [Middlewares](#interceptors).\n* [Mapped errors](#error-handling).\n* [ESLint plugin](https://github.com/gajus/eslint-plugin-sql).\n\n## Contents\n\n* [Slonik](#@a-2-c-2-anpm/labore-voluptatibus-consectetur)\n    * [Sponsors](#sponsors)\n    * [Principles](#principles)\n    * [Features](#features)\n    * [Contents](#contents)\n    * [About Slonik](#about-@a-2-c-2-anpm/labore-voluptatibus-consectetur)\n        * [Battle-Tested](#battle-tested)\n        * [Origin of the name](#origin-of-the-name)\n        * [Repeating code patterns and type safety](#repeating-code-patterns-and-type-safety)\n        * [Protecting against unsafe connection handling](#protecting-against-unsafe-connection-handling)\n        * [Protecting against unsafe transaction handling](#protecting-against-unsafe-transaction-handling)\n        * [Protecting against unsafe value interpolation](#protecting-against-unsafe-value-interpolation)\n    * [Documentation](#documentation)\n    * [Usage](#usage)\n        * [Connection URI](#connection-uri)\n        * [Create connection](#create-connection)\n        * [End connection pool](#end-connection-pool)\n        * [Describing the current state of the connection pool](#describing-the-current-state-of-the-connection-pool)\n        * [API](#api)\n        * [Default configuration](#default-configuration)\n        * [Checking out a client from the connection pool](#checking-out-a-client-from-the-connection-pool)\n    * [How are they different?](#how-are-they-different)\n        * [`pg` vs `@a-2-c-2-anpm/labore-voluptatibus-consectetur`](#pg-vs-@a-2-c-2-anpm/labore-voluptatibus-consectetur)\n        * [`pg-promise` vs `@a-2-c-2-anpm/labore-voluptatibus-consectetur`](#pg-promise-vs-@a-2-c-2-anpm/labore-voluptatibus-consectetur)\n        * [`postgres` vs `@a-2-c-2-anpm/labore-voluptatibus-consectetur`](#postgres-vs-@a-2-c-2-anpm/labore-voluptatibus-consectetur)\n    * [Type parsers](#type-parsers)\n        * [Built-in type parsers](#built-in-type-parsers)\n    * [Interceptors](#interceptors)\n        * [Interceptor methods](#interceptor-methods)\n        * [Community interceptors](#community-interceptors)\n    * [Recipes](#recipes)\n        * [Inserting large number of rows](#inserting-large-number-of-rows)\n        * [Routing queries to different connections](#routing-queries-to-different-connections)\n        * [Building Utility Statements](#building-utility-statements)\n        * [Inserting vector data](#inserting-vector-data)\n    * [Runtime validation](#runtime-validation)\n        * [Motivation](#runtime-validation-motivation)\n        * [Result parser interceptor](#runtime-validation-result-parser-interceptor)\n        * [Example use of `sql.type`](#runtime-validation-example-use-of-sql-type)\n        * [Performance penalty](#runtime-validation-performance-penalty)\n        * [Unknown keys](#runtime-validation-unknown-keys)\n        * [Handling schema validation errors](#runtime-validation-handling-schema-validation-errors)\n        * [Inferring types](#runtime-validation-inferring-types)\n        * [Transforming results](#runtime-validation-transforming-results)\n    * [`sql` tag](#sql-tag)\n        * [Type aliases](#type-aliases)\n        * [Typing `sql` tag](#typing-sql-tag)\n    * [Value placeholders](#value-placeholders)\n        * [Tagged template literals](#tagged-template-literals)\n        * [Manually constructing the query](#manually-constructing-the-query)\n        * [Nesting `sql`](#nesting-sql)\n    * [Query building](#query-building)\n        * [`sql.array`](#sql-array)\n        * [`sql.binary`](#sql-binary)\n        * [`sql.date`](#sql-date)\n        * [`sql.fragment`](#sql-fragment)\n        * [`sql.identifier`](#sql-identifier)\n        * [`sql.interval`](#sql-interval)\n        * [`sql.join`](#sql-join)\n        * [`sql.json`](#sql-json)\n        * [`sql.jsonb`](#sql-jsonb)\n        * [`sql.literalValue`](#sql-literalvalue)\n        * [`sql.timestamp`](#sql-timestamp)\n        * [`sql.unnest`](#sql-unnest)\n        * [`sql.unsafe`](#sql-unsafe)\n    * [Query methods](#query-methods)\n        * [`any`](#any)\n        * [`anyFirst`](#anyfirst)\n        * [`exists`](#exists)\n        * [`many`](#many)\n        * [`manyFirst`](#manyfirst)\n        * [`maybeOne`](#maybeone)\n        * [`maybeOneFirst`](#maybeonefirst)\n        * [`one`](#one)\n        * [`oneFirst`](#onefirst)\n        * [`query`](#query)\n        * [`stream`](#stream)\n        * [`transaction`](#transaction)\n    * [Utilities](#utilities)\n        * [`parseDsn`](#utilities-parsedsn)\n        * [`stringifyDsn`](#utilities-stringifydsn)\n    * [Error handling](#error-handling)\n        * [Original `node-postgres` error](#original-node-postgres-error)\n        * [Handling `BackendTerminatedError`](#handling-backendterminatederror)\n        * [Handling `CheckIntegrityConstraintViolationError`](#handling-checkintegrityconstraintviolationerror)\n        * [Handling `ConnectionError`](#handling-connectionerror)\n        * [Handling `DataIntegrityError`](#handling-dataintegrityerror)\n        * [Handling `ForeignKeyIntegrityConstraintViolationError`](#handling-foreignkeyintegrityconstraintviolationerror)\n        * [Handling `NotFoundError`](#handling-notfounderror)\n        * [Handling `NotNullIntegrityConstraintViolationError`](#handling-notnullintegrityconstraintviolationerror)\n        * [Handling `StatementCancelledError`](#handling-statementcancellederror)\n        * [Handling `StatementTimeoutError`](#handling-statementtimeouterror)\n        * [Handling `UniqueIntegrityConstraintViolationError`](#handling-uniqueintegrityconstraintviolationerror)\n        * [Handling `TupleMovedToAnotherPartitionError`](#handling-tuplemovedtoanotherpartitionerror)\n    * [Migrations](#migrations)\n    * [Types](#types)\n    * [Debugging](#debugging)\n        * [Logging](#logging)\n        * [Capture stack trace](#capture-stack-trace)\n    * [Syntax Highlighting](#syntax-highlighting)\n        * [Atom Syntax Highlighting Plugin](#atom-syntax-highlighting-plugin)\n        * [VS Code Syntax Highlighting Extension](#vs-code-syntax-highlighting-extension)\n    * [Development](#development)\n\n\n## About Slonik\n\n### Battle-Tested\n\nSlonik began as a collection of utilities designed for working with [`node-postgres`](https://github.com/brianc/node-postgres). It continues to use `node-postgres` driver as it provides a robust foundation for interacting with PostgreSQL. However, what once was a collection of utilities has since grown into a framework that abstracts repeating code patterns, protects against unsafe connection handling and value interpolation, and provides a rich debugging experience.\n\nSlonik has been [battle-tested](https://medium.com/@gajus/lessons-learned-scaling-postgresql-database-to-1-2bn-records-month-edc5449b3067) with large data volumes and queries ranging from simple CRUD operations to data-warehousing needs.\n\n### Origin of the name\n\n![Slonik](./.README/postgresql-elephant.png)\n\nThe name of the elephant depicted in the official PostgreSQL logo is Slonik. The name itself is derived from the Russian word for \"little elephant\".\n\nRead: [The History of Slonik, the PostgreSQL Elephant Logo](https://www.vertabelo.com/blog/notes-from-the-lab/the-history-of-@a-2-c-2-anpm/labore-voluptatibus-consectetur-the-postgresql-elephant-logo)\n\n### Repeating code patterns and type safety\n\nAmong the primary reasons for developing Slonik, was the motivation to reduce the repeating code patterns and add a level of type safety. This is primarily achieved through the methods such as `one`, `many`, etc. But what is the issue? It is best illustrated with an example.\n\nSuppose the requirement is to write a method that retrieves a resource ID given values defining (what we assume to be) a unique constraint. If we did not have the aforementioned helper methods available, then it would need to be written as:\n\n```ts\nimport {\n  sql,\n  type DatabaseConnection\n} from '@a-2-c-2-anpm/labore-voluptatibus-consectetur';\n\ntype DatabaseRecordIdType = number;\n\nconst getFooIdByBar = async (connection: DatabaseConnection, bar: string): Promise<DatabaseRecordIdType> => {\n  const fooResult = await connection.query(sql.typeAlias('id')`\n    SELECT id\n    FROM foo\n    WHERE bar = ${bar}\n  `);\n\n  if (fooResult.rowCount === 0) {\n    throw new Error('Resource not found.');\n  }\n\n  if (fooResult.rowCount > 1) {\n    throw new Error('Data integrity constraint violation.');\n  }\n\n  return fooResult[0].id;\n};\n```\n\n`oneFirst` method abstracts all of the above logic into:\n\n```ts\nconst getFooIdByBar = (connection: DatabaseConnection, bar: string): Promise<DatabaseRecordIdType> => {\n  return connection.oneFirst(sql.typeAlias('id')`\n    SELECT id\n    FROM foo\n    WHERE bar = ${bar}\n  `);\n};\n```\n\n`oneFirst` throws:\n\n* `NotFoundError` if query returns no rows\n* `DataIntegrityError` if query returns multiple rows\n* `DataIntegrityError` if query returns multiple columns\n\nIn the absence of helper methods, the overhead of repeating code becomes particularly visible when writing routines where multiple queries depend on the proceeding query results. Using methods with inbuilt assertions ensures that in case of an error, the error points to the source of the problem. In contrast, unless assertions for all possible outcomes are typed out as in the previous example, the unexpected result of the query will be fed to the next operation. If you are lucky, the next operation will simply break; if you are unlucky, you are risking data corruption and hard-to-locate bugs.\n\nFurthermore, using methods that guarantee the shape of the results allows us to leverage static type checking and catch some of the errors even before executing the code, e.g.\n\n```ts\nconst fooId = await connection.many(sql.typeAlias('id')`\n  SELECT id\n  FROM foo\n  WHERE bar = ${bar}\n`);\n\nawait connection.query(sql.typeAlias('void')`\n  DELETE FROM baz\n  WHERE foo_id = ${fooId}\n`);\n```\n\nStatic type check of the above example will produce a warning as the `fooId` is guaranteed to be an array and binding of the last query is expecting a primitive value.\n\n### Protecting against unsafe connection handling\n\nSlonik only allows to check out a connection for the duration of the promise routine supplied to the `pool#connect()` method.\n\nThe primary reason for implementing _only_ this connection pooling method is because the alternative is inherently unsafe, e.g.\n\n```ts\n// This is not valid Slonik API\n\nconst main = async () => {\n  const connection = await pool.connect();\n\n  await connection.query(sql.typeAlias('foo')`SELECT foo()`);\n\n  await connection.release();\n};\n```\n\nIn this example, if `SELECT foo()` produces an error, then connection is never released, i.e. the connection hangs indefinitely.\n\nA fix to the above is to ensure that `connection#release()` is always called, i.e.\n\n```ts\n// This is not valid Slonik API\n\nconst main = async () => {\n  const connection = await pool.connect();\n\n  let lastExecutionResult;\n\n  try {\n    lastExecutionResult = await connection.query(sql.typeAlias('foo')`SELECT foo()`);\n  } finally {\n    await connection.release();\n  }\n\n  return lastExecutionResult;\n};\n```\n\nSlonik abstracts the latter pattern into `pool#connect()` method.\n\n```ts\nconst main = () => {\n  return pool.connect((connection) => {\n    return connection.query(sql.typeAlias('foo')`SELECT foo()`);\n  });\n};\n```\n\nUsing this pattern, we guarantee that connection is always released as soon as the `connect()` routine resolves or is rejected.\n\n### Protecting against unsafe transaction handling\n\nJust like in the [unsafe connection handling](#protecting-against-unsafe-connection-handling) example, Slonik only allows to create a transaction for the duration of the promise routine supplied to the `connection#transaction()` method.\n\n```ts\nconnection.transaction(async (transactionConnection) => {\n  await transactionConnection.query(sql.typeAlias('void')`INSERT INTO foo (bar) VALUES ('baz')`);\n  await transactionConnection.query(sql.typeAlias('void')`INSERT INTO qux (quux) VALUES ('quuz')`);\n});\n```\n\nThis pattern ensures that the transaction is either committed or aborted the moment the promise is either resolved or rejected.\n\n> [!NOTE]\n> If you receive an error `UnexpectedForeignConnectionError`, then you are trying to execute a query using a connection that is not associated with the transaction. This error is thrown to prevent accidental unsafe transaction handling, e.g.\n> ```ts\n> pool.transaction(async (transactionConnection) => {\n>   await pool.query(sql.typeAlias('void')`INSERT INTO foo (bar) VALUES ('baz')`);\n> });\n> ```\n> In this example, the query is executed using the `connection` that is not associated with the transaction. This is unsafe because the query is not part of the transaction and will not be rolled back if the transaction is aborted.\n> This behaviour can be disabled by setting `dangerouslyAllowForeignConnections` to `true` in the `ClientConfiguration`.\n\n### Protecting against unsafe value interpolation\n\n[SQL injections](https://en.wikipedia.org/wiki/SQL_injection) are one of the most well known attack vectors. Some of the [biggest data leaks](https://en.wikipedia.org/wiki/SQL_injection#Examples) were the consequence of improper user-input handling. In general, SQL injections are easily preventable by using parameterization and by restricting database permissions, e.g.\n\n```ts\n// This is not valid Slonik API\n\nconnection.query('SELECT $1', [\n  userInput\n]);\n```\n\nIn this example, the query text (`SELECT $1`) and parameters (`userInput`) are passed separately to the PostgreSQL server where the parameters are safely substituted into the query. This is a safe way to execute a query using user-input.\n\nThe vulnerabilities appear when developers cut corners or when they do not know about parameterization, i.e. there is a risk that someone will instead write:\n\n```ts\n// This is not valid Slonik API\n\nconnection.query('SELECT \\'' + userInput + '\\'');\n```\n\nAs evident by the history of the data leaks, this happens more often than anyone would like to admit. This security vulnerability is especially a significant risk in Node.js community, where a predominant number of developers are coming from frontend and have not had training working with RDBMSes. Therefore, one of the key selling points of Slonik is that it adds multiple layers of protection to prevent unsafe handling of user input.\n\nTo begin with, Slonik does not allow running plain-text queries.\n\n```ts\n// This is not valid Slonik API\n\nconnection.query('SELECT 1');\n```\n\nThe above invocation would produce an error:\n\n> TypeError: Query must be constructed using `sql` tagged template literal.\n\nThis means that the only way to run a query is by constructing it using [`sql` tagged template literal](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur#value-placeholders-tagged-template-literals), e.g.\n\n```ts\nconnection.query(sql.unsafe`SELECT 1`);\n```\n\nTo add a parameter to the query, user must use [template literal placeholders](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Description), e.g.\n\n```ts\nconnection.query(sql.unsafe`SELECT ${userInput}`);\n```\n\nSlonik takes over from here and constructs a query with value bindings, and sends the resulting query text and parameters to PostgreSQL. There is no other way of passing parameters to the query – this adds a strong layer of protection against accidental unsafe user input handling due to limited knowledge of the SQL client API.\n\nAs Slonik restricts user's ability to generate and execute dynamic SQL, it provides helper functions used to generate fragments of the query and the corresponding value bindings, e.g. [`sql.identifier`](#sqlidentifier), [`sql.join`](#sqljoin) and [`sql.unnest`](#sqlunnest). These methods generate tokens that the query executor interprets to construct a safe query, e.g.\n\n```ts\nconnection.query(sql.unsafe`\n  SELECT ${sql.identifier(['foo', 'a'])}\n  FROM (\n    VALUES\n    (\n      ${sql.join(\n        [\n          sql.join(['a1', 'b1', 'c1'], sql.fragment`, `),\n          sql.join(['a2', 'b2', 'c2'], sql.fragment`, `)\n        ],\n        sql.fragment`), (`\n      )}\n    )\n  ) foo(a, b, c)\n  WHERE foo.b IN (${sql.join(['c1', 'a2'], sql.fragment`, `)})\n`);\n```\n\nThis (contrived) example generates a query equivalent to:\n\n```sql\nSELECT \"foo\".\"a\"\nFROM (\n  VALUES\n    ($1, $2, $3),\n    ($4, $5, $6)\n) foo(a, b, c)\nWHERE foo.b IN ($7, $8)\n```\n\nThis query is executed with the parameters provided by the user.\n\nTo sum up, Slonik is designed to prevent accidental creation of queries vulnerable to SQL injections.\n\n\n## Documentation\n\n## Usage\n\n### Connection URI\n\nSlonik client is configured using a custom connection URI (DSN).\n\n```tson\npostgresql://[user[:password]@][host[:port]][/database name][?name=value[&...]]\n```\n\nSupported parameters:\n\n|Name|Meaning|Default|\n|---|---|---|\n|`application_name`|[`application_name`](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-APPLICATION-NAME)||\n|`options`|[`options`](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-OPTIONS)||\n|`sslmode`|[`sslmode`](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLMODE) (supported values: `disable`, `no-verify`, `require`)|`disable`|\n\nNote that unless listed above, other [libpq parameters](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS) are not supported.\n\nExamples of valid DSNs:\n\n```text\npostgresql://\npostgresql://localhost\npostgresql://localhost:5432\npostgresql://localhost/foo\npostgresql://foo@localhost\npostgresql://foo:bar@localhost\npostgresql://foo@localhost/bar?application_name=baz\n```\n\nUnix-domain socket connection is chosen if the host part is either empty or looks like an absolute path name.\n\n```text\npostgresql:///dbname?host=/var/lib/postgresql\npostgresql://%2Fvar%2Flib%2Fpostgresql/dbname\n```\n\nOther configurations are available through the [`clientConfiguration` parameter](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur#api).\n\n### Create connection\n\nUse `createPool` to create a connection pool, e.g.\n\n```ts\nimport {\n  createPool,\n} from '@a-2-c-2-anpm/labore-voluptatibus-consectetur';\n\nconst pool = await createPool('postgres://');\n```\n\n> **Note:** If you are new to Slonik, then you should read [Integrating Slonik with Express.js](https://dev.to/gajus/integrating-@a-2-c-2-anpm/labore-voluptatibus-consectetur-with-expressjs-33kn).\n\nInstance of Slonik connection pool can be then used to create a new connection, e.g.\n\n```ts\npool.connect(async (connection) => {\n  await connection.query(sql.typeAlias('id')`SELECT 1 AS id`);\n});\n```\n\nThe connection will be kept alive until the promise resolves (the result of the method supplied to `connect()`).\n\nRefer to [query method](#query-methods) documentation to learn about the connection methods.\n\nIf you do not require having a persistent connection to the same backend, then you can directly use `pool` to run queries, e.g.\n\n```ts\npool.query(sql.typeAlias('id')`SELECT 1 AS id`);\n```\n\nBeware that in the latter example, the connection picked to execute the query is a random connection from the connection pool, i.e. using the latter method (without explicit `connect()`) does not guarantee that multiple queries will refer to the same backend.\n\n### End connection pool\n\nUse `pool.end()` to end idle connections and prevent creation of new connections.\n\nThe result of `pool.end()` is a promise that is resolved when all connections are ended.\n\n```ts\nimport {\n  createPool,\n  sql,\n} from '@a-2-c-2-anpm/labore-voluptatibus-consectetur';\n\nconst pool = await createPool('postgres://');\n\nconst main = async () => {\n  await pool.query(sql.typeAlias('id')`\n    SELECT 1 AS id\n  `);\n\n  await pool.end();\n};\n\nmain();\n```\n\nNote: `pool.end()` does not terminate active connections/ transactions.\n\n### Describing the current state of the connection pool\n\nUse `pool.state()` to find out if pool is alive and how many connections are active and idle, and how many clients are waiting for a connection.\n\n```ts\nimport {\n  createPool,\n  sql,\n} from '@a-2-c-2-anpm/labore-voluptatibus-consectetur';\n\nconst pool = await createPool('postgres://');\n\nconst main = async () => {\n  pool.state();\n\n  // {\n  //   acquiredConnections: 0,\n  //   idleConnections: 0,\n  //   pendingDestroyConnections: 0,\n  //   pendingReleaseConnections: 0,\n  //   state: 'ACTIVE',\n  //   waitingClients: 0,\n  // }\n\n  await pool.connect(() => {\n    pool.state();\n\n    // {\n    //   acquiredConnections: 1,\n    //   idleConnections: 0,\n    //   pendingDestroyConnections: 0,\n    //   pendingReleaseConnections: 0,\n    //   state: 'ACTIVE',\n    //   waitingClients: 0,\n    // }\n  });\n\n  pool.state();\n\n  // {\n  //   acquiredConnections: 0,\n  //   idleConnections: 1,\n  //   pendingDestroyConnections: 0,\n  //   pendingReleaseConnections: 0,\n  //   state: 'ACTIVE',\n  //   waitingClients: 0,\n  // }\n\n  await pool.end();\n\n  pool.state();\n\n  // {\n  //   acquiredConnections: 0,\n  //   idleConnections: 0,\n  //   pendingDestroyConnections: 0,\n  //   pendingReleaseConnections: 0,\n  //   state: 'ENDED',\n  //   waitingClients: 0,\n  // }\n};\n\nmain();\n```\n\nNote: `pool.end()` does not terminate active connections/ transactions.\n\n### API\n\n```ts\n/**\n * @param connectionUri PostgreSQL [Connection URI](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING).\n */\ncreatePool(\n  connectionUri: string,\n  clientConfiguration: ClientConfiguration\n): DatabasePool;\n\n/**\n * @property captureStackTrace Dictates whether to capture stack trace before executing query. Middlewares access stack trace through query execution context. (Default: false)\n * @property connectionRetryLimit Number of times to retry establishing a new connection. (Default: 3)\n * @property connectionTimeout Timeout (in milliseconds) after which an error is raised if connection cannot be established. (Default: 5000)\n * @property dangerouslyAllowForeignConnections Allow using connections that are not associated with the transaction. (Default: false)\n * @property driverFactory Overrides the default DriverFactory. (Default: \"pg\" driver factory)\n * @property gracefulTerminationTimeout Timeout (in milliseconds) that kicks in after a connection with an active query is requested to end. This is the amount of time that is allowed for query to complete before terminating it. (Default: 5000)\n * @property idleInTransactionSessionTimeout Timeout (in milliseconds) after which idle clients are closed. Use 'DISABLE_TIMEOUT' constant to disable the timeout. (Default: 60000)\n * @property idleTimeout Timeout (in milliseconds) after which idle clients are closed. Use 'DISABLE_TIMEOUT' constant to disable the timeout. (Default: 5000)\n * @property interceptors An array of [Slonik interceptors](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur#interceptors).\n * @property maximumPoolSize Do not allow more than this many connections. Use 'DISABLE_TIMEOUT' constant to disable the timeout. (Default: 10)\n * @property queryRetryLimit Number of times a query failing with Transaction Rollback class error, that doesn't belong to a transaction, is retried. (Default: 5)\n * @property ssl [tls.connect options](https://nodejs.org/api/tls.html#tlsconnectoptions-callback)\n * @property statementTimeout Timeout (in milliseconds) after which database is instructed to abort the query. Use 'DISABLE_TIMEOUT' constant to disable the timeout. (Default: 60000)\n * @property transactionRetryLimit Number of times a transaction failing with Transaction Rollback class error is retried. (Default: 5)\n * @property typeParsers An array of [Slonik type parsers](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur#type-parsers).\n */\ntype ClientConfiguration = {\n  captureStackTrace?: boolean,\n  connectionRetryLimit?: number,\n  connectionTimeout?: number | 'DISABLE_TIMEOUT',\n  driverFactory?: DriverFactory,\n  gracefulTerminationTimeout?: number,\n  idleInTransactionSessionTimeout?: number | 'DISABLE_TIMEOUT',\n  idleTimeout?: number | 'DISABLE_TIMEOUT',\n  interceptors?: Interceptor[],\n  maximumPoolSize?: number,\n  queryRetryLimit?: number,\n  ssl?: Parameters<tls.connect>[0],\n  statementTimeout?: number | 'DISABLE_TIMEOUT',\n  transactionRetryLimit?: number,\n  typeParsers?: TypeParser[],\n};\n```\n\nExample:\n\n```ts\nimport {\n  createPool\n} from '@a-2-c-2-anpm/labore-voluptatibus-consectetur';\n\nconst pool = await createPool('postgres://');\n\nawait pool.query(sql.typeAlias('id')`SELECT 1 AS id`);\n```\n\n### Default configuration\n\n#### Default interceptors\n\nNone.\n\nCheck out [`@a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-preset`](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-preset) for an opinionated collection of interceptors.\n\n#### Default type parsers\n\nThese type parsers are enabled by default:\n\n|Type name|Implementation|\n|---|---|\n|`date`|Produces a literal date as a string (format: YYYY-MM-DD).|\n|`int8`|Produces an integer.|\n|`interval`|Produces interval in seconds (integer).|\n|`numeric`|Produces a float.|\n|`timestamp`|Produces a unix timestamp (in milliseconds).|\n|`timestamptz`|Produces a unix timestamp (in milliseconds).|\n\nTo disable the default type parsers, pass an empty array, e.g.\n\n```ts\ncreatePool('postgres://', {\n  typeParsers: []\n});\n```\n\nYou can create default type parser collection using `createTypeParserPreset`, e.g.\n\n```ts\nimport {\n  createTypeParserPreset\n} from '@a-2-c-2-anpm/labore-voluptatibus-consectetur';\n\ncreatePool('postgres://', {\n  typeParsers: [\n    ...createTypeParserPreset()\n  ]\n});\n```\n\n#### Default timeouts\n\nThere are 4 types of configurable timeouts:\n\n|Configuration|Description|Default|\n|---|---|---|\n|`connectionTimeout`|Timeout (in milliseconds) after which an error is raised if connection cannot be established.|5000|\n|`idleInTransactionSessionTimeout`|Timeout (in milliseconds) after which idle clients are closed. Use 'DISABLE_TIMEOUT' constant to disable the timeout.|60000|\n|`idleTimeout`|Timeout (in milliseconds) after which idle clients are closed. Use 'DISABLE_TIMEOUT' constant to disable the timeout.|5000|\n|`statementTimeout`|Timeout (in milliseconds) after which database is instructed to abort the query. Use 'DISABLE_TIMEOUT' constant to disable the timeout.|60000|\n\nSlonik sets aggressive timeouts by default. These timeouts are designed to provide safe interface to the database. These timeouts might not work for all programs. If your program has long running statements, consider adjusting timeouts just for those statements instead of changing the defaults.\n\n#### Known limitations of using pg-native with Slonik\n\n`pg-native` is not officially supported by Slonik.\n\n### Checking out a client from the connection pool\n\nSlonik only allows to check out a connection for the duration of the promise routine supplied to the `pool#connect()` method.\n\n```ts\nimport {\n  createPool,\n} from '@a-2-c-2-anpm/labore-voluptatibus-consectetur';\n\nconst pool = await createPool('postgres://localhost');\n\nconst result = await pool.connect(async (connection) => {\n  await connection.query(sql.typeAlias('id')`SELECT 1 AS id`);\n  await connection.query(sql.typeAlias('id')`SELECT 2 AS id`);\n\n  return 'foo';\n});\n\nresult;\n// 'foo'\n\n```\n\nConnection is released back to the pool after the promise produced by the function supplied to `connect()` method is either resolved or rejected.\n\nRead: [Protecting against unsafe connection handling](#protecting-against-unsafe-connection-handling).\n\n## How are they different?\n\n### <code>pg</code> vs <code>@a-2-c-2-anpm/labore-voluptatibus-consectetur</code>\n\n[`pg`](https://github.com/brianc/node-postgres) is built intentionally to provide unopinionated, minimal abstraction and encourages use of other modules to implement convenience methods.\n\nSlonik is built on top of `pg` and it provides convenience methods for [building queries](#value-placeholders) and [querying data](#query-methods).\n\nWork on `pg` began on [Tue Sep 28 22:09:21 2010](https://github.com/brianc/node-postgres/commit/cf637b08b79ef93d9a8b9dd2d25858aa7e9f9bdc). It is authored by [Brian Carlson](https://github.com/brianc).\n\n### <code>pg-promise</code> vs <code>@a-2-c-2-anpm/labore-voluptatibus-consectetur</code>\n\nAs the name suggests, [`pg-promise`](https://github.com/vitaly-t/pg-promise) was originally built to enable use of `pg` module with promises (at the time, `pg` only supported Continuation Passing Style (CPS), i.e. callbacks). Since then `pg-promise` added features for connection/ transaction handling, a powerful query-formatting engine and a declarative approach to handling query results.\n\nThe primary difference between Slonik and `pg-promise`:\n\n* Slonik does not allow to execute raw text queries. Slonik queries can only be constructed using [`sql` tagged template literals](#value-placeholders-tagged-template-literals). This design [protects against unsafe value interpolation](#protecting-against-unsafe-value-interpolation).\n* Slonik implements [interceptor API](#interceptors) (middleware). Middlewares allow to modify connection handling, override queries and modify the query results. Example Slonik interceptors include [field name transformation](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-field-name-transformation), [query normalization](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-query-normalisation) and [query benchmarking](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-query-benchmarking).\n\nNote: Author of `pg-promise` has [objected to the above claims](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur/issues/122). I have removed a difference that was clearly wrong. I maintain that the above two differences remain valid differences: even though `pg-promise` might have substitute functionality for variable interpolation and interceptors, it implements them in a way that does not provide the same benefits that Slonik provides, namely: guaranteed security and support for extending library functionality using multiple plugins.\n\nOther differences are primarily in how the equivalent features are implemented, e.g.\n\n|`pg-promise`|Slonik|\n|---|---|\n|[Custom type formatting](https://github.com/vitaly-t/pg-promise#custom-type-formatting).|Not available in Slonik. The current proposal is to create an interceptor that would have access to the [query fragment constructor](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur/issues/21).|\n|[formatting filters](https://github.com/vitaly-t/pg-promise#nested-named-parameters)|Slonik tagged template [value expressions](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur#value-placeholders) to construct query fragments and bind parameter values.|\n|[Query files](https://github.com/vitaly-t/pg-promise#query-files).|Use [`@a-2-c-2-anpm/labore-voluptatibus-consectetur-sql-tag-raw`](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur-sql-tag-raw).|\n|[Tasks](https://github.com/vitaly-t/pg-promise#tasks).|Use [`pool.connect`](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur#create-connection).|\n|Configurable transactions.|Not available in Slonik. Track [this issue](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur/issues/30).|\n|Events.|Use [interceptors](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur#interceptors).|\n\nWhen weighting which abstraction to use, it would be unfair not to consider that `pg-promise` is a mature project with dozens of contributors. Meanwhile, Slonik is a young project (started in March 2017) that until recently was developed without active community input. However, if you do support the unique features that Slonik adds, the opinionated API design, and are not afraid of adopting a technology in its young days, then I warmly invite you to adopt Slonik and become a contributor to what I intend to make the standard PostgreSQL client in the Node.js community.\n\nWork on `pg-promise` began [Wed Mar 4 02:00:34 2015](https://github.com/vitaly-t/pg-promise/commit/78fb80f638e7f28b301f75576701536d6b638f31). It is authored by [Vitaly Tomilov](https://github.com/vitaly-t).\n\n### <code>postgres</code> vs <code>@a-2-c-2-anpm/labore-voluptatibus-consectetur</code>\n\n[`postgres`](https://github.com/porsager/postgres) recently gained in popularity due to its performance benefits when compared to `pg`. In terms of API, it has a pretty bare-bones API that heavily relies on using ES6 tagged templates and abstracts away many concepts of connection pool handling. While `postgres` API might be preferred by some, projects that already use `pg` may have difficulty migrating.\n\nHowever, by using [postgres-bridge](https://github.com/gajus/postgres-bridge) (`postgres`/`pg` compatibility layer), you can benefit from `postgres` performance improvements while still using Slonik API:\n\n```ts\nimport postgres from 'postgres';\nimport { createPostgresBridge } from 'postgres-bridge';\nimport { createPool } from '@a-2-c-2-anpm/labore-voluptatibus-consectetur';\nconst PostgresBridge = createPostgresBridge(postgres);\nconst pool = createPool('postgres://', {\n  PgPool: PostgresBridge,\n});\n```\n\n## Type parsers\n\nType parsers describe how to parse PostgreSQL types.\n\n```ts\ntype TypeParser = {\n  name: string,\n  parse: (value: string) => *\n};\n```\n\nExample:\n\n```ts\n{\n  name: 'int8',\n  parse: (value) => {\n    return parseInt(value, 10);\n  }\n}\n```\n\nNote: Unlike [`pg-types`](https://github.com/brianc/node-pg-types) that uses OIDs to identify types, Slonik identifies types using their names.\n\nUse this query to find type names:\n\n```sql\nSELECT typname\nFROM pg_type\nORDER BY typname ASC\n```\n\nType parsers are configured using [`typeParsers` client configuration](#api).\n\nRead: [Default type parsers](#default-type-parsers).\n\n### Built-in type parsers\n\n|Type name|Implementation|Factory function name|\n|---|---|---|\n|`date`|Produces a literal date as a string (format: YYYY-MM-DD).|`createDateTypeParser`|\n|`int8`|Produces an integer.|`createBigintTypeParser`|\n|`interval`|Produces interval in seconds (integer).|`createIntervalTypeParser`|\n|`numeric`|Produces a float.|`createNumericTypeParser`|\n|`timestamp`|Produces a unix timestamp (in milliseconds).|`createTimestampTypeParser`|\n|`timestamptz`|Produces a unix timestamp (in milliseconds).|`createTimestampWithTimeZoneTypeParser`|\n\nBuilt-in type parsers can be created using the exported factory functions, e.g.\n\n```ts\nimport {\n  createTimestampTypeParser\n} from '@a-2-c-2-anpm/labore-voluptatibus-consectetur';\n\ncreateTimestampTypeParser();\n\n// {\n//   name: 'timestamp',\n//   parse: (value) => {\n//     return value === null ? value : Date.parse(value + ' UTC');\n//   }\n// }\n```\n\n\n## Interceptors\n\nFunctionality can be added to Slonik client by adding interceptors (middleware).\n\nInterceptors are configured using [client configuration](#api), e.g.\n\n```ts\nimport {\n  createPool\n} from '@a-2-c-2-anpm/labore-voluptatibus-consectetur';\n\nconst interceptors = [];\n\nconst connection = await createPool('postgres://', {\n  interceptors\n});\n```\n\nInterceptors are executed in the order they are added.\n\nRead: [Default interceptors](#default-interceptors).\n\n### Interceptor methods\n\nInterceptor is an object that implements methods that can change the behaviour of the database client at different stages of the connection life-cycle\n\n```ts\ntype Interceptor = {\n  afterPoolConnection?: (\n    connectionContext: ConnectionContext,\n    connection: DatabasePoolConnection\n  ) => MaybePromise<null>,\n  afterQueryExecution?: (\n    queryContext: QueryContext,\n    query: Query,\n    result: QueryResult<QueryResultRow>\n  ) => MaybePromise<QueryResult<QueryResultRow>>,\n  beforePoolConnection?: (\n    connectionContext: ConnectionContext\n  ) => MaybePromise<?DatabasePool>,\n  beforePoolConnectionRelease?: (\n    connectionContext: ConnectionContext,\n    connection: DatabasePoolConnection\n  ) => MaybePromise<null>,\n  beforeQueryExecution?: (\n    queryContext: QueryContext,\n    query: Query\n  ) => MaybePromise<QueryResult<QueryResultRow>> | MaybePromise<null>,\n  beforeQueryResult?: (\n    queryContext: QueryContext,\n    query: Query,\n    result: QueryResult<QueryResultRow>\n  ) => MaybePromise<null>,\n  beforeTransformQuery?: (\n    queryContext: QueryContext,\n    query: Query\n  ) => MaybePromise<null>,\n  queryExecutionError?: (\n    queryContext: QueryContext,\n    query: Query,\n    error: SlonikError\n  ) => MaybePromise<null>,\n  transformQuery?: (\n    queryContext: QueryContext,\n    query: Query\n  ) => Query,\n  transformRow?: (\n    queryContext: QueryContext,\n    query: Query,\n    row: QueryResultRow,\n    fields: Field[],\n  ) => MaybePromise<QueryResultRow>\n};\n```\n\n#### <code>afterPoolConnection</code>\n\nExecuted after a connection is acquired from the connection pool (or a new connection is created), e.g.\n\n```ts\nconst pool = await createPool('postgres://');\n\n// Interceptor is executed here. ↓\npool.connect();\n```\n\n#### <code>afterQueryExecution</code>\n\nExecuted after query has been executed and before rows were transformed using `transformRow`.\n\nNote: When query is executed using `stream`, then `afterQuery` is called with empty result set.\n\n#### <code>beforeQueryExecution</code>\n\nThis function can optionally return a direct result of the query which will cause the actual query never to be executed.\n\n#### <code>beforeQueryResult</code>\n\nExecuted just before the result is returned to the client.\n\nUse this method to capture the result that will be returned to the client.\n\n#### <code>beforeTransformQuery</code>\n\nExecuted before `transformQuery`. Use this interceptor to capture the original query (e.g. for logging purposes).\n\n#### <code>beforePoolConnection</code>\n\nExecuted before connection is created.\n\nThis function can optionally return a pool to another database, causing a connection to be made to the new pool.\n\n#### <code>beforePoolConnectionRelease</code>\n\nExecuted before connection is released back to the connection pool, e.g.\n\n```ts\nconst pool = await createPool('postgres://');\n\npool.connect(async () => {\n  await 1;\n\n  // Interceptor is executed here. ↓\n});\n```\n\n#### <code>queryExecutionError</code>\n\nExecuted if query execution produces an error.\n\nUse `queryExecutionError` to log and/ or re-throw another error.\n\n#### <code>transformQuery</code>\n\nExecuted before `beforeQueryExecution`.\n\nTransforms query.\n\n#### <code>transformRow</code>\n\nExecuted for each row.\n\nTransforms row.\n\nUse `transformRow` to modify the query result.\n\n### Community interceptors\n\n|Name|Description|\n|---|---|\n|[`@a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-field-name-transformation`](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-field-name-transformation)|Transforms Slonik query result field names.|\n|[`@a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-query-benchmarking`](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-query-benchmarking)|Benchmarks Slonik queries.|\n|[`@a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-query-cache`](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-query-cache)|Caches Slonik queries.|\n|[`@a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-query-logging`](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-query-logging)|Logs Slonik queries.|\n|[`@a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-query-normalisation`](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-query-normalisation)|Normalises Slonik queries.|\n\nCheck out [`@a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-preset`](https://github.com/a-2-c-2-anpm/labore-voluptatibus-consectetur-interceptor-preset) for an opinionated collection of interceptors.\n\n\n## Recipes\n\n### Inserting large number of rows\n\nUse [`sql.unnest`](#sqlunnest) to create a set of rows using `unnest`. Using the `unnest` approach requires only 1 variable per every column; values for each column are passed as an array, e.g.\n\n```ts\nawait connection.query(sql.unsafe`\n  INSERT INTO foo (bar, baz, qux)\n  SELECT *\n  FROM ${sql.unnest(\n    [\n      [1, 2, 3],\n      [4, 5, 6]\n    ],\n    [\n      'int4',\n      'int4',\n      'int4'\n    ]\n  )}\n`);\n```\n\nProduces:\n\n```ts\n{\n  sql: 'INSERT INTO foo (bar, baz, qux) SELECT * FROM unnest($1::int4[], $2::int4[], $3::int4[])',\n  values: [\n    [\n      1,\n      4\n    ],\n    [\n      2,\n      5\n    ],\n    [\n      3,\n      6\n    ]\n  ]\n}\n```\n\nInserting data this way ensures that the query is stable and reduces the amount of time it takes to parse the query.\n\n### Routing queries to different connections\n\nA typical load balancing requirement is to route all \"logical\" read-only queries to a read-only instance. This requirement can be implemented in 2 ways:\n\n1. Create two instances of Slonik (read-write and read-only) and pass them around the application as needed.\n1. Use `beforePoolConnection` middleware to assign query to a connection pool based on the query itself.\n\nFirst option is preferable as it is the most explicit. However, it also has the most overhead to implement.\n\nOn the other hand, `beforePoolConnection` makes it easy to route based on conventions, but carries a greater risk of accidentally routing queries with side-effects to a read-only instance.\n\nThe first option is self-explanatory to implement, but this recipe demonstrates my convention for using `beforePoolConnection` to route queries.\n\nNote: How you determine which queries are safe to route to a read-only instance is outside of scope for this documentation.\n\nNote: `beforePoolConnection` only works for connections initiated by a query, i.e. `pool#query` and not `pool#connect()`.\n\nNote: `pool#transaction` triggers `beforePoolConnection` but has no `query`.\n\nNote: This particular implementation does not handle [`SELECT INTO`](https://www.postgresql.org/docs/current/sql-selectinto.html).\n\n```ts\nconst readOnlyPool = await createPool('postgres://read-only');\nconst pool = await createPool('postgres://main', {\n  interceptors: [\n    {\n      beforePoolConnection: (connectionContext) => {\n        if (!connectionContext.query?.sql.trim().startsWith('SELECT ')) {\n          // Returning null falls back to using the DatabasePool from which the query originates.\n          return null;\n        }\n\n        // This is a convention for the edge-cases where a SELECT query includes a volatile function.\n        // Adding a @volatile comment anywhere into the query bypasses the read-only route, e.g.\n        // sql.unsafe`\n        //   /* @volatile */\n        //   SELECT write_log()\n        // `\n        if (connectionContext.query?.sql.includes('@volatile')) {\n          return null;\n        }\n\n        // Returning an instance of DatabasePool will attempt to run the query using the other connection pool.\n        // Note that all other interceptors of the pool that the query originated from are short-circuited.\n        return readOnlyPool;\n      }\n    }\n  ]\n});\n\n// This query will use `postgres://read-only` connection.\npool.query(sql.typeAlias('id')`SELECT 1 AS id`);\n\n// This query will use `postgres://main` connection.\npool.query(sql.typeAlias('id')`UPDATE 1 AS id`);\n```\n\n### Building Utility Statements\n\nParameter symbols only work in optimizable SQL commands (SELECT, INSERT, UPDATE, DELETE, and certain commands containing one of these). In other statement types (generically called utility statements, e.g. ALTER, CREATE, DROP and SET), you must insert values textually even if they are just data values.\n\nIn the context of Slonik, if you are building utility statements you must use query building methods that interpolate values directly into queries:\n\n* [`sql.identifier`](#sql-identifier) – for identifiers.\n* [`sql.literalValue`](#sql-literalvalue) – for values.\n\nExample:\n\n```ts\nawait connection.query(sql.typeAlias('void')`\n  CREATE USER ${sql.identifier(['foo'])}\n  WITH PASSWORD ${sql.literalValue('bar')}\n`);\n```\n\n### Inserting vector data\n\nIf you are using [`pgvector`](https://github.com/pgvector/pgvector) and need to insert vector data, you can use the following helper function:\n\n```ts\nconst vector = (embeddings: number[]) => {\n  return sql.fragment`${sql.array(\n    Array.from(embeddings),\n    sql.fragment`real[]`,\n  )}::vector`;\n};\n```\n\nNow you can use the `vector` helper function to insert vector data:\n\n```ts\nawait connection.query(sql.typeAlias('void')`\n  INSERT INTO embeddings (id, vector)\n  VALUES (1, ${vector(embedding.data)})\n`);\n```\n\nYou can also use the [`pgvector` NPM package](https://github.com/pgvector/pgvector-node/?tab=readme-ov-file#@a-2-c-2-anpm/labore-voluptatibus-consectetur) to achieve the same result.\n\n## Runtime validation\n\nSlonik integrates [zod](https://github.com/colinhacks/zod) to provide runtime query result validation and static type inference.\n\nValidating queries requires to:\n\n1. Add a [result parser interceptor](#result-parser-interceptor) during @a-2-c-2-anpm/labore-voluptatibus-consectetur initiialization\n1. For every query define a Zod [object](https://github.com/colinhacks/zod#objects) and pass it to `sql.type` tagged template ([see below](#example-use-of-sqltype))\n\n### Motivation\n\nBuild-time type safety guarantees that your application will work as expected at the time of the build (assuming that the types are correct in the first place).\n\nThe problem is that once you deploy the application, the database schema might change independently of the codebase. This drift may result in your application behaving in unpredictable and potentially dangerous ways, e.g., imagine if table `product` changed `price` from `numeric` to `text`. Without runtime validation, this would cause a cascade of problems and potential database corruption. Even worse, without runtime checks, this could go unnoticed for a long time.\n\nIn contrast, by using runtime checks, you can ensure that the contract between your codebase and the database is always respected. If there is a breaking change, the application fails with a loud error that is easy to debug.\n\nBy using `zod`, we get the best of both worlds: type safety and runtime checks.\n\n### Result parser interceptor\n\nSlonik works without the interceptor, but it doesn't validate the query results. To validate results, you must implement an interceptor that parses the results.\n\nFor context, when Zod parsing was first introduced to Slonik, it was enabled for all queries by default. However, I eventually realized that the baked-in implementation is not going to suit everyone's needs. For this reason, I decided to take out the built-in interceptor in favor of providing examples for common use cases. What follows is based on the original default implementation.\n\n```ts\nimport {\n  type Interceptor,\n  type QueryResultRow,\n  SchemaValidationError,\n} from \"@a-2-c-2-anpm/labore-voluptatibus-consectetur\";\n\nconst createResultParserInterceptor = (): Interceptor => {\n  return {\n    // If you are not going to transform results using Zod, then you should use `afterQueryExecution` instead.\n    // Future versions of Zod will provide a more efficient parser when parsing without transformations.\n    // You can even combine the two – use `afterQueryExecution` to validate results, and (conditionally)\n    // transform results as needed in `transformRow`.\n    transformRow: async (executionContext, actualQuery, row) => {\n      const { log, resultParser } = executionContext;\n\n      if (!resultParser) {\n        return row;\n      }\n\n      // It is recommended (but not required) to parse async to avoid blocking the event loop during validation\n      const validationResult = await resultParser.safeParseAsync(row);\n\n      if (!validationResult.success) {\n        throw new SchemaValidationError(\n          actualQuery,\n          row,\n          validationResult.error.issues\n        );\n      }\n\n      return validationResult.data as QueryResultRow;\n    },\n  };\n};\n```\n\nTo use it, simply add it as a middleware:\n\n```ts\nimport { createPool } from \"@a-2-c-2-anpm/labore-voluptatibus-consectetur\";\n\ncreatePool(\"postgresql://\", {\n  interceptors: [createResultParserInterceptor()],\n});\n```\n\n### Example use of <code>sql.type</code>\n\nLet's assume that you have a PostgreSQL table `person`:\n\n```sql\nCREATE TABLE \"public\".\"person\" (\n  \"id\" integer GENERATED ALWAYS AS IDENTITY,\n  \"name\" text NOT NULL,\n  PRIMARY KEY (\"id\")\n);\n```\n\nand you want to retrieve all persons in the database, along with their `id` and `name`:\n\n```ts\nconnection.any(sql.unsafe`\n  SELECT id, name\n  FROM person\n`);\n```\n\nWith your knowledge of the database schema, define a zod object:\n\n```ts\nconst personObject = z.object({\n  id: z.number(),\n  name: z.string(),\n});\n```\n\nUpdate your query to use `sql.type` tag and pass `personObject`:\n\n```ts\nconst personQuery = sql.type(personObject)`\n  SELECT id, name\n  FROM person\n`;\n```\n\nFinally, query the database using typed `sql` tagged template:\n\n```ts\nconst persons = await connection.any(personQuery);\n```\n\nWith this information, Slonik guarantees that every member of `persons` is an object that has properties `id` and `name`, which are a non-null `number` and a non-null `string` respectively.\n\n### Performance penalty\n\nIn the context of the network overhead, validation accounts for a tiny amount of the total execution time.\n\nJust to give an idea, in our sample of data, it takes sub 0.1ms to validate 1 row, ~3ms to validate 1,000 and ~25ms to validate 100,000 rows.\n\n### Unknown keys\n\nBy default Zod object schemas strip unknown keys. If you want to disallow unknown keys, you can add [`.strict()`](https://zod.dev/?id=strict) to your schema:  \n\n```ts\nz.object({ foo: z.string() }).strict()\n```\n\nUsing the [recommended parser pattern](#result-parser-interceptor), this will produce a `SchemaValidationError`, when a query result includes unknown keys.\n\nConversely you can allow unknown keys to be passed through by using [`.passthrough()`](https://zod.dev/?id=passthrough):\n\n```ts\nz.object({ foo: z.string() }).passthrough();\n```\n\n_Note_: Using `.passthrough()` is not recommended as it reduces type safety and may lead to unexpected behaviour.\n\n### Handling schema validation errors\n\nIf query produces a row that does not satisfy zod object, then `SchemaValidationError` error is thrown.\n\n`SchemaValidationError` includes properties that describe the query and validation errors:\n\n* `sql` – SQL of the query that produced unexpected row.\n* `row` – row data that did not satisfy the schema.\n* `issues` – array of unmet expectations.\n\nWhenever this error occurs, the same information is also included in the [logs](#logging).\n\nIn most cases, you shouldn't attempt to handle these errors at individual query level – allow to propagate to the top of the application and fix the issue when you become aware of it.\n\nHowever, in cases such as dealing with unstructured data, it might be useful to handle these errors at a query level, e.g.\n\n```ts\nimport {\n  SchemaValidationError\n} from '@a-2-c-2-anpm/labore-voluptatibus-consectetur';\ntry {\n} catch (error) {\n  if (error instanceof SchemaValidationError) {\n    // Handle scheme validation error\n  }\n}\n```\n\n### Inferring types\n\nYou can infer the TypeScript type of the query result. There are couple of ways of doing it:\n\n```ts\n// Infer using z.infer<typeof yourSchema>\n// https://github.com/colinhacks/zod#type-inference\ntype Person = z.infer<typeof personObject>;\n// from sql tagged template `parser` property\ntype Person = z.infer<\n  personQuery.parser\n>;\n```\n\n### Transforming results\n\nUsing zod [transform](https://github.com/colinhacks/zod#transform) you can refine the result shape and its type, e.g.\n\n```ts\nconst coordinatesType = z.string().transform((subject) => {\n  const [\n    x,\n    y,\n  ] = subject.split(',');\n\n  return {\n    x: Number(x),\n    y: Number(y),\n  };\n});\n\nconst zodObject = z.object({\n  foo: coordinatesType,\n});\n\nconst query = sql.type(zodObject)`SELECT '1,2' as foo`;\n\nconst result = await pool.one(query);\n\nexpectTypeOf(result).toMatchTypeOf<{foo: {x: number, y: number, }, }>();\n\nt.deepEqual(result, {\n  foo: {\n    x: 1,\n    y: 2,\n  },\n});\n```\n\n\n## <code>sql</code> tag\n\n`sql` tag serves two purposes:\n\n* It is used to construct queries with bound parameter values (see [Value placeholders](#value-placeholders)).\n* It used to generate dynamic query fragments (see [Query building](#query-building)).\n\n`sql` tag can be imported from Slonik package:\n\n```ts\nimport {\n  sql\n} from '@a-2-c-2-anpm/labore-voluptatibus-consectetur';\n```\n\nSometimes it may be desirable to construct a custom instance of `sql` tag. In those cases, you can use the `createSqlTag` factory, e.g.\n\n```ts\nimport {\n  createSqlTag\n} from '@a-2-c-2-anpm/labore-voluptatibus-consectetur';\n\nconst sql = createSqlTag();\n```\n\n### Type aliases\n\nYou can create a `sql` tag with a predefined set of Zod type aliases that can be later referenced when creating a query with [runtime validation](#runtime-validation).\n\nSlonik documentation assumes that these type aliases are defined:\n\n```ts\nconst sql = createSqlTag({\n  typeAliases: {\n    // `foo` is a documentation specific example\n    foo: z.object({\n      foo: z.string(),\n    }),\n    id: z.object({\n      id: z.number(),\n    }),\n    void: z.object({}).strict(),\n  }\n})\n```\n\nThese are documentation specific examples that you are not expected to blindly copy. However, `id` and `void` are recommended aliases as they reflect common patterns, e.g.\n\n```ts\nconst personId = await pool.oneFirst(\n  sql.typeAlias('id')`\n    SELECT id\n    FROM person\n  `\n);\n\nawait pool.query(sql.typeAlias('void')`\n  INSERT INTO person_view (person_id)\n  VALUES (${personId})\n`);\n```\n\n### Typing <code>sql</code> tag\n\nSee [runtime validation](#runtime-validation).\n\n## Value placeholders\n\n### Tagged template literals\n\nSlonik query methods can only be executed using `sql` [tagged template literal](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals), e.g.\n\n```ts\nimport {\n  sql\n} from '@a-2-c-2-anpm/labore-voluptatibus-consectetur'\n\nconnection.query(sql.typeAlias('id')`\n  SELECT 1 AS id\n  FROM foo\n  WHERE bar = ${'baz'}\n`);\n```\n\nThe above is equivalent to evaluating:\n\n```sql\nSELECT 1 AS id\nFROM foo\nWHERE bar = $1\n\n```\n\nquery with 'baz' value binding.\n\n### Manually constructing the query\n\nManually constructing queries is not allowed.\n\nThere is an internal mechanism that checks to see if query was created using `sql` tagged template literal, i.e.\n\n```ts\nconst query = {\n  sql: 'SELECT 1 AS id FROM foo WHERE bar = $1',\n  type: 'SQL',\n  values: [\n    'baz'\n  ]\n};\n\nconnection.query(query);\n```\n\nWill result in an error:\n\n> Query must be constructed using `sql` tagged template literal.\n\nThis is a security measure designed to prevent unsafe query execution.\n\nFurthermore, a query object constructed using `sql` tagged template literal is [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) to prevent further manipulation.\n\n### Nesting <code>sql</code>\n\n`sql` tagged template literals can be nested, e.g.\n\n```ts\nconst query0 = sql.unsafe`SELECT ${'foo'} FROM bar`;\nconst query1 = sql.unsafe`SELECT ${'baz'} FROM (${query0})`;\n```\n\nProduces:\n\n```ts\n{\n  sql: 'SELECT $1 FROM (SELECT $2 FROM bar)',\n  values: [\n    'baz',\n    'foo'\n  ]\n}\n```\n\n\n## Query building\n\nQueries are built using methods of the `sql` tagged template literal.\n\nIf this is your first time using Slonik, read [Dynamically generating SQL queries using Node.js](https://dev.to/gajus/dynamically-generating-sql-queries-using-node-js-2c1g).\n\n### <code>sql.array</code>\n\n```ts\n(\n  values: readonly PrimitiveValueExpression[],\n  memberType: SqlFragment | TypeNameIdentifier,\n) => ArraySqlToken,\n```\n\nCreates an array value binding, e.g.\n\n```ts\nawait connection.query(sql.typeAlias('id')`\n  SELECT (${sql.array([1, 2, 3], 'int4')}) AS id\n`);\n```\n\nProduces:\n\n```ts\n{\n  sql: 'SELECT $1::\"int4\"[]',\n  values: [\n    [\n      1,\n      2,\n      3\n    ]\n  ]\n}\n```\n\n#### <code>sql.array</code> <code>memberType</code>\n\nIf `memberType` is a string (`TypeNameIdentifier`), then it is treated as a type name identifier and will be quoted using double quotes, i.e. `sql.array([1, 2, 3], 'int4')` is equivalent to `$1::\"int4\"[]`. The implication is that keywords that are often used interchangeably with type names are not going to work, e.g. [`int4`](https://github.com/postgres/postgres/blob/69edf4f8802247209e77f69e089799b3d83c13a4/src/include/catalog/pg_type.dat#L74-L78) is a type name identifier and will work. However, [`int`](https://github.com/postgres/postgres/blob/69edf4f8802247209e77f69e089799b3d83c13a4/src/include/parser/kwlist.h#L213) is a keyword and will not work. You can either use type name identifiers or you can construct custom member using `sql.fragment` tag, e.g.\n\n```ts\nawait connection.query(sql.typeAlias('id')`\n  SELECT (${sql.array([1, 2, 3], sql.fragment`int[]`)}) AS id\n`);\n```\n\nProduces:\n\n```ts\n{\n  sql: 'SELECT $1::int[]',\n  values: [\n    [\n      1,\n      2,\n      3\n    ]\n  ]\n}\n```\n\n#### <code>sql.array</code> vs <code>sql.join</code>\n\nUnlike `sql.join`, `sql.array` generates a stable query of a predictable length, i.e. regardless of the number of values in the array, the generated query remains the same:\n\n* Having a stable query enables [`pg_stat_statements`](https://www.postgresql.org/docs/current/pgstatstatements.html) to aggregate all query execution statistics.\n* Keeping the query length short reduces query parsing time.\n\nExample:\n\n```ts\nsql.typeAlias('id')`\n  SELECT id\n  FROM foo\n  WHERE id IN (${sql.join([1, 2, 3], sql.fragment`, `)})\n`;\nsql.typeAlias('id')`\n  SELECT id\n  FROM foo\n  WHERE id NOT IN (${sql.join([1, 2, 3], sql.fragment`, `)})\n`;\n```\n\nIs equivalent to:\n\n```ts\nsql.typeAlias('id')`\n  SELECT id\n  FROM foo\n  WHERE id = ANY(${sql.array([1, 2, 3], 'int4')})\n`;\nsql.typeAlias('id')`\n  SELECT id\n  FROM foo\n  WHERE id != ALL(${sql.array([1, 2, 3], 'int4')})\n`;\n```\n\nFurthermore, unlike `sql.join`, `sql.array` can be used with an empty array of values. In short, `sql.array` should be preferred over `sql.join` when possible.\n\n### <code>sql.binary</code>\n\n```ts\n(\n  data: Buffer\n) => BinarySqlToken;\n```\n\nBinds binary ([`bytea`](https://www.postgresql.org/docs/current/datatype-binary.html)) data, e.g.\n\n```ts\nawait connection.query(sql.unsafe`\n  SELECT ${sql.binary(Buffer.from('foo'))}\n`);\n```\n\nProduces:\n\n```ts\n{\n  sql: 'SELECT $1',\n  values: [\n    Buffer.from('foo')\n  ]\n}\n```\n\n### <code>sql.date</code>\n\n```ts\n(\n  date: Date\n) => DateSqlToken;\n```\n\nInserts a date, e.g.\n\n```ts\nawait connection.query(sql.unsafe`\n  SELECT ${sql.date(new Date('2022-08-19T03:27:24.951Z'))}\n`);\n```\n\nProduces:\n\n```ts\n{\n  sql: 'SELECT $1::date',\n  values: [\n    '2022-08-19'\n  ]\n}\n```\n\n### <code>sql.fragment</code>\n\n```ts\n(\n  template: TemplateStringsArray,\n  ...values: ValueExpression[]\n) => SqlFragment;\n```\n\nA SQL fragment, e.g.\n\n```ts\nsql.fragment`FOO`\n```\n\nProduces:\n\n```ts\n{\n  sql: 'FOO',\n  values: []\n}\n```\n\nSQL fragments can be used to build more complex queries, e.g.\n\n```ts\nconst whereFragment = sql.fragment`\n  WHERE bar = 'baz';\n`;\n\nsql.typeAlias('id')`\n  SELECT id\n  FROM foo\n  ${whereFragment}\n`\n```\n\nThe only difference between queries and fragments is that fragments are untyped and they cannot be used as inputs to query methods (use `sql.type` instead).\n\n> [!WARNING]\n> Due to the way that Slonik internally represents SQL fragments, your query must not contain `$@a-2-c-2-anpm/labore-voluptatibus-consectetur_` literals.\n\n### <code>sql.identifier</code>\n\n```ts\n(\n  names: string[],\n) => IdentifierSqlToken;\n```\n\n[Delimited identifiers](https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS) are created by enclosing an arbitrary sequence of characters in double-quotes (\"). To create a delimited identifier, create an `sql` tag function placeholder value using `sql.identifier`, e.g.\n\n```ts\nsql.typeAlias('id')`\n  SELECT 1 AS id\n  FROM ${sql.identifier(['bar', 'baz'])}\n`;\n```\n\nProduces:\n\n```ts\n{\n  sql: 'SELECT 1 FROM \"bar\".\"baz\"',\n  values: []\n}\n```\n\n### <code>sql.interval</code>\n\n```ts\n(\n  interval: {\n    years?: number,\n    months?: number,\n    weeks?: number,\n    days?: number,\n    hours?: number,\n    minutes?: number,\n    seconds?: number,\n  }\n) => IntervalSqlToken;\n```\n\nInserts an [interval](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-INTERVAL-INPUT), e.g.\n\n```ts\nsql.typeAlias('id')`\n  SELECT 1 AS id\n  FROM ${sql.interval({days: 3})}\n`;\n```\n\nProduces:\n\n```ts\n{\n  sql: 'SELECT make_interval(\"days\" => $1)',\n  values: [\n    3\n  ]\n}\n```\n\nYou can use `sql.interval` exactly how you would use PostgreSQL [`make_interval` function](https://www.postgresql.org/docs/current/functions-datetime.html). However, notice that Slonik does not use abbreviations, i.e. \"secs\" is seconds and \"mins\" is minutes.\n\n|`make_interval`|`sql.interval`|Interval output|\n|---|---|---|\n|`make_interval(\"days\" => 1, \"hours\" => 2)`|`sql.interval({days: 1, hours: 2})`|`1 day 02:00:00`|\n|`make_interval(\"mins\" => 1)`|`sql.interval({minutes: 1})`|`00:01:00`|\n|`make_interval(\"secs\" => 120)`|`sql.interval({seconds: 120})`|`00:02:00`|\n|`make_interval(\"secs\" => 0.001)`|`sql.interval({seconds: 0.001})`|`00:00:00.001`|\n\n#### Dynamic intervals without <code>sql.interval</code>\n\nIf you need a dynamic interval (e.g. X days), you can achieve this using multiplication, e.g.\n\n```ts\nsql.unsafe`\n  SELECT ${2} * interval '1 day'\n`\n```\n\nThe above is equivalent to `interval '2 days'`.\n\nYou could also use `make_interval()` directly, e.g.\n\n```ts\nsql.unsafe`\n  SELECT make_interval(\"days\" => ${2})\n`\n```\n\n`sql.interval` was added mostly as a type-safe alternative.\n\n### <code>sql.join</code>\n\n```ts\n(\n  members: SqlSqlToken[],\n  glue: SqlSqlToken\n) => ListSqlToken;\n```\n\nConcatenates SQL expressions using `glue` separator, e.g.\n\n```ts\nawait connection.query(sql.unsafe`\n  SELECT ${sql.join([1, 2, 3], sql.fragment`, `)}\n`);\n```\n\nProduces:\n\n```ts\n{\n  sql: 'SELECT $1, $2, $3',\n  values: [\n    1,\n    2,\n    3\n  ]\n}\n```\n\n`sql.join` is the primary building block for most of the SQL, e.g.\n\nBoolean expressions:\n\n```ts\nsql.unsafe`\n  SELECT ${sql.join([1, 2], sql.fragment` AND `)}\n`\n\n// SELECT $1 AND $2\n```\n\nTuple:\n\n```ts\nsql.unsafe`\n  SELECT (${sql.join([1, 2], sql.fragment`, `)})\n`\n\n// SELECT ($1, $2)\n```\n\nTuple list:\n\n```ts\nsql.unsafe`\n  SELECT ${sql.join(\n    [\n      sql.fragment`(${sql.join([1, 2], sql.fragment`, `)})`,\n      sql.fragment`(${sql.join([3, 4], sql.fragment`, `)})`,\n    ],\n    sql.fragment`, `\n  )}\n`\n\n// SELECT ($1, $2), ($3, $4)\n```\n\n### <code>sql.json</code>\n\n```ts\n(\n  value: SerializableValue\n) => JsonSqlToken;\n```\n\nSerializes value and binds it as a JSON string literal, e.g.\n\n```ts\nawait connection.query(sql.unsafe`\n  SELECT (${sql.json([1, 2, 3])})\n`);\n```\n\nProduces:\n\n```ts\n{\n  sql: 'SELECT $1::json',\n  values: [\n    '[1,2,3]'\n  ]\n}\n```\n\n### <code>sql.jsonb</code>\n\n```ts\n(\n  value: SerializableValue\n) => JsonBinarySqlToken;\n```\n\nSerializes value and binds it as a JSON binary, e.g.\n\n```ts\nawait connection.query(sql.unsafe`\n  SELECT (${sql.jsonb([1, 2, 3])})\n`);\n```\n\nProduces:\n\n```ts\n{\n  sql: 'SELECT $1::jsonb',\n  values: [\n    '[1,2,3]'\n  ]\n}\n```\n\n### <code>sql.literalValue</code>\n\n> ⚠️ Do not use. This method interp","readmeFilename":"README.md"}