97 lines
2.2 KiB
TypeScript
97 lines
2.2 KiB
TypeScript
import pl, { DataFrame } from 'nodejs-polars'
|
|
import fs, { writeFile } from 'fs'
|
|
|
|
export function test_x(params: any) {
|
|
const fooSeries = pl.Series("foo", [1, 2, 3])
|
|
|
|
let res = fooSeries.sum()
|
|
|
|
console.log(res)
|
|
|
|
let df = pl.readCSV("data/iris.csv")
|
|
}
|
|
|
|
class CSVDatabase {
|
|
private df: DataFrame | null = null
|
|
private filePath: string
|
|
|
|
constructor(filePath: string) {
|
|
this.filePath = filePath
|
|
this.loadCSV()
|
|
}
|
|
|
|
private loadCSV() {
|
|
fs.existsSync(this.filePath) ? this.df = pl.readCSV(this.filePath) : this.df = DataFrame([])
|
|
}
|
|
|
|
private saveCSV() {
|
|
if (this.df) {
|
|
fs.writeFileSync(this.filePath, this.df.writeCSV())
|
|
}
|
|
}
|
|
|
|
create(row: Record<string, any>) {
|
|
if (this.df) {
|
|
this.df = this.df.vstack(DataFrame([row]))
|
|
this.saveCSV()
|
|
}
|
|
}
|
|
|
|
read(filter: Record<string, any>) {
|
|
return this.df ? this.df.filter(filter) : null
|
|
}
|
|
|
|
update(filter: Record<string, any>, values: Record<string, any>) {
|
|
if (this.df) {
|
|
// update it
|
|
this.saveCSV()
|
|
}
|
|
}
|
|
|
|
delete(filter: Record<string, any>) {
|
|
if (this.df) {
|
|
// should be filter Not
|
|
this.df = this.df.filter(filter)
|
|
this.saveCSV()
|
|
}
|
|
}
|
|
}
|
|
|
|
// A CSV can refer to other CSV's via pointers, a type of metadata
|
|
|
|
interface CSVDatabase2 {
|
|
df: DataFrame
|
|
filepath: string
|
|
}
|
|
|
|
export function create_csv_database(filepath: string): CSVDatabase2 {
|
|
// let df = DataFrame([], { columns: ["key", "value"] })
|
|
let df = DataFrame({ "key": ['header'], "value": ['next'] })
|
|
|
|
// writeFile(filepath, 'key,value\nheader,next', () => { })
|
|
// let df = pl.readCSV(filepath)
|
|
df.writeCSV(filepath)
|
|
|
|
return { df, filepath }
|
|
}
|
|
|
|
export function save_db(db: CSVDatabase2) {
|
|
db.df.writeCSV(db.filepath)
|
|
}
|
|
|
|
export function add_row(db: CSVDatabase2, row: Record<string, string>) {
|
|
db.df = db.df.vstack(DataFrame(row))
|
|
}
|
|
|
|
export function print_head(db: CSVDatabase2) {
|
|
console.log(db.df.head())
|
|
}
|
|
|
|
// can filter everything that is not the row, and do to db
|
|
|
|
export function delete_row_by_key({df, filepath}: CSVDatabase2, key: string) {
|
|
// db.df.drop(pl.col("key").eq(key))
|
|
// df = df.select((pl.col("key") != key).alias("nrs > 1"))
|
|
// db.df = db.df.filter(pl.col("key").neq(key))
|
|
}
|