Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
f35789f
feat(core): store parity surface for the Mac library
datlechin Nov 25, 2026
25686b8
feat(core-storage): the change journal names the records each commit …
datlechin Nov 25, 2026
af329cd
feat(core): six Safe Mode levels, optional tag colour and a kept SSH …
datlechin Nov 25, 2026
22c1763
feat(macos): connections, groups, tags and favourites in the core's s…
datlechin Nov 25, 2026
d5623d8
fix(macos): keep the core's library store trusted only on what TableP…
datlechin Nov 25, 2026
994dad6
test(macos): a failed record write changes the record, and the downgr…
datlechin Nov 25, 2026
ae4c86b
fix(macos): a core library file TablePro did not tag never wins over …
datlechin Nov 25, 2026
fef7c72
fix(macos): an absent connections.json never replaces the core's library
datlechin Nov 25, 2026
614bd44
fix(macos): record the core ahead of the mirror before writing it, an…
datlechin Nov 25, 2026
4e39c02
feat(ios): connection library on the core store models (#4608)
datlechin Nov 26, 2026
b40e760
perf(export): start an export from the catalog's row estimate, not an…
datlechin Nov 26, 2026
0ddc1f4
perf(export): read a dump's table DDL once per schema (#4592)
datlechin Nov 26, 2026
baf645f
perf(connections): read the catalog side kinds in one round trip per …
datlechin Nov 26, 2026
4643c81
perf(editor): bound the memory each document's undo history holds (#4…
datlechin Nov 26, 2026
b2791c6
perf(editor): answer attributedString() with the text storage (#4562)
datlechin Nov 26, 2026
c2524df
perf(connections): reconnect when the network returns and ping less w…
datlechin Nov 26, 2026
d1e2db4
feat(macos): saved queries and history on the core stores (#4611)
datlechin Nov 26, 2026
9c5bfa3
perf(autocomplete): run completion requests off the main thread with …
datlechin Nov 26, 2026
77cff41
perf(redis): page keys from a saved scan cursor and send cluster pipe…
datlechin Nov 26, 2026
9df1cb2
fix(core): replace_library refuses a file that changed since it was r…
datlechin Nov 26, 2026
c3faac7
Merge remote-tracking branch 'origin/integ/mac-engine' into feat/maco…
datlechin Nov 26, 2026
690a9ed
Merge remote-tracking branch 'origin/main' into feat/macos-core-libra…
datlechin Nov 26, 2026
cbd4712
feat(macos): the library writes over the digest it read, rebuilds unt…
datlechin Nov 26, 2026
85aa540
test(macos): a library write over a changed core file is refused, and…
datlechin Nov 26, 2026
c24f31b
feat(macos): after each sync pass the library reads what the core wro…
datlechin Nov 26, 2026
33e0af1
fix(macos): drop the saved queries' pull-apply stop guard, which went…
datlechin Nov 26, 2026
90c3e84
fix(macos): a file read after a sync pass stays untrusted, and rebuil…
datlechin Nov 26, 2026
bda4726
test(macos): the downgrade probe runs beside an installed TablePro
datlechin Nov 26, 2026
deecd35
fix(macos): no secret call before the library reads, and the mirror k…
datlechin Nov 26, 2026
297c6ca
test(macos): a connection a pull leaves unreadable and an unread favo…
datlechin Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 20 additions & 6 deletions .claude/rules/data-sync-storage.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import Foundation
import os
import TableProSQLGrammar
import TableProSQLQuoting

public final class SQLCompletionProvider {
// Sendable so a request runs off the caller's actor: an editor asks on the main thread, and analysis, the catalog
// reads and ranking would otherwise all run there, re-entering it after every catalog read.
public final class SQLCompletionProvider: Sendable {
private struct State {
var functionItems: [SQLCompletionItem]?
var favoriteKeywords: [String: (name: String, query: String)] = [:]
}

private let contextAnalyzer = SQLContextAnalyzer()
private let catalog: (any SQLCompletionCatalog)?
public private(set) var grammar: SQLLexicalGrammar
private var vocabulary: SQLCompletionVocabulary
private var cachedFunctionItems: [SQLCompletionItem]?
private var favoriteKeywords: [String: (name: String, query: String)] = [:]
public let grammar: SQLLexicalGrammar
private let vocabulary: SQLCompletionVocabulary
private let state = OSAllocatedUnfairLock(initialState: State())

private var favoriteKeywords: [String: (name: String, query: String)] {
state.withLock { $0.favoriteKeywords }
}

private let defaultMaxSuggestions = 20

Expand All @@ -32,14 +43,8 @@ public final class SQLCompletionProvider {
self.vocabulary = vocabulary
}

public func update(grammar: SQLLexicalGrammar, vocabulary: SQLCompletionVocabulary) {
self.grammar = grammar
self.vocabulary = vocabulary
self.cachedFunctionItems = nil
}

public func updateFavoriteKeywords(_ keywords: [String: (name: String, query: String)]) {
self.favoriteKeywords = keywords
state.withLock { $0.favoriteKeywords = keywords }
}

// `forcedTableReferences` stands in for the FROM clause when the caller already knows the table, as a
Expand All @@ -57,6 +62,9 @@ public final class SQLCompletionProvider {
return (session.items, session.context)
}

// Off the caller's actor from start to end, so a catalog read returns to this request, not to the caller.
// A request a newer one replaced stops between the steps that cost.
@concurrent
public func completionSession(
text: String,
cursorPosition: Int,
Expand All @@ -67,13 +75,17 @@ public final class SQLCompletionProvider {
context = context.replacingTableReferences(forcedTableReferences)
}

if context.isInsideString || context.isInsideComment {
if context.isInsideString || context.isInsideComment || Task.isCancelled {
return SQLCompletionSession(items: [], candidates: [], context: context, candidatesTruncated: false)
}

let limit = maxSuggestions(for: context.clauseType)
let candidates = await getCandidates(for: context)
guard !Task.isCancelled else {
return SQLCompletionSession(items: [], candidates: [], context: context, candidatesTruncated: false)
}
return await Self.rankedSession(
await getCandidates(for: context),
candidates,
context: context,
limit: limit,
pool: sessionPool(for: limit)
Expand Down Expand Up @@ -121,7 +133,7 @@ public final class SQLCompletionProvider {
private func sessionPool(for limit: Int) -> Int { limit * 10 }

private func functionItems() -> [SQLCompletionItem] {
if let cachedFunctionItems { return cachedFunctionItems }
if let cached = state.withLock({ $0.functionItems }) { return cached }
// The generic list writes SYSDATE() and CURRENT_DATE() too, which the engine may reject.
var items = SQLKeywords.functionItems().map { item in
guard vocabulary.bareFunctions.contains(item.label.uppercased()) else { return item }
Expand All @@ -136,8 +148,9 @@ public final class SQLCompletionProvider {
items.append(SQLCompletionItem.function(name, signature: signature, caseFolding: folding))
}
}
cachedFunctionItems = items
return items
let built = items
state.withLock { $0.functionItems = built }
return built
}

// MARK: - Candidate Generation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,13 @@ public enum SQLCompletionTriggerPolicy {
let semicolon = UInt16(UnicodeScalar(";").value)
let newline = UInt16(UnicodeScalar("\n").value)
guard previous == semicolon || previous == newline else { return false }
guard offset < text.length else { return true }

return text.substring(from: offset).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
// Stops at the first character that is not blank instead of copying the rest of the document.
var index = offset
while index < text.length {
guard let scalar = Unicode.Scalar(text.character(at: index)),
CharacterSet.whitespacesAndNewlines.contains(scalar) else { return false }
index += 1
}
return true
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ public struct SQLContext: Sendable {
)
}

public final class SQLContextAnalyzer {
public final class SQLContextAnalyzer: Sendable {
private static let newline = UInt16(UnicodeScalar("\n").value)
private static let openParen = UInt16(UnicodeScalar("(").value)
private static let closeParen = UInt16(UnicodeScalar(")").value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,15 @@ public struct SSLConfiguration: Codable, Hashable, Sendable {
caCertificatePath: String? = nil,
clientCertificatePath: String? = nil,
clientKeyPath: String? = nil,
isMacPreferred: Bool = false
isMacPreferred: Bool = false,
isLegacyRequire: Bool = false
) {
self.mode = mode
self.caCertificatePath = caCertificatePath
self.clientCertificatePath = clientCertificatePath
self.clientKeyPath = clientKeyPath
self.isMacPreferred = isMacPreferred && mode == .require
self.isLegacyRequire = false
self.isLegacyRequire = isLegacyRequire && mode == .require
}

// Same mode and paths, and the same Preferred, except that a copy an older iOS build stored takes the server's.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import Foundation

/// A key browse walked forward from a saved SCAN cursor, so the next page continues where the last one stopped
/// instead of scanning the keyspace again from the start.
///
/// SCAN returns keys in hash table order and may return a key twice, so the walk keeps every key it has seen, once,
/// in the order the pages were loaded. Each load is sorted on its own and appended: the rows of a page already shown
/// keep their place, and the order on screen covers the loaded keys only, which the status says.
nonisolated public struct RedisKeyBrowseWalk: Sendable {
/// What the walk lists: one database, MATCH pattern and TYPE. Any other scope is a new walk.
public struct Scope: Hashable, Sendable {
public let database: Int
public let pattern: String?
public let type: String?

public init(database: Int, pattern: String?, type: String?) {
self.database = database
self.pattern = pattern
self.type = type
}
}

public let scope: Scope
public private(set) var cursor: String = RedisClusterCursor.start
public private(set) var keys: [String] = []
public private(set) var isComplete = false
/// The offset of the page the walk last served. The same page asked for again is a reload, which starts over.
public var servedOffset: Int?
private var seen: Set<String> = []
private var loadStart = 0

public init(scope: Scope) {
self.scope = scope
}

/// Whether a page at `offset` continues this walk: a later or an earlier page does, the first page and the page
/// already on screen, which a refresh and a changed filter ask for, start a new one.
public func continues(atOffset offset: Int) -> Bool {
offset > 0 && offset != servedOffset
}

/// Whether a page ending at `end` needs more keys than the walk holds and the keyspace may still have them.
public func needsKeys(through end: Int) -> Bool {
!isComplete && keys.count < end
}

/// One SCAN reply. The server answers the start cursor once the walk is over.
public mutating func absorb(keys page: [String], nextCursor: String) {
for key in page where seen.insert(key).inserted {
keys.append(key)
}
cursor = nextCursor
if nextCursor == RedisClusterCursor.start { isComplete = true }
}

/// Sorts the keys loaded since the last call, leaving every earlier key where it was.
public mutating func finishLoad() {
if loadStart < keys.count { keys[loadStart...].sort() }
loadStart = keys.count
}

/// The keys of one page, empty past the end of what the walk loaded.
public func page(offset: Int, limit: Int) -> [String] {
let start = min(max(0, offset), keys.count)
let end = min(start + max(0, limit), keys.count)
return Array(keys[start..<end])
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,15 @@ public struct PublishedSSHRoute: Codable, Hashable, Sendable {
self.target = target
}

// A route as another store kept it, basis included, so reading it back never re-derives what was published.
public init(version: Int, publisher: UUID, basis: String, hops: [Hop], target: Target) {
self.version = version
self.publisher = publisher
self.basis = basis
self.hops = hops
self.target = target
}

public static let defaultPort = 22

public func describes(_ input: Input) -> Bool {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ struct StubCatalog: SQLCompletionCatalog {
var qualifiesInScope = false
// Like the iOS catalog, which quotes a mixed-case name itself because nothing spells it later.
var writesNames = false
// Runs where the provider reads the table list, which is where the request runs.
var onTableRead: (@Sendable () -> Void)?
let keyReads = KeyReads()

final class KeyReads: @unchecked Sendable {
Expand Down Expand Up @@ -61,7 +63,8 @@ struct StubCatalog: SQLCompletionCatalog {
}

func tableCompletionItems() -> [SQLCompletionItem] {
tables.map { SQLCompletionItem.table($0) }
onTableRead?()
return tables.map { SQLCompletionItem.table($0) }
}

func tableCompletionItems(inSchema schema: String) -> [SQLCompletionItem] {
Expand Down Expand Up @@ -505,6 +508,34 @@ struct SQLCompletionProviderIsolationTests {
#expect(session.items.first?.label == "orders")
#expect(executor.enqueuedJobs > 0)
}

// An editor asks on the main actor; analysis and the catalog reads must not run there, or each read re-enters
// the main queue behind the keystroke's own layout and drawing.
@Test("a request made on the main actor reads the catalog off the main thread")
func catalogReadsLeaveTheMainThread() async {
let reads = StubCatalog.KeyReads()
var catalog = StubCatalog(tables: ["orders"], columns: [:])
catalog.onTableRead = { reads.record(Thread.isMainThread ? "main" : "background") }
let provider = SQLCompletionProvider(catalog: catalog, grammar: .ansi, vocabulary: .generic)

let session = await provider.completionSession(text: "SELECT * FROM o", cursorPosition: 15)

#expect(session.items.contains { $0.label == "orders" })
#expect(reads.all == ["background"])
}

@Test("a cancelled request stops before it ranks")
func cancelledRequestStops() async {
let provider = SQLCompletionProvider(
catalog: StubCatalog(tables: ["orders"], columns: [:]), grammar: .ansi, vocabulary: .generic
)
let request = Task {
withUnsafeCurrentTask { $0?.cancel() }
return await provider.completionSession(text: "SELECT * FROM o", cursorPosition: 15)
}

#expect(await request.value.items.isEmpty)
}
}

// The caller's own actor never reaches it, so a job here is work that left the caller.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,17 @@ struct SSLConfigurationWireTests {
#expect(decoded == original)
}

@Test("An older build's require made by hand keeps its spelling in the device's own file, and only for require")
func legacyRequireMadeByHand() throws {
let legacy = TableProModels.SSLConfiguration(mode: .require, isLegacyRequire: true)
let encoder = JSONEncoder()
encoder.userInfo[.deviceLibraryFile] = true
let stored = try JSONDecoder().decode(TableProModels.SSLConfiguration.self, from: encoder.encode(legacy))
#expect(stored == legacy)
#expect(stored.isLegacyRequire)
#expect(!TableProModels.SSLConfiguration(mode: .verifyCa, isLegacyRequire: true).isLegacyRequire)
}

@Test("A Mac Preferred reads as require, writes back as Preferred, and a new mode replaces it")
func macPreferredRoundTrips() throws {
let blob = #"{"mode":"Preferred","caCertificatePath":"","clientCertificatePath":"","clientKeyPath":""}"#
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import Foundation
import TableProRedisCore
import Testing

struct RedisKeyBrowseWalkTests {
private static let scope = RedisKeyBrowseWalk.Scope(database: 0, pattern: "user:*", type: nil)

@Test("Each load is sorted on its own, so the rows of a page already shown keep their place")
func loadsKeepEarlierOrder() {
var walk = RedisKeyBrowseWalk(scope: Self.scope)
walk.absorb(keys: ["d", "b"], nextCursor: "17")
walk.absorb(keys: ["c"], nextCursor: "42")
walk.finishLoad()
#expect(walk.page(offset: 0, limit: 2) == ["b", "c"])
walk.absorb(keys: ["a", "e"], nextCursor: "0")
walk.finishLoad()
#expect(walk.keys == ["b", "c", "d", "a", "e"])
#expect(walk.page(offset: 0, limit: 2) == ["b", "c"])
#expect(walk.page(offset: 2, limit: 2) == ["d", "a"])
#expect(walk.isComplete)
}

@Test("A key SCAN returns twice is listed once")
func duplicatesAreDropped() {
var walk = RedisKeyBrowseWalk(scope: Self.scope)
walk.absorb(keys: ["a", "b", "a"], nextCursor: "5")
walk.absorb(keys: ["b", "c"], nextCursor: "0")
walk.finishLoad()
#expect(walk.keys == ["a", "b", "c"])
}

@Test("The walk asks for more only while the server may hold more and the page is not full")
func needsKeys() {
var walk = RedisKeyBrowseWalk(scope: Self.scope)
#expect(walk.needsKeys(through: 1))
walk.absorb(keys: ["a", "b"], nextCursor: "9")
#expect(!walk.needsKeys(through: 2))
#expect(walk.needsKeys(through: 3))
#expect(walk.cursor == "9")
walk.absorb(keys: [], nextCursor: "0")
#expect(!walk.needsKeys(through: 3))
}

@Test("A page past what the walk loaded is empty, never out of range")
func pagePastTheEnd() {
var walk = RedisKeyBrowseWalk(scope: Self.scope)
walk.absorb(keys: ["a"], nextCursor: "0")
walk.finishLoad()
#expect(walk.page(offset: 5, limit: 10).isEmpty)
#expect(walk.page(offset: -1, limit: 10) == ["a"])
#expect(walk.page(offset: 0, limit: 0).isEmpty)
}

@Test("A later or earlier page continues the walk; the first page and the page on screen start over")
func continuation() {
var walk = RedisKeyBrowseWalk(scope: Self.scope)
#expect(!walk.continues(atOffset: 0))
#expect(walk.continues(atOffset: 50))
walk.servedOffset = 50
#expect(!walk.continues(atOffset: 50))
#expect(walk.continues(atOffset: 100))
#expect(walk.continues(atOffset: 25))
#expect(!walk.continues(atOffset: 0))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
public protocol CodeSuggestionDelegate: AnyObject {
func completionTriggerCharacters() -> Set<String>

// Optional. In the turn of the key or command that asks, before the request starts; a request that only
// refreshes an open window, or asks again after one ends, does not call it.
func completionRequestDidBegin(textView: TextViewController)

func completionSuggestionsRequested(
textView: TextViewController,
cursorPosition: CursorPosition,
Expand Down Expand Up @@ -42,6 +46,7 @@ public protocol CodeSuggestionDelegate: AnyObject {

public extension CodeSuggestionDelegate {
func completionTriggerCharacters() -> Set<String> { [] }
func completionRequestDidBegin(textView: TextViewController) { }
func completionNeedsFreshItems(textView: TextViewController, cursorPosition: CursorPosition) -> Bool { false }
func completionWindowDidShow(textView: TextViewController, itemCount: Int) { }
func completionWindowDidClose() { }
Expand Down
Loading
Loading