diff --git a/src/91indexeddb.js b/src/91indexeddb.js index efb3b97e41..844e6d66b1 100755 --- a/src/91indexeddb.js +++ b/src/91indexeddb.js @@ -350,6 +350,25 @@ IDB.intoTable = function (databaseid, tableid, value, columns, cb) { var ixdb = request.result; var tx = ixdb.transaction([tableid], 'readwrite'); var tb = tx.objectStore(tableid); + // Apply AUTOINCREMENT / IDENTITY values before inserting (only when table has identity columns) + if (table && table.identities && Object.keys(table.identities).length > 0) { + for (var columnid in table.identities) { + var ident = table.identities[columnid]; + for (var i = 0; i < value.length; i++) { + var userProvided = + typeof value[i][columnid] !== 'undefined' && value[i][columnid] !== null; + if (!userProvided) { + value[i][columnid] = ident.value; + } + // Advance counter: if the inserted value is >= current, sync counter past it + if (userProvided && +value[i][columnid] >= ident.value) { + ident.value = +value[i][columnid] + ident.step; + } else { + ident.value += ident.step; + } + } + } + } for (var i = 0, ilen = value.length; i < ilen; i++) { tb.add(value[i]); } diff --git a/test/test861.js b/test/test861.js new file mode 100644 index 0000000000..0177d18c99 --- /dev/null +++ b/test/test861.js @@ -0,0 +1,58 @@ +if (typeof exports === 'object') { + var assert = require('assert'); + var alasql = require('..'); +} else { + __dirname = '.'; +} + +// IndexedDB tests only run in a browser environment +if (typeof exports != 'object') { + describe('Test 861 - AUTOINCREMENT for IndexedDB', function () { + it('1. AUTOINCREMENT column should be populated on INSERT', async () => { + const sql = alasql.promise; + + await sql(` + CREATE INDEXEDDB DATABASE IF NOT EXISTS test861; + ATTACH INDEXEDDB DATABASE test861; + USE test861; + DROP TABLE IF EXISTS autoinctab; + CREATE TABLE IF NOT EXISTS autoinctab (aid INT AUTOINCREMENT, aname STRING); + `); + + await sql('INSERT INTO autoinctab (aname) VALUES ("bar1"),("bar2")'); + + const res = await sql('SELECT * FROM autoinctab'); + + assert.deepStrictEqual(res, [ + {aid: 1, aname: 'bar1'}, + {aid: 2, aname: 'bar2'}, + ]); + + await sql('DROP INDEXEDDB DATABASE test861'); + }); + + it('2. AUTOINCREMENT continues incrementing across multiple INSERTs', async () => { + const sql = alasql.promise; + + await sql(` + CREATE INDEXEDDB DATABASE IF NOT EXISTS test861b; + ATTACH INDEXEDDB DATABASE test861b; + USE test861b; + DROP TABLE IF EXISTS autoinctab2; + CREATE TABLE IF NOT EXISTS autoinctab2 (aid INT AUTOINCREMENT, aname STRING); + `); + + await sql('INSERT INTO autoinctab2 (aname) VALUES ("row1")'); + await sql('INSERT INTO autoinctab2 (aname) VALUES ("row2")'); + + const res = await sql('SELECT * FROM autoinctab2'); + + assert.deepStrictEqual(res, [ + {aid: 1, aname: 'row1'}, + {aid: 2, aname: 'row2'}, + ]); + + await sql('DROP INDEXEDDB DATABASE test861b'); + }); + }); +}