|
| 1 | +import fs from "node:fs/promises" |
| 2 | +import { existsSync } from "node:fs" |
| 3 | +import { createIfNot } from "./utils/fileUtils.mjs" |
| 4 | +import path from "node:path" |
| 5 | +async function writeSQL(statement, saveFileAs = "") { |
| 6 | + try { |
| 7 | + const destinationFile = process.argv[2] || saveFileAs |
| 8 | + if (!destinationFile) { |
| 9 | + throw new Error("Missing saveFileAs parameter") |
| 10 | + } |
| 11 | + createIfNot(path.resolve(`./sql/${destinationFile}`)) |
| 12 | + await fs.writeFile(`sql/${process.argv[2]}.sql`, statement) |
| 13 | + } catch (err) { |
| 14 | + console.log(err) |
| 15 | + } |
| 16 | +} |
| 17 | +async function readCSV(csvFileName = "") { |
| 18 | + try { |
| 19 | + const fileAndTableName = process.argv[2] || csvFileName |
| 20 | + if (!fileAndTableName) { |
| 21 | + throw new Error("Missing csvFileName parameter") |
| 22 | + } |
| 23 | + if (!existsSync(path.resolve(`./csv/${fileAndTableName}.csv`))) { |
| 24 | + console.log("file not found") |
| 25 | + return |
| 26 | + } |
| 27 | + const data = await fs.readFile(`csv/${fileAndTableName}.csv`, { |
| 28 | + encoding: "utf8", |
| 29 | + }) |
| 30 | + const linesArray = data.split(/\r|\n/).filter(line => line) |
| 31 | + const columnNames = linesArray.shift().split(",") |
| 32 | + let beginSQLInsert = `INSERT INTO ${fileAndTableName} (` |
| 33 | + columnNames.forEach(name => (beginSQLInsert += `${name}, `)) |
| 34 | + beginSQLInsert = beginSQLInsert.slice(0, -2) + ")\nVALUES\n" |
| 35 | + let values = "" |
| 36 | + linesArray.forEach(line => { |
| 37 | + // Parses each line of CSV into field values array |
| 38 | + const arr = line.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/) |
| 39 | + if (arr.length > columnNames.length) { |
| 40 | + console.log(arr) |
| 41 | + throw new Error("Too Many Values in row") |
| 42 | + } else if (arr.length < columnNames.length) { |
| 43 | + console.log(arr) |
| 44 | + throw new Error("Too Few Values in row") |
| 45 | + } |
| 46 | + let valueLine = "\t(" |
| 47 | + arr.forEach(value => { |
| 48 | + // Matches NULL values, Numbers, |
| 49 | + // Strings accepted as numbers, and Booleans (0 or 1) |
| 50 | + if (value === "NULL" || !isNaN(+value)) { |
| 51 | + valueLine += `${value}, ` |
| 52 | + } else { |
| 53 | + // If a string is wrapped in quotes, it doesn't need more |
| 54 | + if (value.at(0) === '"') valueLine += `${value}, ` |
| 55 | + else { |
| 56 | + // This wraps strings in quotes |
| 57 | + // also wraps timestamps |
| 58 | + valueLine += `"${value}", ` |
| 59 | + } |
| 60 | + } |
| 61 | + }) |
| 62 | + valueLine = valueLine.slice(0, -2) + "),\n" |
| 63 | + values += valueLine |
| 64 | + }) |
| 65 | + values = values.slice(0, -2) + ";" |
| 66 | + const sqlStatement = beginSQLInsert + values |
| 67 | + // Write File |
| 68 | + writeSQL(sqlStatement) |
| 69 | + } catch (err) { |
| 70 | + console.log(err) |
| 71 | + } |
| 72 | +} |
| 73 | +readCSV() |
| 74 | +console.log("Finished!") |
0 commit comments