npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@fujitsusweden/mssql-handler

v0.2.0

Published

Library for interacting with MS SQL Server

Downloads

10

Readme

mssql-handler

What is it

A library for interacting with MS SQL Server, implemented as a convenience wrapper around mssql.

How to use it

This module provides no classes. You don't need to keep track of connection pools or instances. Just call the module functions directly with what you need. Connection pools are created and cached behind the scenes.

mssqlHandler.init({ log })

Initialize the module. Example:

const mssqlHandler = require("@fujitsusweden/mssql-handler");
mssqlHandler.init({ log });

The log is an object holding the following log functions: debug, info, warn, error and critical. Each log function should be an async function taking arguments data and req.

mssqlHandler.beforeExit()

Close all connection pools.

In scripts that should terminate, call await mssqlHandler.beforeExit() at the end. Otherwise, asynchronous background jobs can prevent the process from terminating indefinitely.

mssqlHandler.runDbQuery({ config, query, types, params, req })

Execute an SQL query and return its result. Example:

const results = await mssqlHandler.runDbQuery({
  config: config.db_sql,
  query: "SELECT * FROM people WHERE Name = @name;",
  params: { name: "Joe" },
  req,
});

Option details:

  • config: The SQL configuration to connect with.

  • query: The SQL query to execute. Use @ to denote parameters.

  • types: Optional. Probably never needed. A map from (some of) the parameter names to the name of their type. For the parameters present in types, this will override the library's attempt at figuring out a suitable type.

  • params: Optional. An object mapping parameter names to values.

  • req: The req object used for logging.

mssqlHandler.runDbQueryAG({ config, query, types, params, req })

Asynchronous generator variant of mssqlHandler.runDbQuery, with the same option details. Example:

for await (const record of mssqlHandler.runDbQueryAG({
  config: config.db_sql,
  query: "SELECT * FROM people WHERE Name = @name;",
  params: { name: "Joe" },
  req,
})) {
  console.log(record);
}

mssqlHandler.runFuncAsTransaction({ config, func, req, ...context })

Execute a function in the context of an SQL transaction. If the function throws any error, the transaction will be rolled back. Example:

async function transfer({ runDbQuery, fromAccount, toAccount, amount }) {
  await runDbQuery({
    query: `
      UPDATE accounts
      SET balance = balance - @amount
      WHERE holder = @fromAccount;`,
    params: { amount, fromAccount },
  });
  await runDbQuery({
    query: `
      UPDATE accounts
      SET balance = balance + @amount
      WHERE holder = @toAccount;`,
    params: { amount, toAccount },
  });
  const fromAccountAfterwards = await runDbQuery({
    query: `
      SELECT *
      FROM accounts
      WHERE holder = @fromAccount;`,
    params: { fromAccount },
  });
  // Rollback to prevent overdraft
  assert(0 <= fromAccountAfterwards[0].balance);
}

await mssqlHandler.runFuncAsTransaction({
  config: config.db_sql,
  func: transfer,
  req,
  fromAccount: "Alice",
  toAccount: "Bob",
  amount: 700,
});

Option details:

  • config: The SQL configuration to connect with.

  • func: The function to run within a transaction. It should be asynchronous and take a context argument, an object containing:

    • req

    • runDbQuery: Just like mssqlHandler.runDbQuery except it does not accept a config option and works within the transaction.

    • runDbQueryAG: Just like mssqlHandler.runDbQueryAG except it does not accept a config option and works within the transaction.

    • transaction: The native transaction object. You probably don't need that.

    • ...context: Any other options passed to mssqlHandler.runFuncAsTransaction.

  • req: The req object used for logging.

  • ...context: Optional. Any number of options you want to pass along to func.

mssqlHandler.escId(id)

Take the name of an identifier (for e.g. a table, column or index) and return it escaped, ready to be used in an SQL statement. It might be a good convention to use a q_ prefix for variables holding quoted identifiers. Example:

const tableName = "Table123";
const q_tableName = mssqlHandler.escId(tableName);
await mssqlHandler.runDbQuery({
  config,
  req,
  query: `UPDATE ${q_tableName} SET a = 0;`,
});

(There is no function for escaping values. Use the params option for that.)

mssqlHandler.unEscId(q_id)

The inverse of mssqlHandler.escId.

mssqlHandler.mssql

The mssql module, in case you need to by-pass the wrapper.

Development

Run ./script without arguments for help.