Last active
March 9, 2022 00:43
-
-
Save Desour/98229b8604c2957ebd4d2791e539bc48 to your computer and use it in GitHub Desktop.
script to insert minetest media files into a sqlite db
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
luafilesystem
andlsqlite3