CCCPaste
-- ldb3
-- tiny file DB stored in /data//

local ROOT = "/data"

if not fs.exists(ROOT) then
  fs.makeDir(ROOT)
end

local function dbPath(db)
  return ROOT .. "/" .. db
end

local function recPath(db, key)
  return dbPath(db) .. "/" .. key
end

local function ensure(db)
  local p = dbPath(db)
  if not fs.exists(p) then
    fs.makeDir(p)
  end
end

function set(db, key, value)
  ensure(db)
  local h = fs.open(recPath(db, key), "w")
  h.write(textutils.serialize(value))
  h.close()
end

function get(db, key, default)
  local p = recPath(db, key)
  if not fs.exists(p) then
    return default
  end
  local h = fs.open(p, "r")
  local raw = h.readAll()
  h.close()
  local ok, val = pcall(textutils.unserialize, raw)
  if ok then
    return val
  else
    return default
  end
end

function list(db)
  local p = dbPath(db)
  if not fs.exists(p) then return {} end
  return fs.list(p)
end

function del(db, key)
  local p = recPath(db, key)
  if fs.exists(p) then fs.delete(p) end
end

function clear(db)
  for _, name in ipairs(list(db)) do
    del(db, name)
  end
end