11import { promises as fs , existsSync } from "fs" ;
22import { createIfNot } from "./utils/fileUtils.js"
33import * as path from "node:path"
4- async function writeSQL ( statement : string , saveFileAs = "" ) {
4+ async function writeSQL ( statement : string , saveFileAs = "" , isAppend : boolean = false ) {
55 try {
66 const destinationFile = process . argv [ 2 ] || saveFileAs ;
77 if ( ! destinationFile ) {
88 throw new Error ( "Missing saveFileAs parameter" ) ;
99 }
1010 createIfNot ( path . resolve ( `./sql/${ destinationFile } .sql` ) )
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+ }
1216 } catch ( err ) {
1317 console . log ( err ) ;
1418 }
1519}
16- async function readCSV ( csvFileName = "" ) {
20+
21+ async function readCSV ( csvFileName = "" , batchSize : number = 0 ) {
1722 try {
1823 const fileAndTableName = process . argv [ 2 ] || csvFileName ;
24+
25+ batchSize = parseInt ( process . argv [ 3 ] ) || batchSize || 500 ;
26+ let isAppend : boolean = false ;
27+
1928 if ( ! fileAndTableName ) {
2029 throw new Error ( "Missing csvFileName parameter" ) ;
2130 }
@@ -32,7 +41,7 @@ async function readCSV(csvFileName = "") {
3241 columnNames . forEach ( ( name ) => ( beginSQLInsert += `${ name } , ` ) ) ;
3342 beginSQLInsert = beginSQLInsert . slice ( 0 , - 2 ) + ")\nVALUES\n" ;
3443 let values = "" ;
35- linesArray . forEach ( ( line ) => {
44+ linesArray . forEach ( ( line , index ) => {
3645 // Parses each line of CSV into field values array
3746 const arr = line . split ( / , (? = (?: (?: [ ^ " ] * " ) { 2 } ) * [ ^ " ] * $ ) / ) ;
3847 if ( arr . length > columnNames . length ) {
@@ -42,6 +51,19 @@ async function readCSV(csvFileName = "") {
4251 console . log ( arr ) ;
4352 throw new Error ( "Too Few Values in row" ) ;
4453 }
54+
55+ // Check batch size (rows per batch)
56+ if ( index > 0 && index % batchSize == 0 ) {
57+ values = values . slice ( 0 , - 2 ) + ";\n\n" ;
58+
59+ const sqlStatement = beginSQLInsert + values ;
60+
61+ // Write File
62+ writeSQL ( sqlStatement , fileAndTableName , isAppend ) ;
63+ values = "" ;
64+ isAppend = true ;
65+ }
66+
4567 let valueLine = "\t(" ;
4668 arr . forEach ( ( value ) => {
4769 // Matches NULL values, Numbers,
@@ -64,7 +86,7 @@ async function readCSV(csvFileName = "") {
6486 values = values . slice ( 0 , - 2 ) + ";" ;
6587 const sqlStatement = beginSQLInsert + values ;
6688 // Write File
67- writeSQL ( sqlStatement ) ;
89+ writeSQL ( sqlStatement , fileAndTableName , isAppend ) ;
6890 } catch ( err ) {
6991 console . log ( err ) ;
7092 }
0 commit comments