From eeef67882dc0109e288ebd4be7f60cd7f8f42731 Mon Sep 17 00:00:00 2001 From: Jochen Topf Date: Sun, 7 Apr 2024 20:15:07 +0200 Subject: [PATCH] Optionally build id index as unique index Specify with `create_index = 'unique'` in the `ids` field of the `define_table()` Lua function. The user has to make sure not to insert multiple rows into such a table. This can be useful if some program using the data has special handling for unique ids/primary keys, for instance when it needs unique ids to allow editing. --- src/flex-lua-table.cpp | 3 +++ src/flex-table.cpp | 3 ++- src/flex-table.hpp | 13 +++++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/flex-lua-table.cpp b/src/flex-lua-table.cpp index 98888fdd3..242463d09 100644 --- a/src/flex-lua-table.cpp +++ b/src/flex-lua-table.cpp @@ -108,6 +108,9 @@ static void parse_create_index(lua_State *lua_state, flex_table_t *table) lua_pop(lua_state, 1); // "create_index" if (create_index == "always") { table->set_always_build_id_index(); + } else if (create_index == "unique") { + table->set_always_build_id_index(); + table->set_build_unique_id_index(); } else if (create_index != "auto") { throw fmt_error("Unknown value '{}' for 'create_index' field of ids", create_index); diff --git a/src/flex-table.cpp b/src/flex-table.cpp index 6dff56a4e..76224a6b7 100644 --- a/src/flex-table.cpp +++ b/src/flex-table.cpp @@ -226,7 +226,8 @@ std::string flex_table_t::build_sql_column_list() const std::string flex_table_t::build_sql_create_id_index() const { - return fmt::format("CREATE INDEX ON {} USING BTREE ({}) {}", full_name(), + return fmt::format("CREATE {}INDEX ON {} USING BTREE ({}) {}", + m_build_unique_id_index ? "UNIQUE " : "", full_name(), id_column_names(), tablespace_clause(index_tablespace())); } diff --git a/src/flex-table.hpp b/src/flex-table.hpp index c1278f9f7..5fef823e1 100644 --- a/src/flex-table.hpp +++ b/src/flex-table.hpp @@ -195,6 +195,16 @@ class flex_table_t return m_always_build_id_index; } + void set_build_unique_id_index() noexcept + { + m_build_unique_id_index = true; + } + + bool build_unique_id_index() const noexcept + { + return m_build_unique_id_index; + } + bool has_columns_with_expire() const noexcept; std::size_t num() const noexcept { return m_table_num; } @@ -253,6 +263,9 @@ class flex_table_t /// Always build the id index, not only when it is needed for updates? bool m_always_build_id_index = false; + /// Build the index as a unique index. + bool m_build_unique_id_index = false; + }; // class flex_table_t class table_connection_t