-
Notifications
You must be signed in to change notification settings - Fork 0
/
read_csv.ts
51 lines (45 loc) · 1.25 KB
/
read_csv.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import process from "node:process";
import pl, { DataFrame } from "nodejs-polars";
import { Database } from "sqlite3";
function getColsString(
df: pl.DataFrame,
f: (col: pl.Series) => string,
): string {
let col_names: string[] = [];
for (const col of df.getColumns()) {
col_names.push(f(col));
}
return col_names.join(", ");
}
function createTable(db: Database, df: DataFrame, name: string) {
const nameAndDType = (col: pl.Series) => {
return `${col.name}`;
};
db.run(
`CREATE TABLE IF NOT EXISTS cars (${getColsString(df, nameAndDType)})`,
);
}
function insertValues(db: Database, df: DataFrame, table_name: string) {
const name = (col: pl.Series) => {
return `${col.name}`;
};
let values = [];
for (const row of df.rows()) {
let r = [];
for (const cell of row) {
r.push(`${cell}`);
}
values.push(`(${row.join(", ")})`);
}
const query = `INSERT INTO ${table_name} (${getColsString(df, name)}) VALUES ${values.join(", ")}`;
console.log(query);
db.run(query);
}
function writeSQLite(df: pl.DataFrame, table: string) {
const db = new Database("./db.sqlite");
createTable(db, df, table);
insertValues(db, df, table);
}
let path = process.argv[2];
const df = pl.readCSV(path);
writeSQLite(df, "cars");