Skip to content

Commit 125daf9

Browse files
committed
refactor: compose native SQLite bootstrap tables
1 parent 98410d9 commit 125daf9

2 files changed

Lines changed: 142 additions & 31 deletions

File tree

‎apps/shared/OpenClawKit/Sources/OpenClawKit/DeviceIdentitySQLiteStore.swift‎

Lines changed: 56 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,20 @@ enum DeviceIdentitySQLiteStore {
7878
}
7979
}
8080

81+
private struct SchemaObject: Hashable {
82+
let type: String
83+
let name: String
84+
}
85+
86+
/// Native stores may seed their canonical tables before Node expands the shared schema.
87+
/// Keep names closed here; each store separately validates the exact shape it owns.
88+
private static let nativeBootstrapSchemaObjects: Set<SchemaObject> = [
89+
SchemaObject(type: "index", name: "idx_device_identities_device"),
90+
SchemaObject(type: "index", name: "idx_macos_port_guardian_records_port"),
91+
SchemaObject(type: "table", name: "device_identities"),
92+
SchemaObject(type: "table", name: "macos_port_guardian_records"),
93+
]
94+
8195
static func loadOrCreate(
8296
databaseURL: URL,
8397
destinationStateDirURL: URL,
@@ -329,12 +343,10 @@ enum DeviceIdentitySQLiteStore {
329343
}
330344

331345
if try !self.schemaObjectExists(database, type: "table", name: self.tableName) {
332-
let objectCount = try self.queryInt64(
333-
database,
334-
sql: "SELECT COUNT(*) FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%'")
335-
guard allowFreshCreation, userVersion == 0, objectCount == 0 else {
346+
guard allowFreshCreation, userVersion == 0 else {
336347
throw DeviceIdentityStore.storageError("Nonempty OpenClaw database is missing device_identities")
337348
}
349+
try self.validateVersionZeroDatabaseOwnership(database, requireIdentityObjects: false)
338350
try self.execute(database, sql: self.createSchemaSQL)
339351
}
340352
try self.validateDatabaseOwnership(database, userVersion: userVersion)
@@ -370,33 +382,7 @@ enum DeviceIdentitySQLiteStore {
370382
userVersion: Int64) throws
371383
{
372384
if userVersion == 0 {
373-
let statement = try self.prepare(
374-
database,
375-
sql: """
376-
SELECT type, name
377-
FROM sqlite_schema
378-
WHERE name NOT LIKE 'sqlite_%'
379-
ORDER BY type, name
380-
""")
381-
defer { sqlite3_finalize(statement) }
382-
var objects: [(String, String)] = []
383-
while true {
384-
let result = sqlite3_step(statement)
385-
if result == SQLITE_DONE { break }
386-
guard result == SQLITE_ROW else {
387-
throw self.databaseError(database, operation: "validate Swift identity database ownership")
388-
}
389-
try objects.append((
390-
self.requiredText(statement, column: 0, field: "schema object type"),
391-
self.requiredText(statement, column: 1, field: "schema object name")))
392-
}
393-
guard objects.count == 2,
394-
objects[0].0 == "index", objects[0].1 == self.indexName,
395-
objects[1].0 == "table", objects[1].1 == self.tableName
396-
else {
397-
throw DeviceIdentityStore.storageError(
398-
"Schema version zero database contains objects not owned by the Swift identity store")
399-
}
385+
try self.validateVersionZeroDatabaseOwnership(database, requireIdentityObjects: true)
400386
return
401387
}
402388

@@ -415,6 +401,45 @@ enum DeviceIdentitySQLiteStore {
415401
}
416402
}
417403

404+
private static func validateVersionZeroDatabaseOwnership(
405+
_ database: OpaquePointer,
406+
requireIdentityObjects: Bool) throws
407+
{
408+
let statement = try self.prepare(
409+
database,
410+
sql: """
411+
SELECT type, name
412+
FROM sqlite_schema
413+
WHERE name NOT LIKE 'sqlite_%'
414+
ORDER BY type, name
415+
""")
416+
defer { sqlite3_finalize(statement) }
417+
var objects = Set<SchemaObject>()
418+
while true {
419+
let result = sqlite3_step(statement)
420+
if result == SQLITE_DONE { break }
421+
guard result == SQLITE_ROW else {
422+
throw self.databaseError(database, operation: "validate native state database ownership")
423+
}
424+
try objects.insert(SchemaObject(
425+
type: self.requiredText(statement, column: 0, field: "schema object type"),
426+
name: self.requiredText(statement, column: 1, field: "schema object name")))
427+
}
428+
guard objects.isSubset(of: self.nativeBootstrapSchemaObjects) else {
429+
throw DeviceIdentityStore.storageError(
430+
"Schema version zero database contains objects not owned by a native OpenClaw store")
431+
}
432+
if requireIdentityObjects {
433+
let required: Set<SchemaObject> = [
434+
SchemaObject(type: "index", name: self.indexName),
435+
SchemaObject(type: "table", name: self.tableName),
436+
]
437+
guard required.isSubset(of: objects) else {
438+
throw DeviceIdentityStore.storageError("Schema version zero database is missing device identity objects")
439+
}
440+
}
441+
}
442+
418443
private static func tableColumns(_ database: OpaquePointer) throws -> [Column] {
419444
let statement = try self.prepare(database, sql: "PRAGMA table_xinfo('device_identities')")
420445
defer { sqlite3_finalize(statement) }
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import Foundation
2+
import SQLite3
3+
import Testing
4+
@testable import OpenClawKit
5+
6+
struct NativeStateBootstrapTests {
7+
@Test
8+
func `version zero database composes identity and port guardian tables`() throws {
9+
let tempDir = FileManager.default.temporaryDirectory
10+
.appendingPathComponent(UUID().uuidString, isDirectory: true)
11+
defer { try? FileManager.default.removeItem(at: tempDir) }
12+
let databaseURL = tempDir.appendingPathComponent("openclaw.sqlite", isDirectory: false)
13+
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
14+
try Self.execute(databaseURL, """
15+
CREATE TABLE macos_port_guardian_records (
16+
pid INTEGER NOT NULL PRIMARY KEY,
17+
port INTEGER NOT NULL,
18+
command TEXT NOT NULL,
19+
mode TEXT NOT NULL,
20+
timestamp REAL NOT NULL
21+
) STRICT;
22+
CREATE INDEX idx_macos_port_guardian_records_port
23+
ON macos_port_guardian_records(port, timestamp DESC);
24+
INSERT INTO macos_port_guardian_records VALUES (4242, 18789, '/usr/bin/ssh', 'remote', 42.5);
25+
""")
26+
27+
_ = try DeviceIdentityStore.loadOrCreate(
28+
databaseURL: databaseURL,
29+
destinationStateDirURL: tempDir,
30+
profile: .primary)
31+
32+
#expect(try Self.scalarInt(databaseURL, "PRAGMA user_version") == 0)
33+
#expect(try Self.scalarInt(
34+
databaseURL,
35+
"SELECT COUNT(*) FROM macos_port_guardian_records WHERE pid = 4242") == 1)
36+
#expect(try Self.scalarText(
37+
databaseURL,
38+
"""
39+
SELECT group_concat(type || ':' || name, ',')
40+
FROM (SELECT type, name FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name)
41+
""") == "index:idx_device_identities_device,index:idx_macos_port_guardian_records_port," +
42+
"table:device_identities,table:macos_port_guardian_records")
43+
}
44+
45+
private static func execute(_ databaseURL: URL, _ sql: String) throws {
46+
var database: OpaquePointer?
47+
guard sqlite3_open(databaseURL.path, &database) == SQLITE_OK, let database else {
48+
throw DeviceIdentityStore.storageError("Could not open test database")
49+
}
50+
defer { sqlite3_close(database) }
51+
guard sqlite3_exec(database, sql, nil, nil, nil) == SQLITE_OK else {
52+
throw DeviceIdentityStore.storageError(String(cString: sqlite3_errmsg(database)))
53+
}
54+
}
55+
56+
private static func scalarInt(_ databaseURL: URL, _ sql: String) throws -> Int64 {
57+
try self.scalar(databaseURL, sql) { sqlite3_column_int64($0, 0) }
58+
}
59+
60+
private static func scalarText(_ databaseURL: URL, _ sql: String) throws -> String? {
61+
try self.scalar(databaseURL, sql) { statement in
62+
sqlite3_column_text(statement, 0).map { String(cString: $0) }
63+
}
64+
}
65+
66+
private static func scalar<T>(
67+
_ databaseURL: URL,
68+
_ sql: String,
69+
transform: (OpaquePointer) -> T) throws -> T
70+
{
71+
var database: OpaquePointer?
72+
guard sqlite3_open(databaseURL.path, &database) == SQLITE_OK, let database else {
73+
throw DeviceIdentityStore.storageError("Could not open test database")
74+
}
75+
defer { sqlite3_close(database) }
76+
var statement: OpaquePointer?
77+
guard sqlite3_prepare_v2(database, sql, -1, &statement, nil) == SQLITE_OK, let statement else {
78+
throw DeviceIdentityStore.storageError(String(cString: sqlite3_errmsg(database)))
79+
}
80+
defer { sqlite3_finalize(statement) }
81+
guard sqlite3_step(statement) == SQLITE_ROW else {
82+
throw DeviceIdentityStore.storageError(String(cString: sqlite3_errmsg(database)))
83+
}
84+
return transform(statement)
85+
}
86+
}

0 commit comments

Comments
 (0)