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"
3
4
async function writeSQL ( statement : string , saveFileAs = "" ) {
4
5
try {
5
6
const destinationFile = process . argv [ 2 ] || saveFileAs ;
6
-
7
7
if ( ! destinationFile ) {
8
8
throw new Error ( "Missing saveFileAs parameter" ) ;
9
9
}
10
-
10
+ createIfNot ( path . resolve ( `/sql/ ${ destinationFile } .sql` ) )
11
11
await fs . writeFile ( `sql/${ process . argv [ 2 ] } .sql` , statement ) ;
12
12
} catch ( err ) {
13
13
console . log ( err ) ;
14
14
}
15
15
}
16
-
17
16
async function readCSV ( csvFileName = "" ) {
18
17
try {
19
18
const fileAndTableName = process . argv [ 2 ] || csvFileName ;
20
-
21
19
if ( ! fileAndTableName ) {
22
20
throw new Error ( "Missing csvFileName parameter" ) ;
23
21
}
24
-
22
+ if ( existsSync ( path . resolve ( `./csv/${ fileAndTableName } .csv` ) ) ) {
23
+ console . log ( "file not found" )
24
+ return
25
+ }
25
26
const data = await fs . readFile ( `csv/${ fileAndTableName } .csv` , {
26
27
encoding : "utf8" ,
27
28
} ) ;
28
-
29
29
const linesArray = data . split ( / \r | \n / ) . filter ( ( line ) => line ) ;
30
30
const columnNames = linesArray ?. shift ( ) ?. split ( "," ) || [ ] ;
31
-
32
31
let beginSQLInsert = `INSERT INTO ${ fileAndTableName } (` ;
33
32
columnNames . forEach ( ( name ) => ( beginSQLInsert += `${ name } , ` ) ) ;
34
33
beginSQLInsert = beginSQLInsert . slice ( 0 , - 2 ) + ")\nVALUES\n" ;
35
-
36
34
let values = "" ;
37
35
linesArray . forEach ( ( line ) => {
38
36
// Parses each line of CSV into field values array
39
37
const arr = line . split ( / , (? = (?: (?: [ ^ " ] * " ) { 2 } ) * [ ^ " ] * $ ) / ) ;
40
-
41
38
if ( arr . length > columnNames . length ) {
42
39
console . log ( arr ) ;
43
40
throw new Error ( "Too Many Values in row" ) ;
44
41
} else if ( arr . length < columnNames . length ) {
45
42
console . log ( arr ) ;
46
43
throw new Error ( "Too Few Values in row" ) ;
47
44
}
48
-
49
45
let valueLine = "\t(" ;
50
46
arr . forEach ( ( value ) => {
51
47
// Matches NULL values, Numbers,
@@ -66,16 +62,12 @@ async function readCSV(csvFileName = "") {
66
62
values += valueLine ;
67
63
} ) ;
68
64
values = values . slice ( 0 , - 2 ) + ";" ;
69
-
70
65
const sqlStatement = beginSQLInsert + values ;
71
-
72
66
// Write File
73
67
writeSQL ( sqlStatement ) ;
74
68
} catch ( err ) {
75
69
console . log ( err ) ;
76
70
}
77
71
}
78
-
79
72
readCSV ( ) ;
80
-
81
73
console . log ( "Finished!" ) ;
0 commit comments