Skip to content

Commit eeef678

Browse files
committed
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.
1 parent 2f35de5 commit eeef678

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

src/flex-lua-table.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,9 @@ static void parse_create_index(lua_State *lua_state, flex_table_t *table)
108108
lua_pop(lua_state, 1); // "create_index"
109109
if (create_index == "always") {
110110
table->set_always_build_id_index();
111+
} else if (create_index == "unique") {
112+
table->set_always_build_id_index();
113+
table->set_build_unique_id_index();
111114
} else if (create_index != "auto") {
112115
throw fmt_error("Unknown value '{}' for 'create_index' field of ids",
113116
create_index);

src/flex-table.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,8 @@ std::string flex_table_t::build_sql_column_list() const
226226

227227
std::string flex_table_t::build_sql_create_id_index() const
228228
{
229-
return fmt::format("CREATE INDEX ON {} USING BTREE ({}) {}", full_name(),
229+
return fmt::format("CREATE {}INDEX ON {} USING BTREE ({}) {}",
230+
m_build_unique_id_index ? "UNIQUE " : "", full_name(),
230231
id_column_names(),
231232
tablespace_clause(index_tablespace()));
232233
}

src/flex-table.hpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,16 @@ class flex_table_t
195195
return m_always_build_id_index;
196196
}
197197

198+
void set_build_unique_id_index() noexcept
199+
{
200+
m_build_unique_id_index = true;
201+
}
202+
203+
bool build_unique_id_index() const noexcept
204+
{
205+
return m_build_unique_id_index;
206+
}
207+
198208
bool has_columns_with_expire() const noexcept;
199209

200210
std::size_t num() const noexcept { return m_table_num; }
@@ -253,6 +263,9 @@ class flex_table_t
253263
/// Always build the id index, not only when it is needed for updates?
254264
bool m_always_build_id_index = false;
255265

266+
/// Build the index as a unique index.
267+
bool m_build_unique_id_index = false;
268+
256269
}; // class flex_table_t
257270

258271
class table_connection_t

0 commit comments

Comments
 (0)