1- import { promises as fs } from "fs" ;
2-
1+ import { promises as fs , existsSync } from "fs" ;
2+ import { createIfNot } from "./utils/fileUtils"
3+ import * as path from "node:path"
34async function writeSQL ( statement : string , saveFileAs = "" ) {
45 try {
56 const destinationFile = process . argv [ 2 ] || saveFileAs ;
6-
77 if ( ! destinationFile ) {
88 throw new Error ( "Missing saveFileAs parameter" ) ;
99 }
10-
10+ createIfNot ( path . resolve ( `/sql/ ${ destinationFile } .sql` ) )
1111 await fs . writeFile ( `sql/${ process . argv [ 2 ] } .sql` , statement ) ;
1212 } catch ( err ) {
1313 console . log ( err ) ;
1414 }
1515}
16-
1716async function readCSV ( csvFileName = "" ) {
1817 try {
1918 const fileAndTableName = process . argv [ 2 ] || csvFileName ;
20-
2119 if ( ! fileAndTableName ) {
2220 throw new Error ( "Missing csvFileName parameter" ) ;
2321 }
24-
22+ if ( existsSync ( path . resolve ( `./csv/${ fileAndTableName } .csv` ) ) ) {
23+ console . log ( "file not found" )
24+ return
25+ }
2526 const data = await fs . readFile ( `csv/${ fileAndTableName } .csv` , {
2627 encoding : "utf8" ,
2728 } ) ;
28-
2929 const linesArray = data . split ( / \r | \n / ) . filter ( ( line ) => line ) ;
3030 const columnNames = linesArray ?. shift ( ) ?. split ( "," ) || [ ] ;
31-
3231 let beginSQLInsert = `INSERT INTO ${ fileAndTableName } (` ;
3332 columnNames . forEach ( ( name ) => ( beginSQLInsert += `${ name } , ` ) ) ;
3433 beginSQLInsert = beginSQLInsert . slice ( 0 , - 2 ) + ")\nVALUES\n" ;
35-
3634 let values = "" ;
3735 linesArray . forEach ( ( line ) => {
3836 // Parses each line of CSV into field values array
3937 const arr = line . split ( / , (? = (?: (?: [ ^ " ] * " ) { 2 } ) * [ ^ " ] * $ ) / ) ;
40-
4138 if ( arr . length > columnNames . length ) {
4239 console . log ( arr ) ;
4340 throw new Error ( "Too Many Values in row" ) ;
4441 } else if ( arr . length < columnNames . length ) {
4542 console . log ( arr ) ;
4643 throw new Error ( "Too Few Values in row" ) ;
4744 }
48-
4945 let valueLine = "\t(" ;
5046 arr . forEach ( ( value ) => {
5147 // Matches NULL values, Numbers,
@@ -66,16 +62,12 @@ async function readCSV(csvFileName = "") {
6662 values += valueLine ;
6763 } ) ;
6864 values = values . slice ( 0 , - 2 ) + ";" ;
69-
7065 const sqlStatement = beginSQLInsert + values ;
71-
7266 // Write File
7367 writeSQL ( sqlStatement ) ;
7468 } catch ( err ) {
7569 console . log ( err ) ;
7670 }
7771}
78-
7972readCSV ( ) ;
80-
8173console . log ( "Finished!" ) ;
0 commit comments