{"id":13683384,"url":"https://github.com/malthe/ts-postgres","last_synced_at":"2025-04-06T16:12:48.225Z","repository":{"id":33130637,"uuid":"152731109","full_name":"malthe/ts-postgres","owner":"malthe","description":"Non-blocking PostgreSQL client for Node.js written in TypeScript.","archived":false,"fork":false,"pushed_at":"2024-04-12T20:34:43.000Z","size":719,"stargazers_count":102,"open_issues_count":6,"forks_count":8,"subscribers_count":6,"default_branch":"master","last_synced_at":"2024-04-14T04:55:36.882Z","etag":null,"topics":["hacktoberfest","postgres","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/malthe.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGES.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-10-12T09:59:47.000Z","updated_at":"2024-06-13T10:02:33.985Z","dependencies_parsed_at":"2023-11-07T17:37:53.480Z","dependency_job_id":"961d951a-6a3c-4dde-b994-ebff7df96026","html_url":"https://github.com/malthe/ts-postgres","commit_stats":{"total_commits":227,"total_committers":5,"mean_commits":45.4,"dds":"0.12334801762114533","last_synced_commit":"d79d914bde9ee0724519ac5d2b44d315ec2114ec"},"previous_names":[],"tags_count":27,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/malthe%2Fts-postgres","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/malthe%2Fts-postgres/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/malthe%2Fts-postgres/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/malthe%2Fts-postgres/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/malthe","download_url":"https://codeload.github.com/malthe/ts-postgres/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247509235,"owners_count":20950232,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest","postgres","typescript"],"created_at":"2024-08-02T13:02:09.276Z","updated_at":"2025-04-06T16:12:48.207Z","avatar_url":"https://github.com/malthe.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"![Build Status](https://github.com/malthe/ts-postgres/actions/workflows/main.yml/badge.svg)\n\u003cspan class=\"badge-npmversion\"\u003e\u003ca href=\"https://npmjs.org/package/ts-postgres\" title=\"View this project on NPM\"\u003e\u003cimg src=\"https://img.shields.io/npm/v/ts-postgres.svg\" alt=\"NPM version\" /\u003e\u003c/a\u003e\u003c/span\u003e\n\u003cspan class=\"badge-npmdownloads\"\u003e\u003ca href=\"https://npmjs.org/package/ts-postgres\" title=\"View this project on NPM\"\u003e\u003cimg src=\"https://img.shields.io/npm/dm/ts-postgres.svg\" alt=\"NPM downloads\" /\u003e\u003c/a\u003e\u003c/span\u003e\n\nNon-blocking PostgreSQL client for Node.js written in TypeScript.\n\n### Install\n\nTo install the latest version of this library:\n\n```sh\n$ npm install ts-postgres\n```\n\n### Features\n\n- Fast!\n- Supports binary and text value formats (result data always uses binary)\n- Multiple queries can be sent at once (pipeline)\n- Extensible value model\n- Hybrid query result object\n  - Iterable (synchronous or asynchronous; one object at a time)\n  - Rows and column names\n  - Streaming data directly into a socket\n- Supports CommonJS and ESM modules\n- No dependencies\n\nSee the [documentation](https://malthe.github.io/ts-postgres/) for a complete reference.\n\n---\n\n## Usage\n\nThe client uses an async/await-based programming model.\n\n```typescript\nimport { connect } from 'ts-postgres';\n\ninterface Greeting {\n  message: string;\n}\n\nconst client = await connect();\n\ntry {\n  // The query method is generic on the result row.\n  const result = client.query\u003cGreeting\u003e(\n    \"SELECT 'Hello ' || $1 || '!' AS message\",\n    ['world'],\n  );\n\n  for await (const obj of result) {\n    // 'Hello world!'\n    console.log(obj.message);\n  }\n} finally {\n  await client.end();\n}\n```\n\nWith TypeScript 5.2+ there is also support for `await using`:\n```typescript\nawait using client = await connect();\n// Will be disposed of automatically at the end of the block.\n```\n\nWaiting on the result (i.e., result iterator) returns the complete query result.\n\n```typescript\nconst result = await client.query(...)\n```\n\nIf the query fails, an exception is thrown.\n\n### Connection options\n\nThe client constructor takes an optional\n[Configuration](https://malthe.github.io/ts-postgres/interfaces/Configuration.html) object.\n\nFor example, to connect to a remote host use the _host_ configuration key:\n\n```typescript\nconst client = await connect({\"host\": \u003chostname\u003e});\n```\n\nThe following table lists the various configuration options and their\ndefault value when applicable.\n\n| Key                     | Type                             | Default                                    |\n| ----------------------- | :------------------------------- | ------------------------------------------ |\n| host                    | `string`                         | \"localhost\"                                |\n| port                    | `number`                         | 5432                                       |\n| user                    | `string`                         | _The username of the process owner_        |\n| database                | `string`                         | \"postgres\"                                 |\n| password                | `string`                         |                                            |\n| types                   | `Map\u003cDataType, ValueTypeReader\u003e` | _Default value mapping for built-in types_ |\n| extraFloatDigits        | `number`                         | 0                                          |\n| keepAlive               | `boolean`                        | true                                       |\n| preparedStatementPrefix | `string`                         | \"tsp\\_\"                                    |\n| connectionTimeout       | `number`                         | 10                                         |\n| ssl                     | `(SSLMode.Disable \\| SSL)`       | `{ mode: SSLMode.Prefer }`                 |\n\nWhen applicable, \"PG\" environment variables used by _libpq_ apply, see\nthe PostgreSQL documentation on [environment\nvariables](https://www.postgresql.org/docs/current/libpq-envars.html).\n\n#### SSL/TLS configuration\n\nAs shown in the configuration options table in the previous section,\nthe default behavior is to _prefer_ making a secure connection. That\nis, if the database has SSL/TLS configured, then the client will\neither make a secure connection or not connect at all.\n\nFor a self-signed certificate or a certificate that's not verifiable\nby the system certificates, either provide the signing certificate\nusing the `NODE_EXTRA_CA_CERTS` environment variable, or disable\nSSL/TLS altogether using `SSLMode.Disable` or the environment variable\n`PGSSLMODE=disable`.\n\nNote that _libpq_ supports a number of additional [SSL/TLS connection\nmodes](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLMODE)\nbut most of them do not sit well with Node's [tls\nmodule](https://nodejs.org/api/tls.html) and are not offered here.\n\n### Querying\n\nThe `query` method accepts a text string or a\n[Query](https://malthe.github.io/ts-postgres/interfaces/Query.html) object \nas the first parameter, and a tuple of values as the second parameter. \n\nThe initial example above could be written as:\n\n```typescript\nconst query = { text: \"SELECT 'Hello ' || $1 || '!' AS message\" };\nconst result = await client.query\u003cGreeting\u003e(query, ['world']);\n```\n\nThe `Query` object has a number of optional properties that can change\nhow the query is carried out, including column name transformation.\n\nIf the object type is omitted, it defaults to `Record\u003cstring, any\u003e`, but\nproviding a type ensures that the object values are typed, both when\naccessed via the iterator or record interface (see below).\n\n### Passing query parameters\n\nQuery parameters use the format `$1`, `$2` etc.\n\nWhen a specific data type can't be inferred from the query, PostgreSQL\nuses `DataType.Text` as the default data type (which is mapped to the\nstring type in TypeScript). An explicit type can be provided in two\ndifferent ways:\n\n1. Using type cast in the query, e.g. `$1::int`.\n\n2. By passing a list of types to the query method:\n\n   ```typescript\n   import { DataType } from 'ts-postgres';\n   const result = await client.query(\n     \"SELECT $1 || ' bottles of beer'\",\n     [99],\n     [DataType.Int4],\n   );\n   ```\n\nNote that the `number` type in TypeScript has a maximum safe integer\nvalue which is 2⁵³ – 1 (also given in the `Number.MAX_SAFE_INTEGER` constant),\na value which lies between `DataType.Int4` and `DataType.Int8`. For numbers\nwhich can take on a value that's outside the safe range, use `DataType.Int8`\n(which translates to a `bigint` in TypeScript.)\n\nThere's an optional setting `bigints` which can be configured on the client and/or\nspecified for each query. It defaults to _true_, but can be set to _false_ in which\ncase `number` is always used instead of `bigint` for `DataType.Int8` (throwing an\nerror if a query returns a value outside of the safe integer range.)\n\nUsing a [check constraint](https://www.postgresql.org/docs/current/ddl-constraints.html)\nis recommended to ensure that values fit into the safe\ninteger range, e.g. `CHECK (id \u003c POWER(2, 53) - 1)`.\n\n### Iterator interface\n\nThe query result can be iterated over, either asynchronously, or after being awaited. The returned objects are reified representations of the result rows, provided as _objects_ of the generic type parameter specified for the query (optional, it defaults to `Record\u003cstring, any\u003e`).\n\nTo extract all objects from the query result, you can use the _spread_ operator:\n\n```typescript\nconst result = await client.query('SELECT generate_series(0, 9) AS i');\nconst objects = [...result];\n```\n\nThe asynchronous await syntax around for-loops is another option:\n\n```typescript\nconst result = client.query(...);\nfor await (const obj of result) {\n  console.log('The number is: ' + obj.i); // 1, 2, 3, ...\n}\n```\n\n### Result interface\n\nThe awaited result object provides an interface based on rows and column names.\n\n```typescript\nfor (const row of result.rows) {\n  // Using the array indices:\n  console.log('The number is: ' + row[0]); // 1, 2, 3, ...\n\n  // Using the column name:\n  console.log('The number is: ' + row.get('i')); // 1, 2, 3, ...\n}\n```\n\nColumn names are available via the `names` property.\n\n### Streaming\n\nA query can support streaming of one or more columns directly into an\nasynchronous stream such as a network socket, or a file.\n\nAssuming that `socket` is a writable stream:\n\n```typescript\nconst result = await client.query({\n  text: 'SELECT some_bytea_column',\n  streams: { some_bytea_column: socket },\n});\n```\n\nThis can for example be used to reduce time to first byte and memory use.\n\n### Multiple queries\n\nThe query command accepts a single query only. If you need to send multiple queries, just call the method multiple times. For example, to send an update command in a transaction:\n\n```typescript\nclient.query('begin');\nclient.query('update ...');\nawait client.query('commit');\n```\n\nThe queries are sent back to back over the wire, but PostgreSQL still processes them one at a time, in the order they were sent (first in, first out).\n\n### Prepared statements\n\nYou can prepare a query and subsequently execute it multiple times. This is also known as a \"prepared statement\".\n\n```typescript\nconst statement = await client.prepare(\n  `SELECT 'Hello ' || $1 || '!' AS message`,\n);\nfor await (const object of statement.execute(['world'])) {\n  console.log(object.message); // 'Hello world!'\n}\n```\n\nWhen the prepared statement is no longer needed, it should be closed to release the resource.\n\n```typescript\nawait statement.close();\n```\nWith TypeScript 5.2+ it's also possible to use the `await using` construct which automatically closes the statement at the end of the block.\n\n\nPrepared statements can be used (executed) multiple times, even concurrently.\n\n## Notes\n\nQueries with parameters are sent using the prepared statement variant of the extended query protocol. In this variant, the type of each parameter is determined prior to parameter binding, ensuring that values are encoded in the correct format.\n\nIf a query has no parameters, it uses the portal variant which saves a round trip.\n\nThe copy commands are not supported.\n\n## FAQ\n\n1. _How do I set up a connection pool?_ You can for example use the [generic-pool](https://www.npmjs.com/package/generic-pool) library.\n\n   See the [generic-pool](./examples/generic-pool/) code example.\n\n2. _How do I convert column names to camelcase?_ Use the `transform` option:\n\n   ```typescript\n   const camelcase = (s: string) =\u003e s.replace(/(_\\w)/g, k =\u003e k[1].toUpperCase());\n   const result = client.query({text: ..., transform: camelcase})\n   ```\n\n3. _How do I use LISTEN/NOTIFY?_ Send `LISTEN` as a regular query, then subscribe to\n   notifications, filtering out the relevant channels.\n\n   ```typescript\n   import type { Notification } from 'ts-postgres';\n\n   const channel = 'test';\n   client.on('notification', (message: Notification) =\u003e {\n     if (message.channel === channel) {\n       // Do stuff\n     }\n   });\n   await client.query(`LISTEN ${channel}`);\n   ```\n\n## Benchmarking\n\nUse the following environment variable to run tests in \"benchmark\" mode.\n\n```bash\n$ NODE_ENV=benchmark npm run test\n```\n\n## Support\n\nts-postgres is free software. If you encounter a bug with the library please open an issue on the [GitHub repo](https://github.com/malthe/ts-postgres).\n\n## License\n\nCopyright (c) 2018-2024 Malthe Borch (mborch@gmail.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmalthe%2Fts-postgres","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmalthe%2Fts-postgres","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmalthe%2Fts-postgres/lists"}