1
1
import { promises as fs } from "fs" ;
2
2
3
- async function writeSQL ( statement : string , saveFileAs = "" ) {
3
+ async function writeSQL ( statement : string , saveFileAs = "" , isAppend : boolean = false ) {
4
4
try {
5
5
const destinationFile = process . argv [ 2 ] || saveFileAs ;
6
6
7
7
if ( ! destinationFile ) {
8
8
throw new Error ( "Missing saveFileAs parameter" ) ;
9
9
}
10
10
11
- await fs . writeFile ( `sql/${ process . argv [ 2 ] } .sql` , statement ) ;
11
+ if ( isAppend ) {
12
+ await fs . appendFile ( `sql/${ process . argv [ 2 ] } .sql` , statement ) ;
13
+ } else {
14
+ await fs . writeFile ( `sql/${ process . argv [ 2 ] } .sql` , statement ) ;
15
+ }
16
+
12
17
} catch ( err ) {
13
18
console . log ( err ) ;
14
19
}
15
20
}
16
21
17
- async function readCSV ( csvFileName = "" ) {
22
+ async function readCSV ( csvFileName = "" , batchSize : number = 0 ) {
18
23
try {
19
24
const fileAndTableName = process . argv [ 2 ] || csvFileName ;
25
+
26
+ batchSize = parseInt ( process . argv [ 3 ] ) || batchSize || 500 ;
27
+ let isAppend : boolean = false ;
20
28
21
29
if ( ! fileAndTableName ) {
22
30
throw new Error ( "Missing csvFileName parameter" ) ;
@@ -34,7 +42,7 @@ async function readCSV(csvFileName = "") {
34
42
beginSQLInsert = beginSQLInsert . slice ( 0 , - 2 ) + ")\nVALUES\n" ;
35
43
36
44
let values = "" ;
37
- linesArray . forEach ( ( line ) => {
45
+ linesArray . forEach ( ( line , index ) => {
38
46
// Parses each line of CSV into field values array
39
47
const arr = line . split ( / , (? = (?: (?: [ ^ " ] * " ) { 2 } ) * [ ^ " ] * $ ) / ) ;
40
48
@@ -46,6 +54,18 @@ async function readCSV(csvFileName = "") {
46
54
throw new Error ( "Too Few Values in row" ) ;
47
55
}
48
56
57
+ // Check batch size (rows per batch)
58
+ if ( index > 0 && index % batchSize == 0 ) {
59
+ values = values . slice ( 0 , - 2 ) + ";\n\n" ;
60
+
61
+ const sqlStatement = beginSQLInsert + values ;
62
+
63
+ // Write File
64
+ writeSQL ( sqlStatement , fileAndTableName , isAppend ) ;
65
+ values = "" ;
66
+ isAppend = true ;
67
+ }
68
+
49
69
let valueLine = "\t(" ;
50
70
arr . forEach ( ( value ) => {
51
71
// Matches NULL values, Numbers,
@@ -70,7 +90,7 @@ async function readCSV(csvFileName = "") {
70
90
const sqlStatement = beginSQLInsert + values ;
71
91
72
92
// Write File
73
- writeSQL ( sqlStatement ) ;
93
+ writeSQL ( sqlStatement , fileAndTableName , isAppend ) ;
74
94
} catch ( err ) {
75
95
console . log ( err ) ;
76
96
}
0 commit comments