1+ const fs = require ( 'node:fs/promises' ) ;
2+
3+ async function writeSQL ( statement ) {
4+ try {
5+ await fs . writeFile ( `sql/${ process . argv [ 2 ] } .sql` , statement ) ;
6+ } catch ( err ) {
7+ console . log ( err ) ;
8+ }
9+ }
10+
11+ async function readCSV ( csvFileName = '' ) {
12+ const fileAndTableName = process . argv [ 2 ] || csvFileName
13+
14+ try {
15+ const data = await fs . readFile ( `csv/${ fileAndTableName } .csv` , { encoding : 'utf8' } ) ;
16+
17+ const linesArray = data . split ( / \r | \n / ) . filter ( line => line )
18+ const columnNames = linesArray . shift ( ) . split ( "," )
19+
20+ let insertStart = `INSERT INTO ${ fileAndTableName } (`
21+ columnNames . forEach ( name => insertStart += `${ name } , ` )
22+ insertStart = insertStart . slice ( 0 , - 2 ) + ")\nVALUES\n"
23+
24+ let values = ''
25+ linesArray . forEach ( line => {
26+ const arr = line . split ( / , (? = (?: (?: [ ^ " ] * " ) { 2 } ) * [ ^ " ] * $ ) / )
27+
28+ if ( arr . length > columnNames . length ) {
29+ console . log ( arr )
30+ throw new Error ( "Too Many Values in row" )
31+ }
32+
33+ const timestampRegex = / ^ \d { 4 } - \d { 2 } - \d { 2 } \d { 2 } : \d { 2 } : \d { 2 } \. \d { 3 } $ /
34+ // value.match(timestampRegex) ||
35+ let valueLine = '\t('
36+ arr . forEach ( value => {
37+ // NULL values
38+ // Numbers, Strings accepted as numbers, and Booleans (0 or 1)
39+ if ( value === "NULL" || ! isNaN ( + value ) ) {
40+ valueLine += `${ value } , `
41+ }
42+ else {
43+ // If a string is wrapped in quotes, it doesn't need more
44+ if ( value . at ( 0 ) === '"' ) valueLine += `${ value } , `
45+ else {
46+ // This wraps strings in quotes that need them
47+ // also wraps timestamps
48+ valueLine += `"${ value } ", `
49+ }
50+ }
51+ } )
52+ valueLine = valueLine . slice ( 0 , - 2 ) + "),\n"
53+ values += valueLine
54+ } )
55+ values = values . slice ( 0 , - 2 ) + ";"
56+
57+ const sqlStatement = insertStart + values
58+
59+ // Write File
60+ writeSQL ( sqlStatement )
61+
62+ } catch ( err ) {
63+ console . log ( err ) ;
64+ }
65+ }
66+
67+ readCSV ( )
68+
69+ console . log ( 'Finished!' )
0 commit comments