]> git.ipfire.org Git - people/ms/libloc.git/commitdiff
lua: database: Implement fetching countries
authorMichael Tremer <michael.tremer@ipfire.org>
Thu, 22 Feb 2024 15:43:07 +0000 (15:43 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Thu, 22 Feb 2024 15:43:07 +0000 (15:43 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/lua/database.c
tests/lua/main.lua

index 65e7aa6e3f0257047ac74684bd0249c95ce19a1d..ca46cbb5ec6ed1db67e346f8e600992cba8c5053 100644 (file)
@@ -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 },
index 2076202115e9854094aeb9a08572e32ca69aadb1..70e918a2e56dba12f3703c267eef2d08c9d45754 100755 (executable)
@@ -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"))