h-sphere_sql-seal/src/modules/explorer/database/memoryDatabase.ts
Kacper Kula 531d486d06
Feat/sql explorer (#174)
* chore: reworking plugin internals into modules

* feat: settings module is now working, added debug module, enabled new api module

* chore: restoring external API

* feat: refactoring project to use proper inversion of control

* feat: plugins can now be loaded in any order

* chore: final file migration, all typescript is in modules now

* chore: fixing dependencies of cellParser

* feat: csv and json views are only registered when they are not colliding with other plugins

* feat: fixed library behaviour on canvas

* feat: added ability to hide columns from csv files

* feat: adding global tables support (wip)

* feat: global tables full implementation

* feat: sqlite databases can now be previewed in explorer

* feat: improved explorer view

* feat: highlighting code in the copy code modal

* chore: fixing typechecks

* chore: adding missing changeset
2025-08-10 10:08:13 +01:00

52 lines
No EOL
1.5 KiB
TypeScript

import { TFile } from "obsidian";
import { BindParams, Database, ParamsObject } from "sql.js";
import { toObjectArray } from "../../database/worker/database";
import { TableInfo } from "../schemaVisualiser/TableVisualiser";
export class MemoryDatabase {
private db: Database
constructor(private sql: initSqlJs.SqlJsStatic, private file: TFile) {
}
async connect() {
const binary = await this.file.vault.readBinary(this.file)
this.db = new this.sql.Database(Buffer.from(binary))
}
query<T = ParamsObject>(query: string, params: BindParams = null): { data: T[], columns: keyof T } {
const stmt = this.db.prepare(query, params)
const data = toObjectArray(stmt)
const columns = stmt.getColumnNames()
stmt.free()
return { data: data, columns } as any
}
select<T = ParamsObject>(query: string, params: BindParams = null) {
return this.query<T>(query, params)
}
explain() {
return {}
}
allTables() {
return this.query<{name: string}>(`select name from sqlite_master where type='table'`)
}
getColumns(tableName: string) {
return this.query<{ name: string, type: string }>('select name, type from pragma_table_info(@tableName)', { '@tableName': tableName })
}
getSchema(): TableInfo[] {
const tables = this.allTables().data
return tables.map(t => {
const columns = this.getColumns(t.name)
return {
name: t.name,
columns: columns.data
}
})
}
}