From: Michael Tremer Date: Thu, 22 Feb 2024 15:43:07 +0000 (+0000) Subject: lua: database: Implement fetching countries X-Git-Tag: 0.9.18~150 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=494633750307613cbe12537ad10c68dcc114ac76;p=location%2Flibloc.git lua: database: Implement fetching countries Signed-off-by: Michael Tremer --- diff --git a/src/lua/database.c b/src/lua/database.c index 65e7aa6..ca46cbb 100644 --- a/src/lua/database.c +++ b/src/lua/database.c @@ -24,6 +24,7 @@ #include "location.h" #include "as.h" +#include "country.h" #include "database.h" #include "network.h" @@ -107,6 +108,29 @@ static int Database_get_as(lua_State* L) { return r; } +static int Database_get_country(lua_State* L) { + struct loc_country* country = NULL; + int r; + + Database* self = luaL_checkdatabase(L, 1); + + // Fetch code + const char* code = luaL_checkstring(L, 2); + + // Fetch the country + r = loc_database_get_country(self->db, &country, code); + if (r) { + lua_pushnil(L); + return 1; + } + + // Create a new country object + r = create_country(L, country); + loc_country_unref(country); + + return r; +} + static int Database_lookup(lua_State* L) { struct loc_network* network = NULL; int r; @@ -130,6 +154,7 @@ static int Database_lookup(lua_State* L) { static const struct luaL_Reg database_functions[] = { { "get_as", Database_get_as }, + { "get_country", Database_get_country }, { "open", Database_open }, { "lookup", Database_lookup }, { "__gc", Database_gc }, diff --git a/tests/lua/main.lua b/tests/lua/main.lua index 2076202..70e918a 100755 --- a/tests/lua/main.lua +++ b/tests/lua/main.lua @@ -110,6 +110,22 @@ function test_country() c2 = nil end +function test_fetch_country() + location = require("location") + + -- Open the database + db = location.Database.open(ENV_TEST_DATABASE) + + -- Fetch an invalid country + c = db:get_country("XX") + luaunit.assertNil(c) + + -- Fetch something that exists + c = db:get_country("DE") + luaunit.assertEquals(c:get_code(), "DE") + luaunit.assertEquals(c:get_name(), "Germany") +end + -- This test is not very deterministic but should help to test the GC methods function test_gc() print("GC: " .. collectgarbage("collect"))