Skip to content

Instantly share code, notes, and snippets.

@Desour
Last active March 9, 2022 00:43
Show Gist options
  • Save Desour/98229b8604c2957ebd4d2791e539bc48 to your computer and use it in GitHub Desktop.
Save Desour/98229b8604c2957ebd4d2791e539bc48 to your computer and use it in GitHub Desktop.
script to insert minetest media files into a sqlite db
local lfs = require("lfs")
local sqlite3 = require("lsqlite3")
local cache_path = "path_to_minetest/cache/" -- please edit this!
local function check(expected, ...)
if select(1, ...) == expected then
return ...
end
error(string.format("expected retval %d, but got %d", expected, select(1, ...)),
2)
end
local function checkOK(...)
return check(sqlite3.OK, ...)
end
local mediafiles_folder_path = cache_path .. "media/"
local media_db_path = cache_path .. "media_db.sqlite"
local db, ret, msg = sqlite3.open(media_db_path)
if not db then
print(msg)
checkOK(ret)
end
local stmt_insert = db:prepare([[
INSERT OR IGNORE INTO files
VALUES(?, strftime('%s', 'now'), 0, ?, ?, ?);
]])
checkOK(db:exec([[BEGIN EXCLUSIVE;]]))
for filename in lfs.dir(mediafiles_folder_path) do
local filepath = mediafiles_folder_path .. filename
if assert(lfs.attributes(filepath, "mode")) == "file" then
local file = assert(io.open(filepath))
local data = assert(file:read("*a"))
checkOK(stmt_insert:bind(1, filename)) -- sha1
checkOK(stmt_insert:bind(2, 1)) -- cache_class (=Legacy=1)
checkOK(stmt_insert:bind(3, 0)) -- data_format (=Raw=0)
checkOK(stmt_insert:bind_blob(4, data)) -- data
check(sqlite3.DONE, stmt_insert:step())
file:close()
stmt_insert:bind_values(nil, nil, nil, nil)
stmt_insert:reset()
end
end
checkOK(db:exec([[END;]]))
checkOK(db:close())
@Desour
Copy link
Author

Desour commented Aug 24, 2021

  • Dependencies can be installed with luarocks: install luafilesystem and lsqlite3
  • Tested with lua5.1 (luajit).
  • The sqlite db must already exist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment