Skip to content

Commit b5fd96b

Browse files
committed
LibSQL: Ungracefully handle database version incompatibilities
In the long run, this is obviously a bad way to handle version changes to the SQL database files. We will want to migrate old databases to new formats. Until we figure out a good way to do that, wipe old databases so that we don't crash trying to read incompatible data.
1 parent d5ed07f commit b5fd96b

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed

Tests/LibSQL/TestSqlDatabase.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ TEST_CASE(create_heap)
110110
ScopeGuard guard([]() { unlink("/tmp/test.db"); });
111111
auto heap = SQL::Heap::construct("/tmp/test.db");
112112
EXPECT(!heap->open().is_error());
113-
EXPECT_EQ(heap->version(), 0x00000001u);
113+
EXPECT_EQ(heap->version(), SQL::Heap::current_version);
114114
}
115115

116116
TEST_CASE(create_from_dev_random)

Userland/Libraries/LibSQL/Heap.cpp

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include <AK/Format.h>
99
#include <AK/QuickSort.h>
1010
#include <LibCore/IODevice.h>
11+
#include <LibCore/System.h>
1112
#include <LibSQL/Heap.h>
1213
#include <LibSQL/Serializer.h>
1314
#include <sys/stat.h>
@@ -58,6 +59,15 @@ ErrorOr<void> Heap::open()
5859
initialize_zero_block();
5960
}
6061

62+
// FIXME: We should more gracefully handle version incompatibilities. For now, we drop the database.
63+
if (m_version != current_version) {
64+
dbgln_if(SQL_DEBUG, "Heap file {} opened has incompatible version {}. Deleting for version {}.", name(), m_version, current_version);
65+
m_file = nullptr;
66+
67+
TRY(Core::System::unlink(name()));
68+
return open();
69+
}
70+
6171
dbgln_if(SQL_DEBUG, "Heap file {} opened. Size = {}", name(), size());
6272
return {};
6373
}
@@ -248,7 +258,7 @@ void Heap::update_zero_block()
248258

249259
void Heap::initialize_zero_block()
250260
{
251-
m_version = 0x00000001;
261+
m_version = current_version;
252262
m_schemas_root = 0;
253263
m_tables_root = 0;
254264
m_table_columns_root = 0;

Userland/Libraries/LibSQL/Heap.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ class Heap : public Core::Object {
3333
C_OBJECT(Heap);
3434

3535
public:
36+
static constexpr inline u32 current_version = 1;
37+
3638
virtual ~Heap() override;
3739

3840
ErrorOr<void> open();
@@ -104,7 +106,7 @@ class Heap : public Core::Object {
104106
u32 m_schemas_root { 0 };
105107
u32 m_tables_root { 0 };
106108
u32 m_table_columns_root { 0 };
107-
u32 m_version { 0x00000001 };
109+
u32 m_version { current_version };
108110
Array<u32, 16> m_user_values { 0 };
109111
HashMap<u32, ByteBuffer> m_write_ahead_log;
110112
};

0 commit comments

Comments
 (0)