{"id":21640456,"url":"https://github.com/alallier/db-access-utils","last_synced_at":"2026-04-13T05:38:31.682Z","repository":{"id":198012889,"uuid":"699958644","full_name":"alallier/db-access-utils","owner":"alallier","description":"A library that allows Node.js applications to setup database connections, data access, and persistence operations quickly and easily.","archived":false,"fork":false,"pushed_at":"2023-10-03T19:27:37.000Z","size":15,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-01-25T03:38:15.436Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/alallier.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2023-10-03T17:07:38.000Z","updated_at":"2023-10-03T19:27:40.000Z","dependencies_parsed_at":null,"dependency_job_id":"11f5dd5b-241c-4c78-9f43-fcf6be8f1111","html_url":"https://github.com/alallier/db-access-utils","commit_stats":null,"previous_names":["alallier/db-access-utils"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alallier%2Fdb-access-utils","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alallier%2Fdb-access-utils/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alallier%2Fdb-access-utils/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alallier%2Fdb-access-utils/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alallier","download_url":"https://codeload.github.com/alallier/db-access-utils/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244352080,"owners_count":20439309,"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":[],"created_at":"2024-11-25T04:18:42.074Z","updated_at":"2025-12-31T00:12:28.991Z","avatar_url":"https://github.com/alallier.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Database Access Utility Library\n\nA library that allows Node.js applications to setup database connection, data access and persistence operations quickly and easily.\n\n## Installation\nInstall this dependency in your Node.js application using the NPM command:\n\n```\nnpm i db-access-utils\n```\n\n## Usage\n\nThe following sections outline various use cases for performing data access using this library, starting with the most basic usage to get you up and running.\n\n### Basic usage\n\nStart by creating a `DBConfig` object using the configuration JS class for the database vendor you intend on using. For example, if you are using a PostgreSQL database, instantiate a `PostgresDBConfig` instance.\n\n**Instantiate a configuration object for PostgreSQL databases**\n```js\nconst { PostgresDBConfig } = require('db-access-utils')\n\nconst options = {\n  maxClients: 5,\n  idleTimeoutMillis: 10000,\n  connectionTimeoutMillis: 10000\n}\nconst dbConfig = new PostgresDBConfig(hostname,\n  port,\n  database,\n  username,\n  password,\n  options)\n```\n\nUsing the configuration object, instantiate a `DB` object for the database vendor you are using and start the connection using the `DB.connect` function. For example, if you are using PostgreSQL, instantiate a `PostgresDB` instance. This DB type object will be used for low-level connection management and data access operations. Each subtype of the `DB` class, corresponding to a different database vendor, will **implement the same interface**.\n\n**Instantiate and connect a DB object for PostgreSQL databases**\n```js\nconst { PostgresDB } = require('db-access-utils')\n\nconst db = new PostgresDB(dbConfig)\ntry {\n  await db.connect()\n} catch (e) {\n  console.log('Unable to connect to postgres')\n}\n```\n\nExecute a query statement using the `DB.query` function. This function takes two arguments:\n\n  1. Statement - A query statement string\n  2. Options - An optional options object with the following properties:\n      - `parameters` - An array of query parameters (Optional)\n\n**Execute a query**\n```js\n// Basic query statement without parameters\nconst statement1 = 'SELECT * FROM students'\ntry {\n  let dbResult = await db.query(statement1)\n} catch (e) {\n  console.log('An error has occurred attempting to execute the query')\n}\n\n// Query with parameters\nconst statement2 = 'SELECT * FROM departments WHERE name=$1'\nconst parameters = [ 'CS' ]\ntry {\n  let dbResult = await db.query(statement2, { parameters })\n} catch (e) {\n  console.log('An error has occurred attempting to execute the query')\n}\n```\n\nOnce you're finished using the `DB` object, such as during application teardown, disconnect from the database using the `DB.disconnect` function.\n\n**Disconnect from the database**\n```js\ntry {\n  await db.disconnect()\n} catch (e) {\n  console.log('An error occurred while disconnecting from the database')\n}\n```\n\n### ES Module Loading\n\nYou may also import the library's named exports as ECMAScript modules. The project includes a wrapper around the exports so that you can import modules using ES Module loading and ESM `import` statements.\n\n```js\nimport { PostgresDB, DBOperation } from 'db-access-utils'\n```\n\n### Query operations\nThe `DB` classes allow you to execute an operation instead of a simple query statement. This operation allows you to specify:\n\n  - The query statement string\n  - The query parameters (Optional)\n  - A data marshaller function to marshall the raw `DBResult` into the appropriate type (Optional)\n\nThis may be useful if you're designing a higher level DAO abstraction on top of the low-level data access this library provides. Use the `DBOperation` type along with `DB.operation` to perform operations.\n\n**Performing a database operation**\n```js\nconst { DBOperation } = require('db-access-utils')\n\nconst statement = 'SELECT * FROM professors WHERE lastname=$1'\nconst professorMarshallerFn = dbResult =\u003e {\n  return dbResult.rows.map(row =\u003e {\n    return {\n      firstName: row.firstname,\n      lastName: row.lastname,\n      departmentId: row.department_id\n      dateOfBirth: row.date_of_birth,\n    }\n  })\nconst getProfessorByLastName = new DBOperation(statement,\n{\n  marshaller: professorMarshallerFn\n})\n\ntry {\n  const professors = await db.operation(getProfessorByLastName,\n  {\n    parameters: [ 'Smith' ]\n  })\n} catch (e) {\n  console.log('An error has occurred attempting to execute the query')\n}\n```\n\nIf a marshaller function is provided, the function will receive the raw `DBResult` object normally returned from a query execution, and execute the function to return an array of marshalled results (Returns an `Array\u003c*\u003e` type).\n\nIf the optional options object is provided to the `DB.operation` function call that defines `parameters`, the `DBOperation.parameters` will be overriden in the database operation execution. This allows you to defer knowing the operation parameters until you're ready to execute the operation (Useful for defining operations ahead of time when parameters aren't known until runtime).\n\n### Transactions\nThe `DB.transaction` function allows you to perform a sequential list of database operations in a single unit of work. In the case that any of the operations fail, the previous operations will be rolled back.\n\nTo perform a transaction, create a `DBOperation` for each operation in the transaction, and execute the transaction using the `DB.transaction` function with all operations in an ordered Array of objects containing each operation and any parameters.\n\n**Performing a database transaction**\n```js\nconst { DBOperation } = require('db-access-utils')\n\nconst op1 = new DBOperation('INSERT INTO buildings VALUES ( $1, $2 )')\nconst op2 = new DBOperation('INSERT INTO departments VALUES ($1, $2 )')\n\nconst operations = [\n  {\n    operation: op1,\n    parameters: [ '103', 'New Athletic Center' ]\n  },\n  {\n    operation: op2,\n    parameters: [ 'PE', '103' ]\n  }\n]\n\ntry {\n  const dbResults = await db.transaction(operations)\n} catch (e) {\n  console.log('An error occurred while performing a transaction. Transaction rolled back')\n}\n```\n\n### Using the DBFactory module\nInstead of explicitly creating the `DB` subtype, you may use the `DBFactory` module to create the appropriate `DB` instance by providing it a database configuration object. The configuration object should be a flat object defining the properties for the database's `DBConfig`, as well as define a `vendor` field with the appropriate vendor name.\n\nThe `DBFactory.createDB` method will inspect the database configuration object, determine which `DB` subtype to instantiate, and return it. This method determines the `DB` subtype using the `config.vendor` property, and marshalling the `config` properties into the appropriate `DBConfig` for that vendor's `DB` subclass. The supported vendors are:\n\n- \"postgres\" - PostgreSQL database\n\nThis is useful if your application can't anticipate the correct `DB` subclass to use until runtime loading a configuration.\n\n**Using DBFactory to create a DB instance**\n```js\nconst { DBFactory } = require('db-access-utils')\nconst config = require('./path/to/db/config') // Imported object defines a config.vendor field\n\ntry {\n  const db = DBFactory.createDB(config)\n} catch (e) {\n  console.log('Failed to instantiate DB using the DBFactory')\n}\n```\n\n## API\nLibrary API\n\n### PostgresDBConfig\nConfiguration object for `PostgresDB` instances.\n\n#### Constructor\n\n```\nnew PostgresDBConfig(\u003cstring\u003ehostname, \u003cnumber\u003eport, \u003cstring\u003edatabase, \u003cstring\u003eusername, \u003cstring\u003epassword, \u003cObject\u003eopts)\n```\n\nThe `opts` argument is an object with the following properties:\n  - `maxClients`: (number) Maximum number of clients in the connection pool. Optional, defaults to 10.\n  - `idleTimeoutMillis`: (number) Milliseconds a client in the pool will sit idle before being disconnected. Setting this to 0 disables the auto-disconnect feature. Optional, defaults to 10000.\n  - `connectionTimeoutMillis`: (number) Milliseconds before timing out a connected client. Setting this to 0 disables the auto-timeout feature. Optional, defaults to 0.\n\n### PostgresDB\nPostgreSQL database access object.\n\n#### Constructor\n\n```\nnew PostgresDB(\u003cPostgresDBConfig\u003econfig)\n```\n\n#### DB.connect\n\n```\ndb.connect() : Promise\u003cvoid\u003e throws DBConnectionError\n```\n\nConnects to the database. Applies to all subtypes of `DB`, such as `PostgresDB`.\n\n#### DB.disconnect\n\n```\ndb.disconnect() : Promise\u003cvoid\u003e throws Error\n```\n\nDisconnects from the database. Applies to all subtypes of `DB`, such as `PostgresDB`.\n\n#### DB.query\n\n```\ndb.query(\u003cstring\u003estatement[, opts: [\u003cArray\u003c*\u003e\u003eparameters]]) : Promise\u003cDBResult\u003e throws DBConnectionError, QueryExecutionError\n```\n\nExecutes a database query using the provided query statemeent.\n\nIf an `opts.parameters` array property is provided, executes the query with the query parameters.\n\nReturns a `DBResult` object.\n\nExecutes a database query. May take a plain text query statement, or a `DBOperation` object that defines the statement, optional parameters, and optional results marshaller function.\n\nIf a `DBOperation` object is provided that contains the query parameters, the query parameters provided to this function will be ignored.\n\nIf a plain text query or a `DBOperation` object without a marshaller function defined is used, a `DBResult` object is returned.\n\nIf a `DBOperation` is used and defines a marshaller function, the query function will return the Array of `*` returned from the marshaller function.\n\n#### DB.operation\n\n```\ndb.operation(\u003cDBOperation\u003eoperation[, opts: [\u003cArray\u003c*\u003e\u003eparameters]]) : Promise\u003cDBResult\u003e|Promise\u003cArray\u003c*\u003e\u003e throws DBConnectionError, QueryExecutionError, DBMarshallerError\n```\n\nExecutes a database operation with the provided `DBOperation` operation.\n\nReturns a `DBResult` if the operation does not define a data marshaller function, or an `Array\u003c*\u003e` if a data marshaller is provided.\n\nMay take a `opts.parameters` array if the caller wishes to override the operation's existing parameters.\n\n#### DB.transaction\n\n```\ndb.transaction(Array\u003cDBOperation\u003eoperations[, opts: [\u003cArray\u003cArray\u003c*\u003e\u003e\u003eparameters]]) : Promise\u003cArray\u003cDBResult\u003e\u003e|Promise\u003cArray\u003cArray\u003c*\u003e\u003e\u003e throws DBConnectionError, QueryExecutionError, DBResultMarshallerError\n```\n\nExecutes a ordered list of operations sequentially in a single database transaction/unit of work. Returns an ordered list of `DBResult` objects whose index corresponds to the provided operation.\n\nIf the `DBOperation` defines a marshaller function, the object in the results array at the index corresponding to the operation will be the return value from the data marshaller function instead.\n\nMay take an `opts.parameters` ordered array of query parameters if the caller wishes to override a operation's existing parameters. The array in the `opts.parameters` array will replace the operation's query parameters in the same index. For example, if `opts.parameters` is provided, the array of query parameters in index 1 of `opts.parameters` will replace the query parameters for the operation in index 1 of `operations`. A `null` in the `opts.parameters` array will skip query parameter overriding for that operation in the same index.\n\n### DBOperation\nDefines a database operation executed.\n\n#### Constructor\n\n```\nnew DBOperation(\u003cstring\u003estatement[, opts: [ \u003cArray\u003c*\u003e\u003eparameters[, \u003cFunction\u003emarshaller]]])\n```\n\nMay take an `opts` options object.\n\nThe `opts.parameters` may be an array of query parameters.\n\nThe `opts.marshaller` may be a function that executes on the database operation's returned `DBResult` object for marshalling the results into a particular list of objects instead.\n\nThe **marshaller** function has the following function signature, where the return type is the data marshalled by the function from the DBResult rows:\n\n```\nmarshallerFn(\u003cDBResult\u003edbResult) : Array\u003c*\u003e\n```\n\n### DBResult\nRepresents the raw results of a database query or transaction\n\n#### Constructor\n\n```\nnew DBResult([\u003cArray\u003cObject\u003e\u003erows[, \u003cnumber\u003erowCount[, \u003cArray\u003cObject\u003e\u003efields]]])\n```\n\n#### DBResult.setRows\n\n```\nDBResult.setRows(\u003cArray\u003cObject\u003e\u003erows) : void\n```\n\nSets the `DBResult.rows` property. Each row object represents a row returned from a database query/operation.\n\n#### DBResult.setRowCount\n\n```\nDBResult.setRows(\u003cnumber\u003erowCount) : void\n```\n\nSets the `DBResult.rowCount` property. The number of rows in the query result.\n\n#### DBResult.setFields\n\n```\nDBResult.setFields(\u003cArray\u003cObject\u003e\u003efields) : void\n```\n\nSets the `DBResult.fields` property. A list of 'field' objects containing metadata for each row object field.\n\nEach field object contains a `name` property that corresponds to a row object property name.\n\n### DBFactory\nObject that defines shortcut functions for creating a `DB` subtype.\n\n#### DBFactory.createDB\n\n```\nDBFactory.createDB(\u003cObject\u003econfig) : DB throws DBFactoryError\n```\n\nA factory method that creates an appropriate `DB` instance for the given configuration object. Used as an alternative to creating the `DBConfig` and `DB` subtype instances manually.\n\nInspects the provided `config` object to determine what subtype of `DB` to instantiate and return. The `config` object should define a `vendor` field with the appropriate vendor name, and all fields defined in the appropriate `DBConfig` subclass as a direct child property.\n\n### DBFactoryError\nAn error thrown when an error occurs creating a `DB` instance using the `DBFactory.createDB` method\n\n#### Constructor\n\n```\nnew DBFactoryError(\u003cstring\u003emessage, \u003cError\u003ecause)\n```\n\n#### DBFactoryError.cause\n\nThe thrown error that caused with error to throw.\n\n\n### DBConnectionError\nAn error thrown by a `DB` function when there is an error with the database connection.\n\n#### Constructor\n\n```\nnew DBConnectionError(\u003cstring\u003emessage, \u003cError\u003ecause)\n```\n\n#### DBConnectionError.cause\n\nThe thrown error that caused with error to throw.\n\n### QueryExecutionError\nAn error thrown when a database query or transaction fails to execute.\n\n#### Constructor\n\n```\nnew QueryExecutionError(\u003cstring\u003emessage, \u003cError\u003ecause)\n```\n\n#### QueryExecutionError.cause\n\nThe thrown error that caused with error to throw.\n\n### DBResultMarshallerError\nAn error thrown when an error occurs in a database operation's results marshaller function.\n\n#### Constructor\n\n```\nnew DBResultMarshallerError(\u003cstring\u003emessage, \u003cError\u003ecause)\n```\n\n#### DBResultMarshallerError.cause\n\nThe thrown error that caused with error to throw.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falallier%2Fdb-access-utils","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falallier%2Fdb-access-utils","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falallier%2Fdb-access-utils/lists"}