# database() function · @imqueue/pg-sequelize

Source: https://imqueue.org/api/pg-sequelize/latest/pg-sequelize.database/
Published: 2026-08-01
Author: @imqueue maintainers (https://github.com/imqueue)
Package: @imqueue/pg-sequelize 4.2.0 — generated reference, not hand-written

Connects to the database, loads the models, and returns the Sequelize instance.

**Signature:**

```typescript
export declare function database(options?: IMQORMOptions): Sequelize;
```

## Parameters


| Parameter | Type | Description |
| --- | --- | --- |
| options | [IMQORMOptions](https://imqueue.org/api/pg-sequelize/latest/pg-sequelize.imqormoptions/) | _(Optional)_ Required on the first call, ignored on every later one. |


**Returns:**

[Sequelize](https://imqueue.org/api/pg-sequelize/latest/pg-sequelize.sequelize/)

The single Sequelize instance for this process, with models registered.

## Exceptions

TypeError when the first call has no options, or when no connection string can be resolved from either the options or the environment.

## Remarks

A process-wide singleton. The first call does all the work; every call after it returns the cached instance and DOES NOT LOOK AT ITS ARGUMENT — so passing a different config later is silently ignored rather than reconnecting. That is why services can import `database` anywhere and call `database(dbConfig)` freely, and also why there is no way to swap the connection once it is up.

The first call resolves its configuration in this order:

- `connectionString`, or [DB\_CONN\_STR](https://imqueue.org/api/pg-sequelize/latest/pg-sequelize.db_conn_str/) from the environment. Neither throws. - `logger`, or the `@imqueue/rpc` service default, or `console`. - `sequelize.logging`: left alone if explicitly falsy, so `false` disables logging; otherwise replaced with this package's formatter, honouring [SQL\_PRETTIFY](https://imqueue.org/api/pg-sequelize/latest/pg-sequelize.sql_prettify/) and [SQL\_COLORIZE](https://imqueue.org/api/pg-sequelize/latest/pg-sequelize.sql_colorize/). A function you supply is wrapped rather than discarded, and receives the formatted SQL.

Models are then discovered by walking `modelsPath` for compiled `.js` files and taking the export whose name matches the filename — see [IMQORMOptions.modelsPath](https://imqueue.org/api/pg-sequelize/latest/pg-sequelize.imqormoptions.modelspath/), since a mismatch there fails in a way the error does not explain. The require is synchronous and CommonJS-scoped, which is what makes the models loadable from an ESM package.

## Example


```typescript
// config.ts — built once at start-up
export const dbConfig: IMQORMOptions = {
    logger,
    connectionString: process.env.DB_CONN_STR || '',
    sequelize: toSequelizeConfig(process.env.DB_CONN_STR, process.env.DB_DIALECT),
    modelsPath: './src/orm/models',
};

// anywhere in the service — the first call wins, the rest are free
const orm = database(dbConfig);
```

