2021-01-01 19:42:19 +02:00
|
|
|
const identity = require('lodash/identity');
|
|
|
|
const chunk = require('lodash/chunk');
|
|
|
|
|
2021-01-03 04:10:26 +02:00
|
|
|
function insertChunked(trx, chunkSize, target, iterator, existingData) {
|
|
|
|
const result = [];
|
2021-01-01 19:42:19 +02:00
|
|
|
iterator = iterator || identity;
|
2021-01-03 04:10:26 +02:00
|
|
|
const chunked = chunk(existingData, chunkSize);
|
2021-01-01 19:42:19 +02:00
|
|
|
for (const batch of chunked) {
|
2021-01-03 04:10:26 +02:00
|
|
|
result.push(
|
|
|
|
trx.queryBuilder().table(target).insert(batch.map(iterator)).toQuery()
|
|
|
|
);
|
2021-01-01 19:42:19 +02:00
|
|
|
}
|
2021-01-03 04:10:26 +02:00
|
|
|
return result;
|
2021-01-01 19:42:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function createTempTable(createTable, tablename, alteredName) {
|
|
|
|
return createTable.sql.replace(tablename, alteredName);
|
|
|
|
}
|
|
|
|
|
2021-01-03 04:10:26 +02:00
|
|
|
// ToDo To be removed
|
2021-01-01 19:42:19 +02:00
|
|
|
async function copyData(trx, tableName, alteredName) {
|
2021-01-03 04:10:26 +02:00
|
|
|
const existingData = await trx.raw(`SELECT * FROM "${tableName}"`);
|
|
|
|
return insertChunked(trx, 20, alteredName, identity, existingData);
|
|
|
|
}
|
|
|
|
|
|
|
|
// ToDo To be removed
|
|
|
|
async function reinsertData(trx, iterator, tableName, alteredName) {
|
|
|
|
const existingData = await trx.raw(`SELECT * FROM "${alteredName}"`);
|
|
|
|
return insertChunked(trx, 20, tableName, iterator, existingData);
|
|
|
|
}
|
|
|
|
|
|
|
|
function copyAllData(sourceTable, targetTable) {
|
|
|
|
return `INSERT INTO ${targetTable} SELECT * FROM ${sourceTable};`;
|
2021-01-01 19:42:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function dropOriginal(tableName) {
|
|
|
|
return `DROP TABLE "${tableName}"`;
|
|
|
|
}
|
|
|
|
|
|
|
|
function dropTempTable(alteredName) {
|
|
|
|
return `DROP TABLE "${alteredName}"`;
|
|
|
|
}
|
|
|
|
|
|
|
|
function renameTable(tableName, alteredName) {
|
|
|
|
return `ALTER TABLE "${tableName}" RENAME TO "${alteredName}"`;
|
|
|
|
}
|
|
|
|
|
2021-01-01 20:35:54 +02:00
|
|
|
function getTableSql(tableName) {
|
|
|
|
return `SELECT name, sql FROM sqlite_master WHERE type="table" AND name="${tableName}"`;
|
|
|
|
}
|
|
|
|
|
2021-01-01 19:42:19 +02:00
|
|
|
module.exports = {
|
2021-01-03 04:10:26 +02:00
|
|
|
copyAllData,
|
2021-01-01 19:42:19 +02:00
|
|
|
copyData,
|
|
|
|
createTempTable,
|
|
|
|
dropOriginal,
|
|
|
|
dropTempTable,
|
|
|
|
reinsertData,
|
|
|
|
renameTable,
|
2021-01-01 20:35:54 +02:00
|
|
|
getTableSql,
|
2021-01-01 19:42:19 +02:00
|
|
|
};
|