import getfiles from "https://deno.land/x/getfiles@v1.0.0/mod.ts"; import postgres from "https://deno.land/x/postgresjs@v3.4.4/mod.js"; import { parse } from "https://deno.land/std/csv/mod.ts"; const seedDir = "./db/seeds/"; export default async function (args: string[]) { const sql = postgres({ debug: (_, query) => console.log("Running query", query), }); const files = getfiles(seedDir).filter((x) => x.name?.endsWith(".sql") || x.name?.endsWith(".ts") || x.name?.endsWith(".csv") ); for (const file of files) { if ( args.length <= 0 || args.includes( file.name?.replace(/^.*?\/(.*?)\.(?:sql|ts|csv)$/g, "$1"), ) ) { // identified a seed we are supposed to run if (file.name?.endsWith(".csv")) { const tables = Deno.readTextFileSync(file.realPath).split(/\r?\n\r?\n/); for (const table of tables) { const [table_name, ...table_data] = table.split(/\r?\n/); const parsedData = parse(table_data.join("\r\n"), { skipFirstRow: true, separator: ",", lazyQuotes: true, }); await sql`TRUNCATE TABLE ${table_name}`; await parsedData.reduce(async (accP, row) => { const cols = Object.keys(row).join(", "); await accP; return await sql`INSERT INTO ${sql(table_name)} ${ sql(row, ...cols) }`; }, Promise.resolve([])); } } else if (file.name?.endsWith(".sql")) { console.log("Seeding ", file.name.replace(/\.sql$/, "")); const commands = Deno.readTextFileSync(file.realPath).split(/;/); for (const command of commands) { if (!command.trim()) continue; const cmd = command; await sql.unsafe(cmd); } } else if (file.name?.endsWith(".ts")) { const mod = await import(file.realPath); await mod(sql); } else { throw new Error("Unable to identify seed type: " + file.name); } } } }