Skip to content

Official UPSERT support with sqlite 3.24.0 (2018-06-04) #9629

Closed

Description

@aguynamedben

Thanks for the time you put into making sequelize great!

What are you doing?

sqlite 3.24.0 (2018-06-04) added Postgres-like UPSERT support last month. https://sqlite.org/lang_UPSERT.html

The Sequelize docs say the Model.upsert for sqlite is implemented as 2 queries

SQLite - Implemented as two queries INSERT; UPDATE. This means that the update is executed regardless of whether the row already existed or not
From http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-upsert

What do you expect to happen?

It would be nice if Sequelize used sqlite's UPSERT. I presume it would be better for performance, and I'm doing a lot of UPSERTS. Maybe Sequelize could automatically detect the sqlite version and use UPSERT if the version is 3.24.0 or higher.

What is actually happening?

UPSERTs work fine, but seem slow-ish. I haven't done any sophisticated benchmarking, though.

Dialect: sqlite
Dialect version: 3.24.0 (2018-06-04)
Database version: 3.24.0 (2018-06-04)
Sequelize version: 4.38.0
Tested with latest release: Yes

Activity

  1. changed the title [-]UPSERT support on sqlite 3.24.0 (2018-06-04)[/-] [+]Official UPSERT support on sqlite 3.24.0 (2018-06-04)[/+] on Jul 4, 2018
  2. changed the title [-]Official UPSERT support on sqlite 3.24.0 (2018-06-04)[/-] [+]Official UPSERT support with sqlite 3.24.0 (2018-06-04)[/+] on Jul 4, 2018
  3. added
    type: feature
    dialect: sqlite
    on Jul 4, 2018
  4. aguynamedben commented on Jul 4, 2018

    @aguynamedben
    Author

    Note that sqlite UPSERT also apparently supports multi-row INSERTs.

    If the insert operation would cause the uniqueness constraint identified by the conflict-target clause to fail, then the insert is omitted and either the DO NOTHING or DO UPDATE operation is performed instead. In the case of a multi-row insert, this decision is made separately for each row of the insert.

    My use case: I have 5,000 potentially updated records I've re-downloaded from an API and I want to UPSERT them into a local sqlite database all at once (or say, in batches of 1,000) instead of one at a time. Multi-row UPSERTs could be supported by the Model.bulkCreate API (the options.updateOnDuplicate option).

  5. aguynamedben commented on Jul 4, 2018

    @aguynamedben
    Author

    Here's a helper function that builds a SQLite UPSERT query using sequelize.escape(). Anecdotally, SQLite UPSERT seems insanely fast compared to the current implementation in this library (INSERT+UPDATE a single record at at time for SQLite). I'm performing UPSERTs in 100 record batches for several thousand records, and it's at least a few orders of magnitude faster. Very promising!

    /**
     * Build a SQLite UPSERT query using sequelize.escape()
     * https://sqlite.org/lang_UPSERT.html
     * This syntax became available in SQLite 3.24.0 (2018-06-04)
     * @author Ben Standefer
     *
     * @param {string} tableName - The table to insert the records into. This table
     * should have createdAt and updatedAt columns you wish to be automatically updated.
     * @param {string[]} columns - The columns (from the records param) to insert.
     * Do not include createdAt or updatedAt.
     * @param {Object[]} records - The objects to insert. Columns not listen in the
     * columns param will be ignored. Do not include createdAt or updatedAt, those
     * values are automatically generated.
     * @param {string[]} conflictTargets - The conflict targets that cause the
     * insert to become an update.
     *
     * @example
     * const tableName = 'phonebook';
     * const columns = ['name', 'phonenumber'];
     * const records = [{ name: 'Alice', phonenumber: '704-555-1212' }];
     * const conflictTargets = ['name'];
     * const sql = buildUpsertQuery(tableName, columns, records, conflictTargets);
     * // returns `INSERT INTO phonebook (name,phonenumber,createdAt,updatedAt) VALUES ('Alice','704-555-1212',datetime('now'),datetime('now')) ON CONFLICT(name) DO UPDATE SET phonenumber=excluded.phonenumber,updatedAt=excluded.updatedAt;`
     * await sequelize.query(sql, { type: sequelize.QueryTypes.INSERT });
     */
    function buildUpsertQuery(tableName, columns, records, conflictTargets) {
      const columnsSql = columns
        .concat(['createdAt', 'updatedAt'])
        .join(',');
    
      // Convert the records to a SQL values string
      // ('record1column1value','record1colum2value'),('record2column1value','record2column2value')
      // Append `datetime('now')` as last 2 values to set createdAt and updatedAt
      const valuesSql = records.map(record => (
        columns
          .map(column => sequelize.escape(record[column]))
          .concat([`datetime('now')`, `datetime('now')`])
          .join(',')
      ))
        .map(recordValuesString => `(${recordValuesString})`)
        .join(',');
    
      const conflictSql = conflictTargets.join(',');
    
      // Exclude conflictTargets from the set
      // Update updatedAt, leave createdAt at it's original value (record already
      // exists)
      const setSql = columns
        .filter(column => !conflictTargets.includes(column))
        .map(column => `${column}=excluded.${column}`)
        .concat(['updatedAt=excluded.updatedAt'])
        .join(',');
    
      const sql = [
        `INSERT INTO ${tableName} (${columnsSql}) VALUES ${valuesSql} `,
        `ON CONFLICT(${conflictSql}) DO UPDATE SET ${setSql};`,
      ].join('');
    
      return sql;
    }
  6. lracicot commented on Jul 26, 2019

    @lracicot

    This is not an issue, this is a feature request and an important one.

  7. deleted a comment from stale on Jul 26, 2019
  8. aguynamedben commented on Jul 26, 2019

    @aguynamedben
    Author

    +1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    dialect: sqlitetype: feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions