Sqlite: Add unique index to table

Some times we need the constraint for an index.

Change-Id: I81332238d36b88196ef03e26b4edcc1307de46e0
Reviewed-by: Ivan Donchevskii <ivan.donchevskii@qt.io>
This commit is contained in:
Marco Bubke
2018-01-30 15:13:52 +01:00
parent c29ae225c5
commit c6f65e94c8
4 changed files with 51 additions and 3 deletions

View File

@@ -34,12 +34,21 @@
namespace Sqlite {
enum class IndexType
{
Normal,
Unique
};
class Index
{
public:
Index(Utils::SmallString &&tableName, Utils::SmallStringVector &&columnNames)
Index(Utils::SmallString &&tableName,
Utils::SmallStringVector &&columnNames,
IndexType indexType=IndexType::Normal)
: m_tableName(std::move(tableName)),
m_columnNames(std::move(columnNames))
m_columnNames(std::move(columnNames)),
m_indexType(indexType)
{
}
@@ -48,7 +57,9 @@ public:
checkTableName();
checkColumns();
return {"CREATE INDEX IF NOT EXISTS index_",
return {"CREATE ",
m_indexType == IndexType::Unique ? "UNIQUE " : "",
"INDEX IF NOT EXISTS index_",
m_tableName,
"_",
m_columnNames.join("_"),
@@ -75,6 +86,7 @@ public:
private:
Utils::SmallString m_tableName;
Utils::SmallStringVector m_columnNames;
IndexType m_indexType;
};
using SqliteIndices = std::vector<Index>;

View File

@@ -90,6 +90,15 @@ public:
return m_sqliteIndices.back();
}
Index &addUniqueIndex(const SqliteColumnConstReferences &columns)
{
m_sqliteIndices.emplace_back(m_tableName.clone(),
sqliteColumnNames(columns),
IndexType::Unique);
return m_sqliteIndices.back();
}
const SqliteColumns &columns() const
{
return m_sqliteColumns;

View File

@@ -31,6 +31,7 @@ namespace {
using Sqlite::Exception;
using Sqlite::Index;
using Sqlite::IndexType;
TEST(Index, OneColumn)
{
@@ -63,4 +64,13 @@ TEST(Index, EmptyColumns)
ASSERT_THROW(index.sqlStatement(), Exception);
}
TEST(Index, UniqueIndex)
{
Index index{"tableName", {"column1"}, IndexType::Unique};
auto sqlStatement = index.sqlStatement();
ASSERT_THAT(sqlStatement, Eq("CREATE UNIQUE INDEX IF NOT EXISTS index_tableName_column1 ON tableName(column1)"));
}
}

View File

@@ -110,4 +110,21 @@ TEST_F(SqliteTable, InitializeTableWithIndex)
table.initialize(mockDatabase);
}
TEST_F(SqliteTable, InitializeTableWithUniqueIndex)
{
InSequence sequence;
table.setName(tableName.clone());
auto &column = table.addColumn("name");
auto &column2 = table.addColumn("value");
table.addUniqueIndex({column});
table.addIndex({column2});
EXPECT_CALL(mockDatabase, execute(Eq("CREATE TABLE testTable(name NUMERIC, value NUMERIC)")));
EXPECT_CALL(mockDatabase, execute(Eq("CREATE UNIQUE INDEX IF NOT EXISTS index_testTable_name ON testTable(name)")));
EXPECT_CALL(mockDatabase, execute(Eq("CREATE INDEX IF NOT EXISTS index_testTable_value ON testTable(value)")));
table.initialize(mockDatabase);
}
}