2025-11-25 09:11:29 -06:00

158 lines
4.0 KiB
JavaScript

const initSqlJs = require('sql.js');
const fs = require('fs');
const { resourceUsage } = require('process');
let db = null;
const DB_PATH = './ka.db';
// Helper functions
function getNextKANumber() {
const result = db.exec('SELECT ka_number FROM articles ORDER BY id DESC LIMIT 1')
if (result.length > 0 && result[0].values.length > 0) {
const lastKANumber = result[0].values[0][0];
const number = parseInt(lastKANumber.replace('KA', '')) + 1;
return `KA${String(number).padStart(3, '0')}`;
}
return 'KA001';
}
async function initDb() {
const SQL = await initSqlJs();
console.log('Initializing Database...');
// Loading Database if it already exists
if (fs.existsSync(DB_PATH)) {
const buffer = fs.readFileSync(DB_PATH);
db = new SQL.Database(buffer);
console.log('Database Loaded')
} else {
// Creating a new one if it does not
console.log('Database not found. Creating new instance...')
db = new SQL.Database();
// Creating Knowledge Article table
db.run(`
CREATE TABLE articles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ka_number TEXT UNIQUE,
title TEXT,
content TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME
)
`);
db.run("CREATE INDEX idx_ka_number ON articles(ka_number)");
// Saving the created db to file
const data = db.export();
fs.writeFileSync(DB_PATH, Buffer.from(data));
console.log(`Database created at ${DB_PATH}`);
}
return db;
}
// Get all articles from the DB
function getAllArticles() {
const result = db.exec("SELECT * FROM articles ORDER BY created_at DESC");
if (result.length === 0) {
return [];
}
const columns = result[0].columns;
const rows = result[0].values;
const articles = rows.map(row => {
const article = {};
columns.forEach((col, index) => {
article[col] = row[index];
});
return article;
})
return articles;
}
// Get a specific article from the DB
function getArticle(ka_num) {
const stmt = db.prepare('SELECT * FROM articles where ka_number = ?');
stmt.bind([ka_num]);
if (stmt.step()) {
const article = stmt.getAsObject();
stmt.free();
return article;
}
stmt.free();
return null;
}
// Create a new article
function createArticle(title, content) {
const ka_num = getNextKANumber();
db.run(
"INSERT INTO articles (ka_number, title, content) VALUES (?, ?, ?)",
[ka_num, title, content]
);
// Saving updated DB to file
const data = db.export();
fs.writeFileSync(DB_PATH, Buffer.from(data));
return getArticle(ka_num);
}
function updateArticle(ka_num, title, content) {
db.run(
"UPDATE articles SET title = ?, content = ?, updated_at = CURRENT_TIMESTAMP WHERE ka_number = ?",
[title, content, ka_num]
);
// Saving updated DB to file
const data = db.export();
fs.writeFileSync(DB_PATH, Buffer.from(data));
return getArticle(ka_num);
}
// Delete the article from the DB
function deleteArticle(ka_num) {
db.run(
"DELETE FROM articles WHERE ka_number = ?",
[ka_num]
);
// Saving updated DB to file
const data = db.export();
fs.writeFileSync(DB_PATH, Buffer.from(data));
}
// Simple search to look for matching terms or KA number
function searchArticles(query) {
const searchTerm = `%${query}%`;
const stmt = db.prepare(
"SELECT * FROM articles WHERE title LIKE ? OR content LIKE ? or ka_number LIKE ? ORDER BY created_at DESC"
);
stmt.bind([searchTerm, searchTerm, searchTerm]);
const results = [];
while (stmt.step()) {
results.push(stmt.getAsObject());
}
stmt.free();
return results;
}
module.exports = { initDb, getAllArticles, getArticle, createArticle, updateArticle, deleteArticle, searchArticles };