Skip to content

Commit

Permalink
updated this template to work with sqlite and dbAdmin
Browse files Browse the repository at this point in the history
  • Loading branch information
pratikbuilds committed Dec 2, 2024
1 parent 6c08aeb commit c2338fe
Show file tree
Hide file tree
Showing 5 changed files with 208 additions and 52 deletions.
2 changes: 1 addition & 1 deletion aos/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ interface OutputData {
}

export default class aos {
wasm = fs.readFileSync(path.join(__dirname) + "/../process.wasm");
wasm = fs.readFileSync(path.join(__dirname) + "/../process-sqlite.wasm");
code: string;
process_id: string;
module_id: string;
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "AOS Integration Test Kit",
"scripts": {
"test:js": "node --test test/**/*.test.js",
"test:sqlite": "FORMAT=wasm32-unknown-emscripten2 WASM=./AOS-SQLITE.wasm node --test test/**/*.test.js",
"test:sqlite": "FORMAT=wasm32-unknown-emscripten2 WASM=./process-sqlite.wasm node --experimental-wasm-memory64 --import tsx --test ./test/*.test.ts",
"test": "node --experimental-wasm-memory64 --import tsx --test ./test/*.test.ts"
},
"keywords": [],
Expand Down
79 changes: 79 additions & 0 deletions src/dbAdmin.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
local dbAdmin = {}
dbAdmin.__index = dbAdmin

-- Function to create a new database explorer instance
function dbAdmin.new(db)
local self = setmetatable({}, dbAdmin)
self.db = db
return self
end

-- Function to list all tables in the database
function dbAdmin:tables()
local tables = {}
for row in self.db:nrows("SELECT name FROM sqlite_master WHERE type='table';") do
table.insert(tables, row.name)
end
return tables
end

-- Function to get the record count of a table
function dbAdmin:count(tableName)
local count_query = string.format("SELECT COUNT(*) AS count FROM %s;", tableName)
for row in self.db:nrows(count_query) do
return row.count
end
end

-- Function to execute a given SQL query
function dbAdmin:exec(sql)
local results = {}
for row in self.db:nrows(sql) do
table.insert(results, row)
end
return results
end

-- Function to apply SQL INSERT, UPDATE, and DELETE statements with parameter binding
function dbAdmin:apply(sql, values)
local DONE = require('lsqlite3').DONE
assert(type(sql) == 'string', 'SQL MUST be a String')
assert(type(values) == 'table', 'values MUST be an array of values')

local stmt = self.db:prepare(sql)
stmt:bind_values(table.unpack(values))

if stmt:step() ~= DONE then
error(sql .. ' statement failed because ' .. self.db:errmsg())
end

stmt:finalize()
end

-- Function to apply SQL SELECT statements with parameter binding
function dbAdmin:select(sql, values)
local sqlite3 = require('lsqlite3')
local DONE = sqlite3.DONE
assert(type(sql) == 'string', 'SQL MUST be a String')
assert(type(values) == 'table', 'values MUST be an array of values')

local stmt = self.db:prepare(sql)
stmt:bind_values(table.unpack(values))

local results = {}
while true do
local row = stmt:step()
if row == sqlite3.ROW then
table.insert(results, stmt:get_named_values())
elseif row == DONE then
break
else
error(sql .. ' statement failed because ' .. self.db:errmsg())
end
end

stmt:finalize()
return results
end

return dbAdmin
113 changes: 92 additions & 21 deletions src/main.lua
Original file line number Diff line number Diff line change
@@ -1,21 +1,92 @@
Handlers.add("hello", Handlers.utils.hasMatchingTag("Action","hello"),function (msg)
Handlers.utils.reply("hello, world")(msg)
end)
Handlers.add("data",Handlers.utils.hasMatchingTag("Action","data"),function (msg)
local data = "You have send ".. msg.Data
Handlers.utils.reply(data)(msg)
end)
Handlers.add("tags",Handlers.utils.hasMatchingTag("Action","tag"),function (msg)
local data = "The Key is `carname` and the value is "..msg.Tags.carname
Handlers.utils.reply(data)(msg)
end)
Db = Db or {}
Handlers.add("set",Handlers.utils.hasMatchingTag("Action","set"),function (msg)
Db[msg.Tags.key] = msg.Tags.value
local s = "Added "..msg.Tags.key.." as key and "..msg.Tags.value.." as value"
Handlers.utils.reply(s)(msg)
end)
Handlers.add("get",Handlers.utils.hasMatchingTag("Action","get"),function (msg)
local s = "The value for "..msg.Tags.keys.." is "..Db[msg.Tags.keys]
Handlers.utils.reply(s)(msg)
end)
local sqlite3 = require("lsqlite3")
local json = require("json")
DB = DB or sqlite3.open_memory()
DbAdmin = require('DbAdmin').new(DB)
-- DbAdmin = dbAdmin.new(DB)
function Configure()
-- Create Todo table with basic fields
DbAdmin:exec[[
CREATE TABLE Todos (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
completed BOOLEAN DEFAULT 0
);
]]

Configured = true
end

if not Configured then Configure() end


function sendReply(msg, data)
msg.reply({Data = data, Action = msg.Action .. "Response"})
end

function addTodo(data)
DbAdmin:apply(
'INSERT INTO Todos (id, title, completed) VALUES (?, ?, ?)',
{
data.id,
data.title,
data.completed or false
}
)
end

-- Get all todos
function getTodos()
local results = DbAdmin:exec("SELECT * FROM Todos;")
print(results)
return json.encode(results)
end

-- Update todo
function updateTodo(data)
DbAdmin:apply(
'UPDATE Todos SET title = ?, completed = ? WHERE id = ?',
{
data.title,
data.completed,
data.id
}
)
end

-- Delete todo
function deleteTodo(id)
DbAdmin:apply('DELETE FROM Todos WHERE id = ?', {id})
end

-- Add new todo
function addTodoProcessor(msg)
local data = json.decode(msg.Data)
addTodo(data)
sendReply(msg, data)
end

-- Get all todos
function getTodosProcessor(msg)
local data = getTodos()
sendReply(msg, data)
end

-- Update todo
function updateTodoProcessor(msg)
local data = json.decode(msg.Data)
updateTodo(data)
sendReply(msg, data)
end

-- Delete todo
function deleteTodoProcessor(msg)
local data = json.decode(msg.Data)
deleteTodo(data.id)
sendReply(msg, {success = true})
end

-- Register handlers
Handlers.add("AddTodo", addTodoProcessor)
Handlers.add("GetTodos", getTodosProcessor)
Handlers.add("UpdateTodo", updateTodoProcessor)
Handlers.add("DeleteTodo", deleteTodoProcessor)
64 changes: 35 additions & 29 deletions test/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,43 +16,49 @@ describe("AOS Tests", () => {
await env.init();
});

test("should respond with 'hello, world' for Action: hello", async () => {
const response = await env.send({ Action: "hello" });
assert.equal(response.Messages[0].Data, "hello, world");
test("load DbAdmin module", async () => {
const dbAdminCode = fs.readFileSync("./src/dbAdmin.lua", "utf-8");
const result = await env.send({
Action: "Eval",
Data: `
local function _load()
${dbAdminCode}
end
_G.package.loaded["DbAdmin"] = _load()
return "ok"
`,
});
console.log("result DbAdmin Module", result);
assert.equal(result.Output.data, "ok");
});

test("should respond with 'You have send archlinux' for Action: data", async () => {
const response = await env.send({ Action: "data", Data: "archlinux" });
assert.equal(response.Messages[0].Data, "You have send archlinux");
test("load source", async () => {
const code = fs.readFileSync("./src/main.lua", "utf-8");
const result = await env.send({ Action: "Eval", Data: code });
console.log("result load source", result);
// assert.equal(result.Output.data, "OK");
});

test("should respond with the correct carname value for Action: tag", async () => {
const response = await env.send({
Action: "tag",
Tags: [{ carname: "tesla" }],
});
assert.equal(
response.Messages[0].Data,
"The Key is `carname` and the value is tesla"
);
});
test("should add and get todo", async () => {
const todo = {
id: "1",
title: "Test Todo",
completed: false,
};

test("should add a key-value pair for Action: set", async () => {
const response = await env.send({
Action: "set",
Tags: [{ key: "blockchain" }, { value: "aos" }],
Action: "AddTodo",
Data: JSON.stringify(todo),
});
assert.equal(
response.Messages[0].Data,
"Added blockchain as key and aos as value"
);

console.log("add todo", response);
// const response = await env.send({ Action: "GetTodos" });
// const todos = JSON.parse(response.Messages[0].Data);
// assert.deepEqual(todos[0], todo);
});

test("should retrieve the correct value for Action: get", async () => {
const response = await env.send({
Action: "get",
Tags: [{ keys: "blockchain" }],
});
assert.equal(response.Messages[0].Data, "The value for blockchain is aos");
test("should get todos", async () => {
const response = await env.send({ Action: "GetTodos" });
console.log(response);
});
});

0 comments on commit c2338fe

Please sign in to comment.