{"id":22221116,"url":"https://github.com/davesag/sequelize-pg-utilities","last_synced_at":"2025-07-27T16:31:05.765Z","repository":{"id":32859863,"uuid":"144455637","full_name":"davesag/sequelize-pg-utilities","owner":"davesag","description":"An opinionated set of database utilities that simplify creating and connecting to a Postgres database","archived":false,"fork":false,"pushed_at":"2024-04-23T05:51:20.000Z","size":2446,"stargazers_count":17,"open_issues_count":0,"forks_count":3,"subscribers_count":3,"default_branch":"develop","last_synced_at":"2024-05-02T00:12:36.478Z","etag":null,"topics":["configuration","nodejs","pgtools","sequelize","sequelize-cli"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/davesag.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["davesag"]}},"created_at":"2018-08-12T09:56:28.000Z","updated_at":"2024-06-26T07:29:26.716Z","dependencies_parsed_at":"2024-02-19T07:23:17.885Z","dependency_job_id":"4ca81ac6-e910-422c-ae1b-2022fe7fa980","html_url":"https://github.com/davesag/sequelize-pg-utilities","commit_stats":{"total_commits":366,"total_committers":6,"mean_commits":61.0,"dds":"0.10109289617486339","last_synced_commit":"9024ff992d8a6d8d057aa25ac527bb94f5c2f64a"},"previous_names":[],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davesag%2Fsequelize-pg-utilities","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davesag%2Fsequelize-pg-utilities/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davesag%2Fsequelize-pg-utilities/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davesag%2Fsequelize-pg-utilities/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/davesag","download_url":"https://codeload.github.com/davesag/sequelize-pg-utilities/tar.gz/refs/heads/develop","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":227674006,"owners_count":17802301,"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":["configuration","nodejs","pgtools","sequelize","sequelize-cli"],"created_at":"2024-12-02T23:12:19.792Z","updated_at":"2024-12-02T23:12:20.560Z","avatar_url":"https://github.com/davesag.png","language":"JavaScript","funding_links":["https://github.com/sponsors/davesag"],"categories":[],"sub_categories":[],"readme":"# sequelize-pg-utilities\n\n[`Sequelize`](https://github.com/sequelize/sequelize), and the [`Sequelize CLI`](https://github.com/sequelize/cli), use slightly different database configuration objects, and neither provide a mechanism for creating a [`Postgresql`](https://www.postgresql.org) database. I work with `Sequelize` a lot in my day-job so decided to write a simple utility suite that manages the different configuration needs any project using `Sequelize` inevitably needs.\n\nWhen your application starts yo need to construct correct database configuration values as a mix of a config file, selected environment variables, and sensible defaults.\n\n`sequelize-pg-utilities` is an opinionated set of database utilities that, together, simplify creating and connecting to a `Postgres` database via `Sequelize`, or the `Sequelize CLI`, via a common, and minimal, set of config file settings. You can use environment variables to override the config file settings, as well as supply a range of detailed programmatic settings that get passed on to Sequelize directly. If no values are supplied and a value is needed by Sequelize then this defines sensible defaults. Any values not needed and which have no value are simply removed from the config object sent to Sequelize.\n\n[![NPM](https://nodei.co/npm/sequelize-pg-utilities.png)](https://nodei.co/npm/sequelize-pg-utilities/)\n\n## Related Projects\n\n- [`sequelize-test-helpers`](https://github.com/davesag/sequelize-test-helpers) — Mocks and helpers that simplify unit testing of `Sequelize` models.\n\n## Prerequisites\n\nThis library assumes:\n\n1. You are using NodeJS 8.10+\n2. You are using [`Sequelize`](https://github.com/sequelize/sequelize) to manage interactions with [`Postgresql`](https://www.postgresql.org)\n\n## Install\n\nAdd `sequelize-pg-utilities` and [`pg`](https://github.com/brianc/node-postgres/tree/master/packages/pg) as dependencies:\n\n```sh\nnpm i pg sequelize-pg-utilities\n```\n\n**Note**: `pg` is a peer-dependency of `sequelize-pg-utilities`.\n\n## Usage Scenarios\n\n### Configuration\n\nTypically a Sequelize project will include a `config/config.json` file with entries as follows:\n\n```json\n{\n  \"development\": {\n    \"username\": \"my-dev-user\",\n    \"password\": \"my-dev-password\",\n    \"database\": \"my-project-development\"\n  },\n  \"test\": {\n    \"username\": \"my-test-user\",\n    \"password\": \"my-test-password\",\n    \"database\": \"my-project-test\"\n  },\n  \"production\": {\n    \"username\": \"my-production-user\",\n    \"password\": \"my-production-password\",\n    \"database\": \"my-project-prod\"\n  }\n}\n```\n\nWhen your application starts you'll need to construct correct database configuration values as a mix of the above config file, selected environment variables, and sensible defaults.\n\nTo do this simply create a configuration object as follows:\n\n```js\nconst { configure } = require('sequelize-pg-utilities')\nconst config = require('path/to/config/config.json')\n\nconst { name, user, password, options } = configure(config)\n```\n\nThese configuration values can then be passed in to Sequelize as follows:\n\n```js\nconst sequelize = new Sequelize(name, user, password, options)\n```\n\n#### Environment Variables Supported\n\nThe following environment variables take precedence over whatever is defined in `config/config.json`\n\n- `DATABASE_URL` The database url, if provided, will override many of the below `DB` settings.\n- `DB_NAME` The database name — You may also supply a default (see below)\n- `DB_USER` The database user — no default\n- `DB_PASS` The database password — no default\n- `DB_POOL_MAX` The maximum number of database connections — Defaults to `5`\n- `DB_POOL_MIN` The minimum number of database connections — Defaults to `1`\n- `DB_POOL_IDLE` The database idle time — Defaults to `10000` ms\n- `DB_HOST` The database host — Defaults to `'localhost'`\n- `DB_PORT` The database port — Defaults to `5432`\n- `DB_TYPE` The database type — Defaults to `'postgres'` — This library is written with Postgres in mind so please don't change this unless you know what you are doing.\n\nThe following environment variables remain unset if they don't appear, or get set in `config/config.json`.\n\n- `DB_POOL_ACQUIRE` The database pool's `acquire` value.\n- `DB_POOL_EVICT` The database pool's `evict` value.\n\n#### Regarding `DATABASE_URL`\n\nIf you supply the `DATABASE_URL` environment variable, as Heroku and other PaaS systems generally do, then the `configure` function will extract most of what it needs from that and the extracted values will take priority over other values.\n\n### Initialisation of a database\n\nIn `development` and `test` environments, you'll need your server to create a database the first time it runs. To do this you can make an `initialiser` using the `makeInitialiser` function.\n\n```js\nconst { makeInitialiser } = require('sequelize-pg-utilities')\nconst config = require('path/to/config/config.json')\n\nconst initialise = makeInitialiser(config)\n\nconst start = async () =\u003e {\n  try {\n    const result = await initialise()\n    console.log(result.message)\n\n    // now do whatever else is needed to start your server\n  } catch (err) {\n    console.error('Could not start server', err)\n    process.exit(1)\n  }\n}\n```\n\nYou can set the number of retries by passing it in as a parameter to `initialise`. The default is `5`.\n\n```js\nconst result = await initialise(10)\n```\n\nOn each retry it will wait for a progressively longer period of time, starting with 2 seconds, and increasing the delay by 2 seconds each retry.\n\nThe `result` object has two properties:\n\n```js\n{\n  dbNew: false, // or true if a new database was created?\n  message: 'More information' // some clarifying text.\n}\n```\n\nIn `production` it assumes your database already exists.\n\n### Configuring migrations\n\nThe Sequelize CLI requires a `.sequelizerc` file at the root of the project that exports data such as `config`, `migrations-path`, and `models-path`.\n\nThe `config` required by the Sequelize CLI is an object in the form:\n\n```js\n{\n  [env]: {\n    username,\n    password,\n    database,\n    dialect,\n    host,\n    port,\n    // optionally also the following\n    pool: {\n      acquire: 20000,\n      evict: 15000,\n      min: 5,\n      max: 15,\n      idle: 10000\n    },\n    protocol,\n    ssl: {\n      rejectUnauthorized: false,\n      ca: 'some-root-cert',\n      key: 'some-client-key',\n      cert: 'some-client-certificate'\n    }\n  }\n}\n```\n\nUse the `migrationConfig` function to generate configuration details to suit Sequelize CLI's needs from your common `config` file, or environment variables.\n\nCreate a `migrationConfig.js` file as follows:\n\n```js\nconst { migrationConfig } = require('sequelize-pg-utilities')\nconst config = require('path/to/config/config.json')\n\nmodule.exports = migrationConfig(config)\n```\n\nThen in `.sequelizerc` file do this:\n\n```js\nconst path = require('path')\n\nmodule.exports = {\n  config: path.resolve(__dirname, 'path', 'to', 'migrationConfig.js'),\n  'migrations-path': path.resolve(__dirname, 'migrations'),\n  'models-path': path.resolve(__dirname, 'src', 'models')\n}\n```\n\n### Function Signature\n\nThe `configure`, `makeInitialiser`, and `migrationConfig` functions all have an identical signature.\n\nThey each accept the following parameters.\n\n- `config`: The content of the `config/config.json` file. Required, no default.\n\n  Configuration file is in the form:\n\n  ```js\n  {\n    [env]: {\n      // everything is optional but these are usually set here\n      username,\n      password,\n      database,\n      dialect,\n      host,\n      port,\n      // less often used but optionally also the following\n      benchmark,\n      clientMinMessages,\n      native,\n      omitNull,\n      pool: {\n        acquire: 20000,\n        evict: 15000,\n        min: 5,\n        max: 15,\n        idle: 10000\n      },\n      protocol,\n      // if you have ssl specifics\n      ssl: {\n        rejectUnauthorized: false,\n        ca: 'some-root-cert',\n        key: 'some-client-key',\n        cert: 'some-client-certificate'\n      },\n      replication,\n      timezone\n    }\n  }\n  ```\n\n- `defaultDbName`: If the database name is not set in an environment variable, and if the config file does not define a database name, then use this as the database name. Optional, no default.\n- `logger`: You can pass in a logger function here for Sequelize to use. Optional, default is `false`, meaning don't log anything. This gets returned as `logging` in the configs.\n- `options`: optional additional configuration that is passed through to Sequelize.\n\n  These match to the options listed at [sequelize/sequelize/lib/sequelize.js#126](https://github.com/sequelize/sequelize/blob/master/lib/sequelize.js#L126), which at the time of this writing are:\n\n  - `dialectModule`,\n  - `dialectModulePath`,\n  - `define`,\n  - `query`,\n  - `schema`,\n  - `set`,\n  - `sync`,\n  - `quoteIdentifiers`,\n  - `transactionType`,\n  - `typeValidation`,\n  - `hooks`,\n  - `pool.validate`,\n  - `retry.match`,\n  - `retry.max`\n\n  Other additional options are ignored.\n\n### SSL Options\n\nIf you supply `ssl` options in your `config.json` file then these will be injected into your configuration as `dialectOptions` and the `ssl` option will be set to `true`.\n\nNote this is not used by `makeInitialiser` as it's assumed that you are only using `ssl` in `production` and you won't be trying to create your database from within your code when in `production`. A future release may address that however.\n\n## Development\n\n### Branches\n\n\u003c!-- prettier-ignore --\u003e\n| Branch | Status | Coverage | Audit | Notes |\n| ------ | ------ | -------- | ----- | ----- |\n| `develop` | [![CircleCI](https://circleci.com/gh/davesag/sequelize-pg-utilities/tree/develop.svg?style=svg)](https://circleci.com/gh/davesag/sequelize-pg-utilities/tree/develop) | [![codecov](https://codecov.io/gh/davesag/sequelize-pg-utilities/branch/develop/graph/badge.svg)](https://codecov.io/gh/davesag/sequelize-pg-utilities) | [![Vulnerabilities](https://snyk.io/test/github/davesag/sequelize-pg-utilities/develop/badge.svg)](https://snyk.io/test/github/davesag/sequelize-pg-utilities/develop) | Work in progress |\n| `main` | [![CircleCI](https://circleci.com/gh/davesag/sequelize-pg-utilities/tree/main.svg?style=svg)](https://circleci.com/gh/davesag/sequelize-pg-utilities/tree/main) | [![codecov](https://codecov.io/gh/davesag/sequelize-pg-utilities/branch/main/graph/badge.svg)](https://codecov.io/gh/davesag/sequelize-pg-utilities) | [![Vulnerabilities](https://snyk.io/test/github/davesag/sequelize-pg-utilities/main/badge.svg)](https://snyk.io/test/github/davesag/sequelize-pg-utilities/main) | Latest stable release |\n\n### Development Prerequisites\n\n- [NodeJS](https://nodejs.org). I use [`nvm`](https://github.com/creationix/nvm) to manage Node versions — `brew install nvm`.\n\n### Test it\n\n- `npm test` — runs the unit tests.\n- `npm run test:unit:cov` — runs the unit tests with coverage reporting.\n\n### Lint it\n\n```sh\nnpm run lint\n```\n\n## Contributing\n\nPlease see the [contributing notes](CONTRIBUTING.md).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdavesag%2Fsequelize-pg-utilities","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdavesag%2Fsequelize-pg-utilities","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdavesag%2Fsequelize-pg-utilities/lists"}