lil/extras/mig.js

1import sqlite from "better-sqlite3"; 2import path from "path"; 3 4import dbDest from "../app/db.js"; 5import { makeId, makeToken } from "../app/utils.js"; 6 7// node extras/mig.js lil.old.db 8const dbSrcPath = process.argv[2] || "lil.old.db"; 9const _dbSrc = new sqlite(path.resolve(dbSrcPath), { fileMustExist: true }); 10const dbSrc = { 11 query: (sql, params) => { 12 return _dbSrc.prepare(sql).all(params); 13 }, 14}; 15 16function start() { 17 try { 18 const allUsers = dbSrc.query( 19 `SELECT id, username, status, createdAt FROM users`, 20 {} 21 ); 22 for (const user of allUsers) { 23 const urls = dbSrc.query( 24 `SELECT id, destination, short, status, createdAt FROM Urls WHERE status=@status AND UserId=@UserId`, 25 { 26 UserId: user.id, 27 status: "ACTIVE", 28 } 29 ); 30 // insert the user 31 let newUser = { 32 id: makeId(), 33 username: user.username, 34 api_token: makeToken(), 35 status: "active", 36 }; 37 dbDest.run( 38 `INSERT INTO users (id, username, api_token, status) 39 VALUES (@id, @username, @api_token, @status)`, 40 { ...newUser } 41 ); 42 // insert the url 43 for (const url of urls) { 44 let newUrl = { 45 id: makeId(), 46 destination: url.destination, 47 short: url.short || makeId(), 48 user: newUser.id, 49 }; 50 dbDest.run( 51 `INSERT INTO urls (id, destination, short, user) VALUES (@id, @destination, @short, @user);`, 52 { ...newUrl } 53 ); 54 } 55 } 56 } catch (error) { 57 console.error(error); 58 } 59} 60 61start();