@@ -59,9 +59,29 @@ final class QueryViewModel {
59 var columns: [String] = []
59 var columns: [String] = []
60 var columnOrder: [String] = []
60 var columnOrder: [String] = []
61 var hiddenColumns: Set<String> = []
61 var hiddenColumns: Set<String> = []
62+ /// The full persisted set of hidden columns for the current stream, including
63+ /// ones absent from the current result. Hiding a column drops it from the
64+ /// SELECT list, so it's missing from the very next result and `hiddenColumns`
65+ /// (only the columns present) forgets it — the next save would then erase the
66+ /// preference. This keeps the intent, mirroring LiveTailViewModel.
67+ private(set) var savedHiddenColumns: Set<String> = []
68+ /// The persisted column order including columns absent from the current
69+ /// result (the order counterpart of `savedHiddenColumns`), so saving doesn't
70+ /// drop a hidden column's position and it returns to its place when shown.
71+ private var savedColumnOrder: [String] = []
62 var autoHiddenColumns: Set<String> = []
72 var autoHiddenColumns: Set<String> = []
63 /// Column config from a saved query, applied on next query execution.
73 /// Column config from a saved query, applied on next query execution.
64 var pendingColumnConfig: ColumnConfiguration?
74 var pendingColumnConfig: ColumnConfiguration?
76+ /// The connection and stream the editor text and results belong to. The view
77+ /// model outlives QueryView (switching tabs keeps the query), so the view
78+ /// compares this on appear to catch a stream/server change made while another
80+ struct BoundContext: Equatable {
81+ let connectionID: UUID?
84+ var boundContext: BoundContext?
65 private var currentStream: String?
85 private var currentStream: String?
66 var isLoading = false
86 var isLoading = false
67 var errorMessage: String?
87 var errorMessage: String?
@@ -80,6 +100,11 @@ final class QueryViewModel {
80 /// The stream of the most recent `loadSchema` call, used to drop a stale
100 /// The stream of the most recent `loadSchema` call, used to drop a stale
81 /// in-flight response when the user rapidly switches streams.
101 /// in-flight response when the user rapidly switches streams.
82 private(set) var latestSchemaStream: String?
102 private(set) var latestSchemaStream: String?
103+ /// The stream of the most recent `executeQuery` call. Defense-in-depth
104+ /// alongside `queryGeneration`/task cancellation: drops a stale in-flight
105+ /// query response if a newer query for a different stream supersedes it
106+ /// without going through the normal cancel path.
107+ private var latestQueryStream: String?
84 // Query task for cancellation
109 // Query task for cancellation
85 private var queryTask: Task<Void, Never>?
110 private var queryTask: Task<Void, Never>?
@@ -187,9 +212,16 @@ final class QueryViewModel {
187 return columnOrder.filter { !allHidden.contains($0) }
212 return columnOrder.filter { !allHidden.contains($0) }
215+ /// Whether any column is hidden — including saved-hidden columns that aren't
216+ /// in the current result, which "Show All" can bring back.
217+ var hasHiddenColumns: Bool {
218+ !hiddenColumns.isEmpty || !autoHiddenColumns.isEmpty || !savedHiddenColumns.isEmpty
190 func toggleColumnVisibility(_ column: String) {
221 func toggleColumnVisibility(_ column: String) {
191 if hiddenColumns.contains(column) {
222 if hiddenColumns.contains(column) {
192 hiddenColumns.remove(column)
223 hiddenColumns.remove(column)
224+ savedHiddenColumns.remove(column)
193 } else if autoHiddenColumns.contains(column) {
225 } else if autoHiddenColumns.contains(column) {
194 autoHiddenColumns.remove(column)
226 autoHiddenColumns.remove(column)
@@ -198,6 +230,7 @@ final class QueryViewModel {
198 let visibleCount = columnOrder.count - allHidden.count
230 let visibleCount = columnOrder.count - allHidden.count
199 if visibleCount > 1 {
231 if visibleCount > 1 {
200 hiddenColumns.insert(column)
232 hiddenColumns.insert(column)
233+ savedHiddenColumns.insert(column)
203 saveColumnConfig()
236 saveColumnConfig()
@@ -206,6 +239,7 @@ final class QueryViewModel {
207 func showAllColumns() {
240 func showAllColumns() {
208 hiddenColumns.removeAll()
241 hiddenColumns.removeAll()
242+ savedHiddenColumns.removeAll()
209 autoHiddenColumns.removeAll()
243 autoHiddenColumns.removeAll()
210 saveColumnConfig()
244 saveColumnConfig()
211 updateSQLColumns()
245 updateSQLColumns()
@@ -235,32 +269,116 @@ final class QueryViewModel {
236 func resetColumnConfig() {
270 func resetColumnConfig() {
237 columnOrder = columns
271 columnOrder = columns
272+ savedColumnOrder = []
238 hiddenColumns.removeAll()
273 hiddenColumns.removeAll()
274+ savedHiddenColumns.removeAll()
239 autoHiddenColumns.removeAll()
275 autoHiddenColumns.removeAll()
240 saveColumnConfig()
276 saveColumnConfig()
241 updateSQLColumns()
277 updateSQLColumns()
244− /// Rewrites the SELECT clause of `sqlQuery` to reflect the current `visibleColumns`.
280+ /// Rewrites the SELECT clause of `sqlQuery` to reflect the user's column
281+ /// choices (order and hidden columns; auto-hidden columns stay display-only).
245 func updateSQLColumns() {
282 func updateSQLColumns() {
246− guard let range = SQLTokenizer.selectColumnListRange(in: sqlQuery) else { return }
283+ guard let range = SQLTokenizer.selectColumnListRange(in: sqlQuery),
247−
284+ let currentList = Self.parseColumnList(sqlQuery[range]) else { return }
248− let visible = visibleColumns
285+
286+ // Project the user's choices only. `autoHiddenColumns` is a display
287+ // heuristic for the current rows (the field is empty in all of them);
288+ // baking it into the SQL would stop the field from ever being fetched
289+ // again, even for a time range where it has values.
290+ let visible = columnOrder.filter { !hiddenColumns.contains($0) }
249 guard !visible.isEmpty else { return }
291 guard !visible.isEmpty else { return }
293+ // Columns an explicit list names that aren't in the results: Parseable
294+ // omits all-null fields from query JSON, so a sparse listed field can be
295+ // missing from `columns`. Keep it (unless the user hid it) rather than
296+ // silently dropping it from the SELECT on the next rewrite.
297+ var listedButAbsent: [String] = []
298+ var excludesHiddenColumn = false
299+ if case .identifiers(let names) = currentList {
300+ let present = Set(columns)
301+ listedButAbsent = names.filter { !present.contains($0) && !savedHiddenColumns.contains($0) }
302+ // A column the user hid is absent from these results precisely
303+ // because this list was narrowed to exclude it.
304+ excludesHiddenColumn = !savedHiddenColumns.isSubset(of: present)
251 let newColumnList: String
307 let newColumnList: String
252 // Use `*` whenever every column is visible, regardless of display order —
308 // Use `*` whenever every column is visible, regardless of display order —
253 // reordering columns (a set-preserving permutation) must not pin the query
309 // reordering columns (a set-preserving permutation) must not pin the query
254− // to an explicit snapshot that hides newly-appearing fields on re-query.
310+ // to an explicit snapshot that hides newly-appearing fields on re-query —
311+ // unless the list is explicit because it leaves out a hidden column, which
312+ // `*` would fetch again.
255− if visible.count == columns.count && Set(visible) == Set(columns) {
313+ if !excludesHiddenColumn && visible.count == columns.count && Set(visible) == Set(columns) {
256 newColumnList = "*"
314 newColumnList = "*"
258− newColumnList = visible.map { Self.escapeSQLIdentifier($0) }.joined(separator: ", ")
316+ newColumnList = (visible + listedButAbsent).map { Self.escapeSQLIdentifier($0) }.joined(separator: ", ")
261 sqlQuery.replaceSubrange(range, with: newColumnList)
319 sqlQuery.replaceSubrange(range, with: newColumnList)
322+ enum ColumnListShape: Equatable {
324+ /// Plain column references, as the column names they resolve to.
325+ case identifiers([String])
328+ /// Parses a SELECT list the column manager can regenerate without changing
329+ /// what the query computes: `*`, or a comma-separated list of plain column
330+ /// references. Anything else — aggregates, expressions, aliases
331+ /// (`count(*) AS n`), qualified names — returns nil: rewriting it with `*` or
332+ /// bare result keys would break the query, so the column manager then only
333+ /// hides/reorders client-side.
334+ nonisolated static func parseColumnList(_ list: Substring) -> ColumnListShape? {
335+ let tokens = SQLTokenizer.tokenize(String(list)).filter { !$0.kind.isTrivia }
336+ if tokens.count == 1, tokens[0].kind == .star { return .star }
337+ guard tokens.count % 2 == 1 else { return nil }
338+ var names: [String] = []
339+ for (index, token) in tokens.enumerated() {
341+ guard token.kind == .comma else { return nil }
345+ // DataFusion folds unquoted identifiers to lowercase.
346+ case .identifier(let name): names.append(name.lowercased())
347+ case .quotedIdentifier(let name): names.append(name)
351+ return .identifiers(names)
354+ /// Inserts `newColumns` into `order`, placing each one that appears in
355+ /// `reference` (a saved order) right after its nearest saved predecessor
356+ /// that's already placed — or first if none is — and appending the rest.
357+ /// Used to keep the positions of columns that are absent for a while.
358+ nonisolated static func mergedColumnOrder(
359+ _ order: [String], inserting newColumns: [String], reference: [String]
362+ let referenceIndex = Dictionary(reference.enumerated().map { ($1, $0) }, uniquingKeysWith: { first, _ in first })
363+ let pending = newColumns.filter { referenceIndex[$0] == nil }
364+ let positioned = newColumns
365+ .filter { referenceIndex[$0] != nil }
366+ .sorted { referenceIndex[$0]! < referenceIndex[$1]! }
367+ for column in positioned where !result.contains(column) {
368+ let savedIndex = referenceIndex[column]!
369+ let predecessor = reference[..<savedIndex].reversed().first { result.contains($0) }
370+ if let predecessor, let position = result.firstIndex(of: predecessor) {
371+ result.insert(column, at: position + 1)
373+ result.insert(column, at: 0)
376+ for column in pending where !result.contains(column) {
377+ result.append(column)
264 // MARK: - Column Configuration Persistence
382 // MARK: - Column Configuration Persistence
266 struct ColumnConfiguration: Codable {
384 struct ColumnConfiguration: Codable {
@@ -274,7 +392,16 @@ final class QueryViewModel {
275 private func saveColumnConfig() {
393 private func saveColumnConfig() {
276 guard let stream = currentStream else { return }
394 guard let stream = currentStream else { return }
395+ // Persist the full intended hidden set and order, not just the currently
396+ // present columns (see `savedHiddenColumns` / `savedColumnOrder`).
397+ let present = Set(columnOrder)
398+ let order = Self.mergedColumnOrder(
400+ inserting: savedColumnOrder.filter { !present.contains($0) },
401+ reference: savedColumnOrder
403+ savedColumnOrder = order
277− let config = ColumnConfiguration(order: columnOrder, hidden: hiddenColumns)
404+ let config = ColumnConfiguration(order: order, hidden: savedHiddenColumns.union(hiddenColumns))
278 if let data = try? JSONEncoder().encode(config) {
405 if let data = try? JSONEncoder().encode(config) {
279 UserDefaults.standard.set(data, forKey: Self.columnConfigKey(for: stream))
406 UserDefaults.standard.set(data, forKey: Self.columnConfigKey(for: stream))
@@ -303,7 +430,9 @@ final class QueryViewModel {
304 guard let config else {
431 guard let config else {
305 columnOrder = extractedColumns
432 columnOrder = extractedColumns
433+ savedColumnOrder = []
306 hiddenColumns = []
434 hiddenColumns = []
435+ savedHiddenColumns = []
@@ -316,6 +445,8 @@ final class QueryViewModel {
316 merged.append(col)
445 merged.append(col)
318 columnOrder = merged
447 columnOrder = merged
448+ savedColumnOrder = config.order
449+ savedHiddenColumns = config.hidden
319 hiddenColumns = config.hidden.intersection(extractedSet)
450 hiddenColumns = config.hidden.intersection(extractedSet)
321 // The `visibleCount > 1` guard in toggleColumnVisibility only covers
452 // The `visibleCount > 1` guard in toggleColumnVisibility only covers
@@ -415,6 +546,7 @@ final class QueryViewModel {
415 // the loading indicator during this query).
546 // the loading indicator during this query).
416 queryGeneration &+= 1
547 queryGeneration &+= 1
417 let generation = queryGeneration
548 let generation = queryGeneration
549+ latestQueryStream = stream
419 isLoading = true
551 isLoading = true
420 errorMessage = nil
552 errorMessage = nil
@@ -442,6 +574,9 @@ final class QueryViewModel {
442 // cancellation landing just after the check above would otherwise
574 // cancellation landing just after the check above would otherwise
443 // let a stale query clobber the newer one's results/columns.
575 // let a stale query clobber the newer one's results/columns.
444 guard !Task.isCancelled else { return }
576 guard !Task.isCancelled else { return }
577+ // Drop the response if a newer query (possibly for a different
578+ // stream) has since been launched without cancelling this task.
579+ guard latestQueryStream == stream else { return }
446 results = queryResults
581 results = queryResults
447 // Drop any prior row selection: the new result set reassigns row
582 // Drop any prior row selection: the new result set reassigns row
@@ -484,12 +619,23 @@ final class QueryViewModel {
485 } catch {
620 } catch {
486 guard !Task.isCancelled else { return }
621 guard !Task.isCancelled else { return }
622+ // Same supersession guard as the success path: a stale failed
623+ // query must not clobber a newer query's state.
624+ guard latestQueryStream == stream else { return }
487 errorMessage = ParseableError.userFriendlyMessage(for: error)
625 errorMessage = ParseableError.userFriendlyMessage(for: error)
488 if let serverError = error as? ParseableError,
626 if let serverError = error as? ParseableError,
489 case .serverError(_, let msg) = serverError,
627 case .serverError(_, let msg) = serverError,
490− let pos = SQLErrorPosition.parse(from: msg) {
628+ let pos = SQLErrorPosition.parse(from: msg),
630+ // The server's line/column is relative to the *submitted* SQL.
631+ // Only map it back into the editor when the editor still holds
632+ // that same text — if the user edited the query while it was in
633+ // flight, the position no longer corresponds to what's displayed
634+ // and would underline an unrelated span. (`sqlQuery`'s didSet
635+ // already cleared errorRange on that edit, so leaving it nil here
636+ // keeps the editor unmarked.)
491 errorRange = SQLTokenizer.errorHighlightRange(
637 errorRange = SQLTokenizer.errorHighlightRange(
492− line: pos.line, column: pos.column, in: sqlQuery
638+ line: pos.line, column: pos.column, in: sql
495 results = []
641 results = []
@@ -499,6 +645,8 @@ final class QueryViewModel {
499 // report stale column names after the failure.
645 // report stale column names after the failure.
500 columnOrder = []
646 columnOrder = []
501 hiddenColumns = []
647 hiddenColumns = []
648+ savedHiddenColumns = []
649+ savedColumnOrder = []
502 autoHiddenColumns = []
650 autoHiddenColumns = []
@@ -665,6 +813,8 @@ final class QueryViewModel {
665 columns = []
813 columns = []
666 columnOrder = []
814 columnOrder = []
667 hiddenColumns = []
815 hiddenColumns = []
816+ savedHiddenColumns = []
817+ savedColumnOrder = []
668 autoHiddenColumns = []
818 autoHiddenColumns = []
669 currentStream = nil
819 currentStream = nil
670 resultCount = 0
820 resultCount = 0
@@ -674,6 +824,11 @@ final class QueryViewModel {
674 errorRange = nil
824 errorRange = nil
675 resultsTruncated = false
825 resultsTruncated = false
676 schemaFields = []
826 schemaFields = []
827+ // Keep the stream trackers consistent with the cleared schema/results so
828+ // a later reload guard never sees a non-nil stream paired with empty data.
829+ latestSchemaStream = nil
830+ latestQueryStream = nil
679 /// Modifies `sqlQuery` to add a column-value filter condition.
834 /// Modifies `sqlQuery` to add a column-value filter condition.
@@ -683,75 +838,139 @@ final class QueryViewModel {
683 let condition: String
838 let condition: String
684 if let value, value != .null {
839 if let value, value != .null {
685 let literal = value.sqlLiteral
840 let literal = value.sqlLiteral
841+ // Exclude with `IS DISTINCT FROM`, not `<>`: under SQL's three-valued
842+ // logic `NULL <> 'x'` is NULL, so `<>` also dropped every row where the
843+ // column is missing/NULL — common for sparse fields — which "exclude
844+ // this value" doesn't ask for (the live-tail exclude keeps them too).
846+ ? "\(escapedCol) IS DISTINCT FROM \(literal)"
686− condition = exclude ? "\(escapedCol) <> \(literal)" : "\(escapedCol) = \(literal)"
847+ : "\(escapedCol) = \(literal)"
688 condition = exclude ? "\(escapedCol) IS NOT NULL" : "\(escapedCol) IS NULL"
849 condition = exclude ? "\(escapedCol) IS NOT NULL" : "\(escapedCol) IS NULL"
691− var sql = sqlQuery.trimmingCharacters(in: .whitespacesAndNewlines)
852+ let sql = sqlQuery.trimmingCharacters(in: .whitespacesAndNewlines)
692 if sql.isEmpty { return }
853 if sql.isEmpty { return }
694 // Locate the top-level WHERE and the first trailing clause using the
855 // Locate the top-level WHERE and the first trailing clause using the
695 // tokenizer rather than a raw regex, so keywords inside quoted
856 // tokenizer rather than a raw regex, so keywords inside quoted
696 // identifiers, string literals, comments, or subqueries are ignored.
857 // identifiers, string literals, comments, or subqueries are ignored.
697− let tailKeywords: Set<String> = ["ORDER", "GROUP", "HAVING", "LIMIT", "OFFSET"]
858+ let tokens = SQLTokenizer.tokenize(sql)
698 var depth = 0
859 var depth = 0
699− var whereEnd: String.Index?
860+ // WHERE and the trailing clauses only follow the top-level FROM. Keywords
700− var tailStart: String.Index?
861+ // before it belong to the SELECT list — e.g. a field named `offset` or
862+ // `limit` (which the tokenizer reports as keywords) — and must not be
863+ // mistaken for clause starts.
864+ var fromSeen = false
865+ var whereIndex: Int?
701 // Track whether the existing WHERE body has a top-level OR — only then does
867 // Track whether the existing WHERE body has a top-level OR — only then does
702 // AND-ing a new condition need parentheses to preserve precedence.
868 // AND-ing a new condition need parentheses to preserve precedence.
703 var bodyHasTopLevelOr = false
869 var bodyHasTopLevelOr = false
704− for token in SQLTokenizer.tokenize(sql) {
870+ // The last token that is actual SQL — not whitespace, a comment, or a
871+ // statement-terminating `;`. New text is spliced in right after such
872+ // tokens (never at the raw end of the string), so a trailing `;` or a
873+ // trailing `-- comment` stays at the end instead of swallowing the
874+ // appended condition: `... LIMIT 10;` must not become `... LIMIT 10; WHERE`,
875+ // and `... -- note` must not become `... -- note WHERE <commented out>`.
876+ func isSignificant(_ token: SQLTokenizer.Token) -> Bool {
877+ !token.kind.isTrivia && token.kind != .other(";")
879+ func nextSignificantKind(after index: Int) -> SQLTokenizer.TokenKind? {
880+ tokens[(index + 1)...].first(where: { isSignificant($0) })?.kind
882+ // Whether the keyword at `index` actually opens a trailing clause. ORDER and
883+ // GROUP must be followed by BY (so `WITHIN GROUP (…)` or a column named
884+ // `order` doesn't count), and LIMIT/OFFSET by their row count (so a column
885+ // named `offset` in `WHERE offset > 5` doesn't cut the WHERE body short).
886+ func startsTrailingClause(_ keyword: String, at index: Int) -> Bool {
888+ case "ORDER", "GROUP":
889+ return nextSignificantKind(after: index) == .keyword("BY")
890+ case "LIMIT", "OFFSET":
891+ if case .number = nextSignificantKind(after: index) { return true }
899+ var lastSignificant: Int?
900+ for (idx, token) in tokens.enumerated() {
901+ if isSignificant(token) { lastSignificant = idx }
705 switch token.kind {
902 switch token.kind {
706 case .leftParen:
903 case .leftParen:
707 depth += 1
904 depth += 1
708 case .rightParen:
905 case .rightParen:
709 depth = max(0, depth - 1)
906 depth = max(0, depth - 1)
907+ case .keyword("FROM") where depth == 0:
710− case .keyword(let kw) where depth == 0:
909+ case .keyword(let kw) where depth == 0 && fromSeen:
711− if kw == "WHERE", whereEnd == nil {
910+ if kw == "WHERE", whereIndex == nil {
712− whereEnd = token.range.upperBound
911+ whereIndex = idx
713− } else if tailKeywords.contains(kw), tailStart == nil {
912+ // A trailing clause seen *before* the WHERE (e.g. the GROUP BY of
714− tailStart = token.range.lowerBound
913+ // the first SELECT in `... GROUP BY a UNION ALL SELECT ... WHERE`)
914+ // doesn't end this WHERE's body. Keeping it would make the body
915+ // range run backwards (a trapping `Range`), so look for the
916+ // body's end afresh after the WHERE.
918+ } else if tailIndex == nil, startsTrailingClause(kw, at: idx) {
715− } else if kw == "OR", whereEnd != nil, tailStart == nil {
920+ } else if kw == "OR", whereIndex != nil, tailIndex == nil {
716 bodyHasTopLevelOr = true
921 bodyHasTopLevelOr = true
722−
927+ // Nothing but comments/semicolons — there's no statement to filter.
723− if let whereEnd {
928+ guard let lastSignificant else { return }
930+ // Each branch rebuilds the query from slices of the original text, keeping
931+ // the user's line breaks: joining pieces with single spaces would pull the
932+ // text after a `-- comment` onto the comment's line and comment it out.
933+ // Text spliced directly in front of another token (`(a = 1)ORDER BY`) needs
934+ // a space so the two don't fuse (`... IS NULLORDER BY`).
935+ func separated(_ rest: Substring) -> String {
936+ guard let next = rest.first, !next.isWhitespace, next != ";" else { return String(rest) }
940+ // The WHERE body runs up to the first trailing clause, or to the end
941+ // of the statement. Only its significant tokens bound the splice, so a
942+ // comment between the body and ORDER BY stays after the new condition.
943+ let bodyEndIndex = tailIndex ?? (lastSignificant + 1)
944+ let bodyIndices = (whereIndex + 1)..<bodyEndIndex
945+ if let first = bodyIndices.first(where: { isSignificant(tokens[$0]) }),
946+ let last = bodyIndices.last(where: { isSignificant(tokens[$0]) }) {
724− // Parenthesize the existing WHERE body before AND-ing the new
947+ // Parenthesize the existing WHERE body before AND-ing the new
725− // condition only when it has a top-level OR, otherwise the OR
948+ // condition only when it has a top-level OR, otherwise the OR
726− // silently changes meaning: `WHERE a = 1 OR b = 2` would become
949+ // silently changes meaning: `WHERE a = 1 OR b = 2` would become
727− // `WHERE a = 1 OR b = 2 AND c = 3`, which SQL binds as
950+ // `WHERE a = 1 OR b = 2 AND c = 3`, which SQL binds as
728− // `a = 1 OR (b = 2 AND c = 3)` rather than the intended
951+ // `a = 1 OR (b = 2 AND c = 3)` rather than the intended
729− // `(a = 1 OR b = 2) AND c = 3`. A body without a top-level OR is
952+ // `(a = 1 OR b = 2) AND c = 3`. A body without a top-level OR is
730− // left un-parenthesized so simple filters stay readable.
953+ // left un-parenthesized so simple filters stay readable.
731− let bodyEnd = tailStart ?? sql.endIndex
954+ let bodyStart = tokens[first].range.lowerBound
732− let head = sql[..<whereEnd]
955+ let bodyEnd = tokens[last].range.upperBound
733− let body = sql[whereEnd..<bodyEnd].trimmingCharacters(in: .whitespacesAndNewlines)
956+ let body = sql[bodyStart..<bodyEnd]
734− let tail = sql[bodyEnd...].trimmingCharacters(in: .whitespacesAndNewlines)
957+ let wrappedBody = bodyHasTopLevelOr ? "(\(body))" : String(body)
735− // An empty WHERE body (e.g. a half-written `... WHERE` with no
958+ sqlQuery = "\(sql[..<bodyStart])\(wrappedBody) AND \(condition)\(separated(sql[bodyEnd...]))"
736− // condition yet, or `WHERE` immediately followed by ORDER/GROUP/
737− // LIMIT) would otherwise produce `WHERE AND <condition>` — a
738− // dangling AND with no left operand. Drop the AND in that case.
740− sql = "\(head) \(condition)"
742− let wrappedBody = bodyHasTopLevelOr ? "(\(body))" : body
960+ // An empty WHERE body (e.g. a half-written `... WHERE` with no
743− sql = "\(head) \(wrappedBody) AND \(condition)"
961+ // condition yet, or `WHERE` immediately followed by ORDER/GROUP/
962+ // LIMIT) would otherwise produce `WHERE AND <condition>` — a
963+ // dangling AND with no left operand. Drop the AND in that case.
964+ let whereEnd = tokens[whereIndex].range.upperBound
965+ sqlQuery = "\(sql[..<whereEnd]) \(condition)\(separated(sql[whereEnd...]))"
748− } else if let tailStart {
967+ } else if let tailIndex {
968+ let tailStart = tokens[tailIndex].range.lowerBound
749− sql.insert(contentsOf: "WHERE \(condition) ", at: tailStart)
969+ sqlQuery = "\(sql[..<tailStart])WHERE \(condition) \(sql[tailStart...])"
751− sql += " WHERE \(condition)"
971+ let statementEnd = tokens[lastSignificant].range.upperBound
972+ sqlQuery = "\(sql[..<statementEnd]) WHERE \(condition)\(separated(sql[statementEnd...]))"
757 /// Sets the default query for the given stream, returning `true` if the
976 /// Sets the default query for the given stream, returning `true` if the
@@ -795,6 +1014,10 @@ final class QueryViewModel {
795 // MARK: - Query History
1014 // MARK: - Query History
797 private func addToHistory(_ entry: QueryHistoryEntry) {
1016 private func addToHistory(_ entry: QueryHistoryEntry) {
1017+ // Start from what's persisted, not this instance's copy: a model created
1018+ // earlier (e.g. one whose query finished after a reconnect replaced it)
1019+ // would otherwise overwrite newer entries saved by the current one.
1020+ queryHistory = Self.loadHistory()
798 // Deduplicate consecutive identical queries
1021 // Deduplicate consecutive identical queries
799 if queryHistory.first?.sql == entry.sql { return }
1022 if queryHistory.first?.sql == entry.sql { return }
800 queryHistory.insert(entry, at: 0)
1023 queryHistory.insert(entry, at: 0)