botql 1.0.2 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Database.js +1 -146
- package/Parser.js +1 -762
- package/README.md +157 -12
- package/botql.browser.js +481 -1067
- package/botql.js +3 -785
- package/package.json +1 -1
package/Database.js
CHANGED
|
@@ -1,146 +1 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Database.js — Camada de banco de dados do BotQL
|
|
5
|
-
*
|
|
6
|
-
* Qualquer adapter aqui implementa a mesma interface, usada pelo botql.js:
|
|
7
|
-
* createTable(name, columns, preventDefault)
|
|
8
|
-
* insert(table, columnNames, values) -> id
|
|
9
|
-
* update(table, column, value, whereColumn, whereValue)
|
|
10
|
-
* getRows(table) -> array de linhas
|
|
11
|
-
*
|
|
12
|
-
* MemoryDatabase: guarda tudo em memória, sem persistência — bom para
|
|
13
|
-
* testes e para o exemplo do botql.js.
|
|
14
|
-
*
|
|
15
|
-
* SQLiteDatabase: persiste num ficheiro .sqlite real, usando o módulo
|
|
16
|
-
* nativo `node:sqlite` (Node 22+), sem dependências externas.
|
|
17
|
-
*/
|
|
18
|
-
|
|
19
|
-
const CONTEXT_SCHEMA = [
|
|
20
|
-
{ name: 'id', columnType: 'INT', constraints: ['PRIMARY', 'KEY', 'AUTO_INCREMENT'] },
|
|
21
|
-
{ name: 'client', columnType: 'TEXT', constraints: [] },
|
|
22
|
-
{ name: 'message', columnType: 'TEXT', constraints: [] },
|
|
23
|
-
{ name: 'reply', columnType: 'TEXT', constraints: [] },
|
|
24
|
-
{ name: 'created_at', columnType: 'DATETIME', constraints: [] }
|
|
25
|
-
];
|
|
26
|
-
|
|
27
|
-
// ===== MemoryDatabase =====
|
|
28
|
-
|
|
29
|
-
class MemoryDatabase {
|
|
30
|
-
constructor() {
|
|
31
|
-
this.tables = new Map();
|
|
32
|
-
this.autoIncrement = new Map();
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
createTable(name, columns, preventDefault) {
|
|
36
|
-
const resolvedColumns = (name === 'Context' && columns.length === 0)
|
|
37
|
-
? CONTEXT_SCHEMA
|
|
38
|
-
: columns;
|
|
39
|
-
|
|
40
|
-
if (this.tables.has(name)) {
|
|
41
|
-
if (preventDefault) return;
|
|
42
|
-
throw new Error(`runtime error: table "${name}" already exists`);
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
this.tables.set(name, { columns: resolvedColumns, rows: [] });
|
|
46
|
-
this.autoIncrement.set(name, 0);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
insert(table, columnNames, values) {
|
|
50
|
-
const t = this.tables.get(table);
|
|
51
|
-
if (!t) throw new Error(`runtime error: table "${table}" does not exist`);
|
|
52
|
-
|
|
53
|
-
const nextId = this.autoIncrement.get(table) + 1;
|
|
54
|
-
this.autoIncrement.set(table, nextId);
|
|
55
|
-
|
|
56
|
-
const row = { id: nextId };
|
|
57
|
-
columnNames.forEach((col, i) => { row[col] = values[i]; });
|
|
58
|
-
t.rows.push(row);
|
|
59
|
-
|
|
60
|
-
return nextId;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
update(table, column, value, whereColumn, whereValue) {
|
|
64
|
-
const t = this.tables.get(table);
|
|
65
|
-
if (!t) throw new Error(`runtime error: table "${table}" does not exist`);
|
|
66
|
-
|
|
67
|
-
const row = whereColumn
|
|
68
|
-
? t.rows.find((r) => r[whereColumn] === whereValue)
|
|
69
|
-
: t.rows[t.rows.length - 1];
|
|
70
|
-
|
|
71
|
-
if (row) row[column] = value;
|
|
72
|
-
return row || null;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
getRows(table) {
|
|
76
|
-
const t = this.tables.get(table);
|
|
77
|
-
return t ? t.rows.slice() : [];
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// ===== SQLiteDatabase =====
|
|
82
|
-
|
|
83
|
-
function mapColumnType(columnType) {
|
|
84
|
-
const type = (columnType || '').toUpperCase();
|
|
85
|
-
if (type === 'INT' || type === 'INTEGER') return 'INTEGER';
|
|
86
|
-
if (type === 'DATETIME' || type === 'DATE') return 'TEXT';
|
|
87
|
-
return 'TEXT';
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
function buildColumnDef(col) {
|
|
91
|
-
const type = mapColumnType(col.columnType);
|
|
92
|
-
const isPrimary = col.constraints.includes('PRIMARY') && col.constraints.includes('KEY');
|
|
93
|
-
const isAutoIncrement = col.constraints.includes('AUTO_INCREMENT');
|
|
94
|
-
|
|
95
|
-
let def = `${col.name} ${type}`;
|
|
96
|
-
if (isPrimary) def += ' PRIMARY KEY';
|
|
97
|
-
if (isPrimary && isAutoIncrement) def += ' AUTOINCREMENT';
|
|
98
|
-
return def;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
class SQLiteDatabase {
|
|
102
|
-
/**
|
|
103
|
-
* @param {string} filePath Caminho do ficheiro .sqlite, ou ":memory:" para um banco temporário.
|
|
104
|
-
*/
|
|
105
|
-
constructor(filePath = ':memory:') {
|
|
106
|
-
const { DatabaseSync } = require('node:sqlite');
|
|
107
|
-
this.driver = new DatabaseSync(filePath);
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
createTable(name, columns, preventDefault) {
|
|
111
|
-
const resolvedColumns = (name === 'Context' && columns.length === 0)
|
|
112
|
-
? CONTEXT_SCHEMA
|
|
113
|
-
: columns;
|
|
114
|
-
|
|
115
|
-
const columnDefs = resolvedColumns.map(buildColumnDef).join(', ');
|
|
116
|
-
const ifNotExists = preventDefault ? 'IF NOT EXISTS ' : '';
|
|
117
|
-
this.driver.exec(`CREATE TABLE ${ifNotExists}${name} (${columnDefs})`);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
insert(table, columnNames, values) {
|
|
121
|
-
const placeholders = columnNames.map(() => '?').join(', ');
|
|
122
|
-
const sql = `INSERT INTO ${table} (${columnNames.join(', ')}) VALUES (${placeholders})`;
|
|
123
|
-
const info = this.driver.prepare(sql).run(...values);
|
|
124
|
-
return Number(info.lastInsertRowid);
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
update(table, column, value, whereColumn, whereValue) {
|
|
128
|
-
if (whereColumn) {
|
|
129
|
-
const sql = `UPDATE ${table} SET ${column} = ? WHERE ${whereColumn} = ?`;
|
|
130
|
-
this.driver.prepare(sql).run(value, whereValue);
|
|
131
|
-
} else {
|
|
132
|
-
const sql = `UPDATE ${table} SET ${column} = ? WHERE id = (SELECT MAX(id) FROM ${table})`;
|
|
133
|
-
this.driver.prepare(sql).run(value);
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
getRows(table) {
|
|
138
|
-
return this.driver.prepare(`SELECT * FROM ${table}`).all();
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
close() {
|
|
142
|
-
this.driver.close();
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
module.exports = { MemoryDatabase, SQLiteDatabase };
|
|
1
|
+
"use strict";const CONTEXT_SCHEMA=[{name:"id",columnType:"INT",constraints:["PRIMARY","KEY","AUTO_INCREMENT"]},{name:"client",columnType:"TEXT",constraints:[]},{name:"message",columnType:"TEXT",constraints:[]},{name:"reply",columnType:"TEXT",constraints:[]},{name:"created_at",columnType:"DATETIME",constraints:[]}];class MemoryDatabase{constructor(){this.tables=new Map,this.autoIncrement=new Map}createTable(e,t,r){let s="Context"===e&&0===t.length?CONTEXT_SCHEMA:t;if(this.tables.has(e)){if(r)return;throw Error(`runtime error: table "${e}" already exists`)}this.tables.set(e,{columns:s,rows:[]}),this.autoIncrement.set(e,0)}insert(e,t,r){let s=this.tables.get(e);if(!s)throw Error(`runtime error: table "${e}" does not exist`);let n=this.autoIncrement.get(e)+1;this.autoIncrement.set(e,n);let i={id:n};return t.forEach((e,t)=>{i[e]=r[t]}),s.rows.push(i),n}update(e,t,r,s,n){let i=this.tables.get(e);if(!i)throw Error(`runtime error: table "${e}" does not exist`);let a=s?i.rows.find(e=>e[s]===n):i.rows[i.rows.length-1];return a&&(a[t]=r),a||null}getRows(e){let t=this.tables.get(e);return t?t.rows.slice():[]}}function mapColumnType(e){let t=(e||"").toUpperCase();return"INT"===t||"INTEGER"===t?"INTEGER":"TEXT"}function buildColumnDef(e){let t=mapColumnType(e.columnType),r=e.constraints.includes("PRIMARY")&&e.constraints.includes("KEY"),s=e.constraints.includes("AUTO_INCREMENT"),n=`${e.name} ${t}`;return r&&(n+=" PRIMARY KEY"),r&&s&&(n+=" AUTOINCREMENT"),n}class SQLiteDatabase{constructor(e=":memory:"){let{DatabaseSync:t}=require("node:sqlite");this.driver=new t(e)}createTable(e,t,r){let s="Context"===e&&0===t.length?CONTEXT_SCHEMA:t,n=s.map(buildColumnDef).join(", ");this.driver.exec(`CREATE TABLE ${r?"IF NOT EXISTS ":""}${e} (${n})`)}insert(e,t,r){let s=t.map(()=>"?").join(", "),n=`INSERT INTO ${e} (${t.join(", ")}) VALUES (${s})`,i=this.driver.prepare(n).run(...r);return Number(i.lastInsertRowid)}update(e,t,r,s,n){if(s){let i=`UPDATE ${e} SET ${t} = ? WHERE ${s} = ?`;this.driver.prepare(i).run(r,n)}else{let a=`UPDATE ${e} SET ${t} = ? WHERE id = (SELECT MAX(id) FROM ${e})`;this.driver.prepare(a).run(r)}}getRows(e){return this.driver.prepare(`SELECT * FROM ${e}`).all()}close(){this.driver.close()}}module.exports={MemoryDatabase,SQLiteDatabase};
|