mysql-upsert

0.0.3 • Public • Published

mysql-upsert

Upsert (insert or update) multiple rows into MySQL

Upsert

Upsert = An operation that inserts rows into a database table if they do not already exist, or updates them if they do.

Install

npm install mysql-upsert --save

Usage

Basic usage is:

  const upsert = require('mysql-upsert')
  upsert(mysqlConnection)(table, data, fields)
  • mysqlConnection is a mysql connection that has a query function that returns a Promise.
  • table is a the table name to upsert into
  • data is an array of objects. Each object is a row to insert
  • fields is an array of fields to upsert. (optional, defaults to the keys of the first object in data)

Following examples use async/await syntax but can be used with regular Promise syntax.

  const mysql = require('promise-mysql')
  const upsert = require('mysql-upsert')
 
  const table = 'users'
  const data = [
   { id: 1, name: 'Steve', company: 'Apple' },
   { id: 2, name: 'Bill', company: 'Microsoft' }
  ]
 
  // With single connection
  const connection = await mysql.createConnection({ ...config })
  const { affectedRows } = await upsert(connection)(table, data)
  await connection.end()
 
  // Limit fields
  const { affectedRows } = await upsert(connection)(table, data, ['name', 'company'])
 
  // With pools
  const pool = mysql.createPool({ ...config })
  const { affectedRows } = await upsert(pool)(table, data, ['name', 'company'])  
 
  // With single connection from pool
  const connection = await pool.getConnection()
  const { affectedRows } = await upsert(connection)(table, data)
  await connection.release()

Who made this?

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 0.0.3
    12
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 0.0.3
    12
  • 0.0.2
    0
  • 0.0.1
    0

Package Sidebar

Install

npm i mysql-upsert

Weekly Downloads

12

Version

0.0.3

License

MIT

Last publish

Collaborators

  • berzniz