insert into db script fixes

This commit is contained in:
2026-09-02 20:33:23 +02:00
parent 65fc04a4d8
commit 771e81f50b
+46 -39
View File
@@ -22,52 +22,59 @@ const lookup = {
tracks: 'tracks' tracks: 'tracks'
}; };
// Retrieve existing IDs from Stream const existingRow = db.prepare('SELECT * FROM Stream WHERE id = ?');
const existingIds = db
.prepare('SELECT id FROM Stream')
.all()
.map((row) => row.id);
// Create a set of existing IDs for efficient lookup
const idSet = new Set(existingIds);
// Check if --overwrite flag is set // Overwrite differing streams without asking
const shouldOverwrite = process.argv.includes('--overwrite'); const shouldOverwrite = process.argv.includes('--overwrite');
// Process JSON files and insert data into Stream // Process JSON files and insert data into Stream
fs.readdir(jsonFolder, (err, files) => { const files = fs.readdirSync(jsonFolder);
if (err) throw err; console.log(`Found ${files.length} JSON file(s) in ${jsonFolder}.`);
console.log(`Found ${files.length} JSON file(s) in ${jsonFolder}.`);
files.forEach((file) => { for (const file of files) {
if (!file.endsWith('.json')) return; if (!file.endsWith('.json')) continue;
if (file.endsWith('.sideload.json')) return; if (file.endsWith('.sideload.json')) continue;
const jsonString = fs.readFileSync(path.join(jsonFolder, file), 'utf8'); const jsonString = fs.readFileSync(path.join(jsonFolder, file), 'utf8');
let jsonData = JSON.parse(jsonString); let jsonData = JSON.parse(jsonString);
const sideloadPath = path.join(jsonFolder, file.slice(0, -5) + '.sideload.json'); const sideloadPath = path.join(jsonFolder, file.slice(0, -5) + '.sideload.json');
if (fs.existsSync(sideloadPath, 'utf8')) { if (fs.existsSync(sideloadPath)) {
const sideloadData = JSON.parse(fs.readFileSync(sideloadPath)); const sideloadData = JSON.parse(fs.readFileSync(sideloadPath));
jsonData = { ...jsonData, ...sideloadData }; jsonData = { ...jsonData, ...sideloadData };
} }
// Skip if ID already exists in Stream
if (idSet.has(jsonData.id)) { // A key with no column would otherwise reach the query as `undefined`
if (!shouldOverwrite) { const unknown = Object.keys(jsonData).filter((key) => !(key in lookup));
console.log(`Skipped data for ID ${jsonData.id} (already exists).`); if (unknown.length > 0)
return; console.log(`Ignored unknown key(s) in ${file}: ${unknown.join(', ')}.`);
}
console.log(`Overwriting data for ID ${jsonData.id}.`); // Prepare attributes for insertion
const fields = Object.entries(jsonData)
.filter(([key]) => key in lookup)
// Serialize value if array
.map(([key, value]) => [lookup[key], Array.isArray(value) ? JSON.stringify(value) : value]);
const row = existingRow.get(jsonData.id);
if (row) {
const changed = fields
.filter(([column, value]) => String(row[column] ?? '') !== String(value ?? ''))
.map(([column]) => column);
if (changed.length === 0) {
console.log(`Unchanged data for ID ${jsonData.id}.`);
continue;
} }
// Prepare attributes for insertion console.log(`ID ${jsonData.id} differs from the database in: ${changed.join(', ')}.`);
const values = Object.keys(jsonData).map( if (!shouldOverwrite && !confirm(`Overwrite ID ${jsonData.id}?`)) {
// Serialize value if array console.log(`Kept database version of ID ${jsonData.id}.`);
(key) => (Array.isArray(jsonData[key]) ? JSON.stringify(jsonData[key]) : jsonData[key]) continue;
); }
const columns = Object.keys(jsonData).map((key) => lookup[key]); }
const sql = `INSERT OR REPLACE INTO Stream (${columns.join(', ')}) VALUES (${columns.map(() => '?').join(', ')})`; const columns = fields.map(([column]) => column);
db.prepare(sql).run(...values); const sql = `INSERT OR REPLACE INTO Stream (${columns.join(', ')}) VALUES (${columns.map(() => '?').join(', ')})`;
console.log(`Inserted data for ID ${jsonData.id}.`); db.prepare(sql).run(...fields.map(([, value]) => value));
}); console.log(`Inserted data for ID ${jsonData.id}.`);
}); }