diff --git a/apple/TablePro/Core/Coordinators/FindCoordinator.swift b/apple/TablePro/Core/Coordinators/FindCoordinator.swift index 8cb4e3aeaf..d1ced34cf0 100644 --- a/apple/TablePro/Core/Coordinators/FindCoordinator.swift +++ b/apple/TablePro/Core/Coordinators/FindCoordinator.swift @@ -48,7 +48,9 @@ final class FindCoordinator { parent.supportsMatchAnyFilters, tab.filterState.filters.isEmpty else { return false } let rows = parent.tabSessionRegistry.tableRows(for: tabID) - return tab.pagination.hasUnloadedRows(loadedRowCount: rows.rows.count) && !serverSearchableColumns(in: rows).isEmpty + // The server searches a cut value whole, where the page holds only its first characters. + let pageIsPartial = tab.pagination.hasUnloadedRows(loadedRowCount: rows.rows.count) || rows.hasUnloadedValues + return pageIsPartial && !serverSearchableColumns(in: rows).isEmpty } // Its own filter rows: addFilter would apply the user's default-column setting. diff --git a/apple/TablePro/Core/Coordinators/PaginationCoordinator+CappedRead.swift b/apple/TablePro/Core/Coordinators/PaginationCoordinator+CappedRead.swift index b9a92f8a9a..3a9744b93d 100644 --- a/apple/TablePro/Core/Coordinators/PaginationCoordinator+CappedRead.swift +++ b/apple/TablePro/Core/Coordinators/PaginationCoordinator+CappedRead.swift @@ -37,11 +37,11 @@ extension PaginationCoordinator { if let denial = decision.denialError { throw denial } let isTableTab = tab.tabType == .table - let lengthColumns = isTableTab ? parent.unloadedValueLengthColumns(for: tab, sql: query) : [] + let unloadedLayout = isTableTab ? parent.unloadedValueLayout(for: tab, sql: query) : nil let safeModeIsReadOnly = parent.runsAtReadOnly return try await parent.withExecutionDriver(scope: scope, isTableTab: isTableTab, lease: DriverLeaseOwner()) { driver in let values = parameters.map { $0.map { $0 as Any? } } - let result: QueryResult + var result: QueryResult if let context = driver.readOnlyRunContext(safeModeIsReadOnly: safeModeIsReadOnly) { result = try await driver.executeUserQuery( query: query, rowCap: rowCap, parameters: values, context: context @@ -49,7 +49,8 @@ extension PaginationCoordinator { } else { result = try await driver.executeUserQuery(query: query, rowCap: rowCap, parameters: values) } - return result.foldingUnloadedValues(lengthColumns: lengthColumns) + result.foldUnloadedValues(unloadedLayout) + return result } } } diff --git a/apple/TablePro/Core/Coordinators/PaginationCoordinator.swift b/apple/TablePro/Core/Coordinators/PaginationCoordinator.swift index 9768c14289..3efd4f3c09 100644 --- a/apple/TablePro/Core/Coordinators/PaginationCoordinator.swift +++ b/apple/TablePro/Core/Coordinators/PaginationCoordinator.swift @@ -321,7 +321,7 @@ final class PaginationCoordinator: ObservableObject { let owner = TabQueryTaskOwner.unclaimedWork(tabId: tabId, token: workToken) let lease = DriverLeaseOwner() let isTableTab = parent.tabManager.tabs[idx].tabType == .table - let lengthColumns = isTableTab ? parent.unloadedValueLengthColumns(for: parent.tabManager.tabs[idx], sql: baseQuery) : [] + let unloadedLayout = isTableTab ? parent.unloadedValueLayout(for: parent.tabManager.tabs[idx], sql: baseQuery) : nil let failureOutput = ServerOutputBox() let safeModeIsReadOnly = parent.runsAtReadOnly @@ -371,14 +371,15 @@ final class PaginationCoordinator: ObservableObject { } return try await driver.executeUserQuery(query: baseQuery, rowCap: nil, parameters: parameters) } - let result: QueryResult + var result: QueryResult if isTableTab { // A table tab's own reads print nothing, as on its first page. result = try await rerun() } else { result = try await ServerOutputCapture.running(on: driver, failureOutput: failureOutput, rerun) } - return result.foldingUnloadedValues(lengthColumns: lengthColumns) + result.foldUnloadedValues(unloadedLayout) + return result } let fetchTime = CFAbsoluteTimeGetCurrent() - start progressLog.info("[fetchAll] rows=\(result.rows.count) fetchTime=\(String(format: "%.3f", fetchTime))s") diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+SingleRun.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+SingleRun.swift index d4da50adb0..72e9ed3a11 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+SingleRun.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+SingleRun.swift @@ -93,7 +93,7 @@ extension QueryExecutionCoordinator { } let isTableTab = tab.tabType == .table let readsView = tab.tableContext.knowsView(named: tableName) - let (grammar, lengthColumns) = (parent.lexicalGrammar, parent.unloadedValueLengthColumns(for: tab, sql: sql)) + let (grammar, unloadedLayout) = (parent.lexicalGrammar, parent.unloadedValueLayout(for: tab, sql: sql)) let safeModeIsReadOnly = parent.runsAtReadOnly let held = parent.manualCommitRun(skipped: isTableTab || isAutoLoad) let bound = request.bound @@ -130,7 +130,7 @@ extension QueryExecutionCoordinator { lease: run.lease ) { [queryExecutor = parent.queryExecutor, manager = parent.services.databaseManager] driver in leaseTiming?.noteQueryStarted() - let fetched = try await held.running([statement.sql], on: driver) { + var fetched = try await held.running([statement.sql], on: driver) { // Before it runs, so a statement that fails or a connection lost under it is still noted. if !isAutoLoad { await manager.noteSessionStatements([statement.sql], ranOn: driver, scope: scope) } return try await queryExecutor.executeQuery( @@ -145,7 +145,8 @@ extension QueryExecutionCoordinator { let edits = isAutoLoad ? nil : await SucceededStatements.single( statement.sql, scope: scope, databaseType: conn.type, grammar: grammar, ranOn: driver ) - return (fetched.foldingUnloadedValues(lengthColumns: lengthColumns), edits) + fetched.foldUnloadedValues(unloadedLayout) + return (fetched, edits) } } let fetchEndedAt = ContinuousClock.now diff --git a/apple/TablePro/Core/DataGrid/DataGridPrewarmWindow.swift b/apple/TablePro/Core/DataGrid/DataGridPrewarmWindow.swift index 552135903c..7b74fddcc7 100644 --- a/apple/TablePro/Core/DataGrid/DataGridPrewarmWindow.swift +++ b/apple/TablePro/Core/DataGrid/DataGridPrewarmWindow.swift @@ -68,6 +68,8 @@ struct DataGridPrewarmBatch: Sendable { static let rowLimit = 32 let rows: [Row] + // A cut text holds NULL in its row and shows its first characters, which the rows keep beside their values. + var unloadedHeads: [RowID: [Int: String]] = [:] let columnCount: Int let columnTypes: [ColumnType] let formats: [ValueDisplayFormat?] @@ -86,16 +88,18 @@ struct DataGridPrewarmBatch: Sendable { formatted.reserveCapacity(rows.count) for row in rows where !Task.isCancelled { let box = RowDisplayBox(ContiguousArray(repeating: nil, count: columnCount)) + let heads = unloadedHeads[row.id] ?? [:] for dataIndex in 0.. String? { - PluginMetadataRegistry.shared.snapshot(for: databaseType)?.capabilities.binaryLengthFunction + func largeValueFunctions(for databaseType: DatabaseType) -> LargeValueFunctions? { + PluginMetadataRegistry.shared.snapshot(for: databaseType)?.capabilities.largeValueFunctions } func readsCheckListsFromDDL(for databaseType: DatabaseType) -> Bool { diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CuratedDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CuratedDefaults.swift index cacc0dfefc..d81a90e6d1 100644 --- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CuratedDefaults.swift +++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CuratedDefaults.swift @@ -249,7 +249,7 @@ extension PluginMetadataRegistry { supportsDatabaseTriggerBrowse: true, defaultSSLMode: .preferred, browsingRequiresSelectedDatabase: true, - binaryLengthFunction: "OCTET_LENGTH", + largeValueFunctions: .mySQL, readsCheckListsFromDDL: false, readOnlyEnforcement: .sessionDefault ), @@ -322,7 +322,7 @@ extension PluginMetadataRegistry { supportsDatabaseTriggerBrowse: true, defaultSSLMode: .preferred, browsingRequiresSelectedDatabase: true, - binaryLengthFunction: "OCTET_LENGTH", + largeValueFunctions: .mySQL, readsCheckListsFromDDL: false, readOnlyEnforcement: .sessionDefault ), @@ -403,6 +403,7 @@ extension PluginMetadataRegistry { supportsUserDefinedTypeBrowse: true, defaultSSLMode: .preferred, verifiesServerWithSystemTrust: true, + largeValueFunctions: .postgreSQL, readsCheckListsFromDDL: false, readOnlyEnforcement: .sessionDefault ), @@ -689,6 +690,7 @@ extension PluginMetadataRegistry { newDatabaseFileExtensions: Self.sqliteFileExtensions, supportsRemoteDatabaseFile: true, supportsRemoteDatabaseSession: true, + largeValueFunctions: .sqlite, readsCheckListsFromDDL: false, readOnlyEnforcement: .engineEnforced ), diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+KingbaseESDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+KingbaseESDefaults.swift index 04b2757831..2911ed8f12 100644 --- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+KingbaseESDefaults.swift +++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+KingbaseESDefaults.swift @@ -17,7 +17,10 @@ extension PluginMetadataRegistry { /// KingbaseES runs PostgreSQL's catalogs and wire protocol, so its entry is PostgreSQL's with its own identity /// and without the cloud and Kerberos sign-in fields, which its servers do not offer. static func kingbaseESDefaults(postgreSQL: PluginMetadataSnapshot) -> [(typeId: String, snapshot: PluginMetadataSnapshot)] { - [("KingbaseES", PluginMetadataSnapshot( + // Its Oracle mode has not been run against the head and size reads, so a page reads every value whole. + var capabilities = postgreSQL.capabilities + capabilities.largeValueFunctions = nil + return [("KingbaseES", PluginMetadataSnapshot( displayName: "KingbaseES", iconName: "cylinder", defaultPort: 54_321, requiresAuthentication: true, supportsForeignKeys: postgreSQL.supportsForeignKeys, supportsSchemaEditing: postgreSQL.supportsSchemaEditing, isDownloadable: true, @@ -28,7 +31,7 @@ extension PluginMetadataRegistry { brandColorHex: "#C9141E", queryLanguageName: "SQL", editorLanguage: .sql, connectionMode: .network, supportsDatabaseSwitching: postgreSQL.supportsDatabaseSwitching, structureEditing: postgreSQL.structureEditing, - capabilities: postgreSQL.capabilities, schema: postgreSQL.schema, editor: postgreSQL.editor, + capabilities: capabilities, schema: postgreSQL.schema, editor: postgreSQL.editor, connection: PluginMetadataSnapshot.ConnectionConfig( additionalConnectionFields: postgreSQL.connection.additionalConnectionFields.filter { $0.id == "usePgpass" diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry.swift index cb80eb09cf..3a97cc3ba8 100644 --- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry.swift +++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry.swift @@ -171,8 +171,8 @@ struct PluginMetadataSnapshot: Sendable { // False where users and roles are different kinds: there a role never logs in, and Can log in is a user's lock. var supportsRoleLogin: Bool = true - // Set, a table page reads a large binary value's size through it and loads the value on demand. - var binaryLengthFunction: String? + // Set, a table page reads a large value's size and the start of its text through them, and loads the value on demand. + var largeValueFunctions: LargeValueFunctions? // Whether a table's DDL can state a CHECK value list in the form `QuerySqlParser` reads. False where the // server rewrites the clause into another shape, or where the driver fills `allowedValues` itself. @@ -865,7 +865,7 @@ final class PluginMetadataRegistry: @unchecked Sendable { supportsPrincipalConnectionLimit: existingSnapshot?.capabilities .supportsPrincipalConnectionLimit ?? true, supportsRoleLogin: existingSnapshot?.capabilities.supportsRoleLogin ?? true, - binaryLengthFunction: existingSnapshot?.capabilities.binaryLengthFunction, + largeValueFunctions: existingSnapshot?.capabilities.largeValueFunctions, readsCheckListsFromDDL: existingSnapshot?.capabilities.readsCheckListsFromDDL ?? true, readOnlyEnforcement: existingSnapshot?.capabilities.readOnlyEnforcement ?? .loginPrivileges, statementPolicyInDriver: existingSnapshot?.capabilities.statementPolicyInDriver ?? false, diff --git a/apple/TablePro/Core/Services/Query/QueryExecutor.swift b/apple/TablePro/Core/Services/Query/QueryExecutor.swift index 31cd7a6fc4..7b1b1d072a 100644 --- a/apple/TablePro/Core/Services/Query/QueryExecutor.swift +++ b/apple/TablePro/Core/Services/Query/QueryExecutor.swift @@ -8,7 +8,8 @@ private let queryExecutorLog = Logger(subsystem: "com.TablePro", category: "Quer struct QueryFetchResult { let columns: [String] let columnTypes: [ColumnType] - let rows: [[PluginCellValue]] + // Mutable so a fold can cut the trailing columns off each row in place. + var rows: [[PluginCellValue]] let executionTime: TimeInterval let rowsAffected: Int let statusMessage: String? diff --git a/apple/TablePro/Core/Services/Query/UnloadedValuePlan.swift b/apple/TablePro/Core/Services/Query/UnloadedValuePlan.swift index 7a92ab8c35..eac46504a6 100644 --- a/apple/TablePro/Core/Services/Query/UnloadedValuePlan.swift +++ b/apple/TablePro/Core/Services/Query/UnloadedValuePlan.swift @@ -6,16 +6,69 @@ import Foundation import TableProPluginKit -// A deferred column reads its value only up to the limit; its byte length follows in a trailing -// column named after the column's position in the select list. +// How an engine measures a value and reads the start of its text. Each template holds `{}` where the quoted +// column goes; a head's `{count}` counts characters, so a head never ends inside a UTF-8 sequence. +struct LargeValueFunctions: Equatable, Sendable { + let binaryLength: String + let textLength: String + let textHead: String + // Set where a document's text is built from its stored form on every read. Its stored size settles most cuts + // without building that text: over the limit it is cut, within an eighth of the limit it is read whole, and only + // one between is measured as text. A document compressed past an eighth of its text size is read whole. A cut + // value's length and head still build its text. + var documentStoredSize: String? + // False where a declared size such as `varchar(255)` is not enforced, so it says nothing about how large a value is. + var enforcesDeclaredLength = true + // Types whose name carries their largest size, so a value of one under the limit is never cut. + var boundedTypeBytes: [String: Int] = [:] + + static let mySQL = LargeValueFunctions( + binaryLength: "OCTET_LENGTH({})", textLength: "OCTET_LENGTH({})", textHead: "LEFT({}, {count})", + boundedTypeBytes: ["TINYTEXT": 255, "TINYBLOB": 255, "TEXT": 65_535, "BLOB": 65_535] + ) + // `octet_length` takes no json, jsonb or xml, and `substr` reads a stored text only up to the slice it returns. + // `pg_column_size` reads the stored size without decompressing or converting the value. + static let postgreSQL = LargeValueFunctions( + binaryLength: "octet_length({})", textLength: "octet_length({}::text)", textHead: "substr({}::text, 1, {count})", + documentStoredSize: "pg_column_size({})" + ) + // `length` counts a text's characters, its bytes only once cast. + static let sqlite = LargeValueFunctions( + binaryLength: "length(CAST({} AS BLOB))", textLength: "length(CAST({} AS BLOB))", textHead: "substr({}, 1, {count})", + enforcesDeclaredLength: false + ) + + // The column goes in last, so text a quoted name holds is never read as a placeholder. + static func render(_ template: String, column: String, count: Int? = nil) -> String { + let counted = count.map { template.replacingOccurrences(of: "{count}", with: String($0)) } ?? template + return counted.components(separatedBy: "{}").joined(separator: column) + } +} + +// A deferred column reads its value only up to the limit; its byte length, and for text its first characters, +// follow in trailing columns named after the column's position in the select list. struct UnloadedValuePlan: Equatable, Sendable { + enum Kind: Equatable, Sendable { + case binary + case text + // JSON, jsonb and XML: read as text, measured by their stored size where the engine offers one. + case document + + var readsHead: Bool { self != .binary } + } + let columns: [String] - let byteLengthFunction: String + let kinds: [String: Kind] + let columnTypes: [String: ColumnType] + let functions: LargeValueFunctions let inlineByteLimit: Int // MySQL's BLOB holds at most 64 KB, so a BLOB value always arrives with the page. static let defaultInlineByteLimit = 65_536 + // A grid line shows far fewer, and at four bytes a character the head stays near a kilobyte. + static let headCharacterCount = 256 static let lengthAliasPrefix = "__tablepro_byte_length_" + static let headAliasPrefix = "__tablepro_head_" // A value is read back by key, and a sorted or value-filtered column needs its values in the page. static func resolve( @@ -24,91 +77,211 @@ struct UnloadedValuePlan: Equatable, Sendable { primaryKeys: [String], sortColumns: [String] = [], valueFilteredColumns: [String] = [], - byteLengthFunction: String?, + functions: LargeValueFunctions?, inlineByteLimit: Int ) -> UnloadedValuePlan? { - guard let byteLengthFunction, !byteLengthFunction.isEmpty, !primaryKeys.isEmpty, - primaryKeys.allSatisfy(selectedColumns.contains) else { return nil } + guard let functions, !primaryKeys.isEmpty, primaryKeys.allSatisfy(selectedColumns.contains) else { return nil } + let limit = max(0, inlineByteLimit) let kept = Set(primaryKeys).union(sortColumns).union(valueFilteredColumns) - let deferred = selectedColumns.filter { columnTypes[$0]?.isBlobType == true && !kept.contains($0) } + var deferred: [String] = [] + var kinds: [String: Kind] = [:] + var types: [String: ColumnType] = [:] + for name in selectedColumns where !kept.contains(name) && kinds[name] == nil { + guard let type = columnTypes[name], + let kind = kind( + of: type, inlineByteLimit: limit, + trustsDeclaredLength: functions.enforcesDeclaredLength, boundedTypeBytes: functions.boundedTypeBytes + ) + else { continue } + deferred.append(name) + kinds[name] = kind + types[name] = type + } guard !deferred.isEmpty else { return nil } return UnloadedValuePlan( - columns: deferred, - byteLengthFunction: byteLengthFunction, - inlineByteLimit: max(0, inlineByteLimit) + columns: deferred, kinds: kinds, columnTypes: types, functions: functions, inlineByteLimit: limit ) } + // A type whose declared size fits under the limit can never be cut, so it stays a plain column. + static func kind( + of type: ColumnType, + inlineByteLimit: Int, + trustsDeclaredLength: Bool = true, + boundedTypeBytes: [String: Int] = [:] + ) -> Kind? { + let declared = trustsDeclaredLength ? declaredLength(type.rawType) : nil + if let bound = boundedTypeBytes[baseTypeName(type.rawType)], bound <= inlineByteLimit { return nil } + switch type { + case .blob: + if let declared, declared <= inlineByteLimit { return nil } + return .binary + case .json: + return .document + case .text(let rawType): + let name = baseTypeName(rawType) + if name == "XML" { return .document } + guard characterTypeNames.contains(name) else { return nil } + if let declared, declared.multipliedReportingOverflow(by: 4).partialValue <= inlineByteLimit { return nil } + return .text + default: + return nil + } + } + func selectList(for selectColumns: [String], quote: (String) -> String) -> String { - let deferred = Set(columns) var items: [String] = [] var lengths: [String] = [] + var heads: [String] = [] for (index, name) in selectColumns.enumerated() { let quoted = quote(name) - guard deferred.contains(name) else { + guard let kind = kinds[name] else { items.append(quoted) continue } - let length = "\(byteLengthFunction)(\(quoted))" - items.append("CASE WHEN \(length) <= \(inlineByteLimit) THEN \(quoted) END AS \(quoted)") - lengths.append("\(length) AS \(quote(Self.lengthAliasPrefix + String(index)))") + let template = kind == .binary ? functions.binaryLength : functions.textLength + let length = LargeValueFunctions.render(template, column: quoted) + let lengthAlias = quote(Self.lengthAliasPrefix + String(index)) + let isCut: String + if kind == .document, let stored = functions.documentStoredSize { + let storedSize = LargeValueFunctions.render(stored, column: quoted) + isCut = """ + (CASE WHEN \(storedSize) > \(inlineByteLimit) THEN TRUE \ + WHEN \(storedSize) <= \(inlineByteLimit / 8) THEN FALSE \ + ELSE \(length) > \(inlineByteLimit) END) + """ + items.append("CASE WHEN \(isCut) THEN NULL ELSE \(quoted) END AS \(quoted)") + lengths.append("CASE WHEN \(isCut) THEN \(length) END AS \(lengthAlias)") + } else { + isCut = "\(length) > \(inlineByteLimit)" + items.append("CASE WHEN \(length) <= \(inlineByteLimit) THEN \(quoted) END AS \(quoted)") + lengths.append("\(length) AS \(lengthAlias)") + } + guard kind.readsHead else { continue } + let head = LargeValueFunctions.render(functions.textHead, column: quoted, count: Self.headCharacterCount) + heads.append("CASE WHEN \(isCut) THEN \(head) END AS \(quote(Self.headAliasPrefix + String(index)))") } - return (items + lengths).joined(separator: ", ") + return (items + lengths + heads).joined(separator: ", ") + } + + func layout(for selectColumns: [String]) -> UnloadedValueLayout { + UnloadedValueLayout(deferred: selectColumns.enumerated().compactMap { index, name in + guard let kind = kinds[name] else { return nil } + return UnloadedValueLayout.Deferred(position: index, type: columnTypes[name], readsHead: kind.readsHead) + }) + } + + private static let characterTypeNames: Set = [ + "TEXT", "TINYTEXT", "MEDIUMTEXT", "LONGTEXT", "CLOB", "NCLOB", "NTEXT", "CITEXT", "STRING", + "VARCHAR", "CHARACTER VARYING", "NVARCHAR", "NATIONAL CHARACTER VARYING", "VARCHAR2", "NVARCHAR2", + "CHAR", "CHARACTER", "NCHAR", "NATIONAL CHARACTER", "BPCHAR" + ] + + private static func baseTypeName(_ rawType: String?) -> String { + guard let rawType else { return "" } + let name = rawType.prefix { $0 != "(" }.uppercased() + return name.split(whereSeparator: \.isWhitespace).joined(separator: " ") + } + + private static func declaredLength(_ rawType: String?) -> Int? { + guard let rawType, let open = rawType.firstIndex(of: "("), + let close = rawType[open...].firstIndex(of: ")") else { return nil } + return Int(rawType[rawType.index(after: open).. [String] { - let deferred = Set(columns) - return selectColumns.enumerated() - .filter { deferred.contains($0.element) } - .map { Self.lengthAliasPrefix + String($0.offset) } + var trailingColumns: [String] { + deferred.map { UnloadedValuePlan.lengthAliasPrefix + String($0.position) } + + deferred.filter(\.readsHead).map { UnloadedValuePlan.headAliasPrefix + String($0.position) } } } struct UnloadedValueFold { let columns: [String] let columnTypes: [ColumnType] - let rows: [[PluginCellValue]] let columnMeta: [ResultColumnMeta]? let unloadedCells: [Int: [Int: Int]] - // Only the length columns the page's plan asked for, so a table's own column of that name stays. + // Only the columns the page's plan asked for, so a table's own column of that name stays. The rows are cut + // in place: each one already holds its trailing columns, so dropping them allocates nothing. static func fold( columns: [String], columnTypes: [ColumnType], - rows: [[PluginCellValue]], + rows: inout [[PluginCellValue]], columnMeta: [ResultColumnMeta]?, - lengthColumns: [String] + layout: UnloadedValueLayout? ) -> UnloadedValueFold? { - guard !lengthColumns.isEmpty, columns.count > lengthColumns.count, - Array(columns.suffix(lengthColumns.count)) == lengthColumns else { return nil } - let start = columns.count - lengthColumns.count - let targets = lengthColumns.compactMap(measuredColumn(named:)) - guard targets.count == lengthColumns.count, targets.allSatisfy({ $0 >= 0 && $0 < start }) else { return nil } + guard let layout, !layout.deferred.isEmpty else { return nil } + let trailing = layout.trailingColumns + guard columns.count > trailing.count, Array(columns.suffix(trailing.count)) == trailing else { return nil } + let start = columns.count - trailing.count + guard layout.deferred.allSatisfy({ $0.position >= 0 && $0.position < start }) else { return nil } + + var headIndex: [Int: Int] = [:] + var nextHead = start + layout.deferred.count + for item in layout.deferred where item.readsHead { + headIndex[item.position] = nextHead + nextHead += 1 + } var unloaded: [Int: [Int: Int]] = [:] - var stripped: [[PluginCellValue]] = [] - stripped.reserveCapacity(rows.count) - for (rowIndex, row) in rows.enumerated() { - for (offset, target) in targets.enumerated() { + for rowIndex in rows.indices { + let count = rows[rowIndex].count + for (offset, item) in layout.deferred.enumerated() { + let target = item.position let lengthIndex = start + offset - guard lengthIndex < row.count, target < row.count, row[target].isNull, - let length = byteLength(row[lengthIndex]) else { continue } + guard lengthIndex < count, rows[rowIndex][target].isNull, + let length = byteLength(rows[rowIndex][lengthIndex]) else { continue } unloaded[rowIndex, default: [:]][target] = length + // The head rides in the cell only to the grid's rows, which keep NULL there (`TableRows.liftingHeads`). + if let index = headIndex[target], index < count, let head = headText(rows[rowIndex][index]) { + rows[rowIndex][target] = .text(head) + } + } + if count > start { rows[rowIndex].removeLast(count - start) } + } + + var types = Array(columnTypes.prefix(start)) + for item in layout.deferred where item.position < types.count { + guard let type = item.type else { continue } + let reported = types[item.position] + if reported.displayName != type.displayName || (reported.rawType ?? "").isEmpty { + types[item.position] = type } - stripped.append(row.count > start ? Array(row.prefix(start)) : row) } return UnloadedValueFold( columns: Array(columns.prefix(start)), - columnTypes: Array(columnTypes.prefix(start)), - rows: stripped, + columnTypes: types, columnMeta: columnMeta.map { Array($0.prefix(start)) }, unloadedCells: unloaded ) } - private static func measuredColumn(named name: String) -> Int? { - guard name.hasPrefix(UnloadedValuePlan.lengthAliasPrefix) else { return nil } - return Int(name.dropFirst(UnloadedValuePlan.lengthAliasPrefix.count)) + // An engine names no origin for a CASE expression, so a deferred column takes its table from the key's origin, + // which is in every page a plan builds; a reader that masks by origin would otherwise hide the whole column. + static func origins( + _ origins: [PluginColumnOrigin?]?, + columns: [String], + layout: UnloadedValueLayout? + ) -> [PluginColumnOrigin?]? { + guard var kept = origins.map({ Array($0.prefix(columns.count)) }) else { return nil } + guard let layout, let table = kept.lazy.compactMap({ $0 }).first else { return kept } + for item in layout.deferred where kept.indices.contains(item.position) && kept[item.position] == nil { + kept[item.position] = PluginColumnOrigin(schema: table.schema, table: table.table, column: columns[item.position]) + } + return kept } private static func byteLength(_ cell: PluginCellValue) -> Int? { @@ -118,18 +291,31 @@ struct UnloadedValueFold { case .bytes(let data): return String(bytes: data, encoding: .utf8).flatMap { Int($0) } } } + + // A head an engine hands back as bytes is shown only when it reads as text. + private static func headText(_ cell: PluginCellValue) -> String? { + switch cell { + case .null: return nil + case .text(let text): return text.isEmpty ? nil : text + case .bytes(let data): return String(bytes: data, encoding: .utf8).flatMap { $0.isEmpty ? nil : $0 } + } + } } extension QueryResult { - func foldingUnloadedValues(lengthColumns: [String]) -> QueryResult { + mutating func foldUnloadedValues(_ layout: UnloadedValueLayout?) { + var cut = rows + rows = [] guard let fold = UnloadedValueFold.fold( - columns: columns, columnTypes: columnTypes, rows: rows, columnMeta: columnMeta, - lengthColumns: lengthColumns - ) else { return self } + columns: columns, columnTypes: columnTypes, rows: &cut, columnMeta: columnMeta, layout: layout + ) else { + rows = cut + return + } var folded = QueryResult( columns: fold.columns, columnTypes: fold.columnTypes, - rows: fold.rows, + rows: cut, rowsAffected: rowsAffected, executionTime: executionTime, error: error, @@ -143,22 +329,26 @@ extension QueryResult { absentCells: absentCells ) folded.unloadedCells = fold.unloadedCells - // The fold drops the trailing length columns, so the origins of the columns it keeps still line up. - folded.columnOrigins = columnOrigins.map { Array($0.prefix(fold.columns.count)) } - return folded + // The fold drops the trailing columns, so the origins of the columns it keeps still line up. + folded.columnOrigins = UnloadedValueFold.origins(columnOrigins, columns: fold.columns, layout: layout) + self = folded } } extension QueryFetchResult { - func foldingUnloadedValues(lengthColumns: [String]) -> QueryFetchResult { + mutating func foldUnloadedValues(_ layout: UnloadedValueLayout?) { + var cut = rows + rows = [] guard let fold = UnloadedValueFold.fold( - columns: columns, columnTypes: columnTypes, rows: rows, columnMeta: resultColumnMeta, - lengthColumns: lengthColumns - ) else { return self } + columns: columns, columnTypes: columnTypes, rows: &cut, columnMeta: resultColumnMeta, layout: layout + ) else { + rows = cut + return + } var folded = QueryFetchResult( columns: fold.columns, columnTypes: fold.columnTypes, - rows: fold.rows, + rows: cut, executionTime: executionTime, rowsAffected: rowsAffected, statusMessage: statusMessage, @@ -171,8 +361,8 @@ extension QueryFetchResult { absentCells: absentCells ) folded.unloadedCells = fold.unloadedCells - // The fold drops the trailing length columns, so the origins of the columns it keeps still line up. - folded.columnOrigins = columnOrigins.map { Array($0.prefix(fold.columns.count)) } - return folded + // The fold drops the trailing columns, so the origins of the columns it keeps still line up. + folded.columnOrigins = UnloadedValueFold.origins(columnOrigins, columns: fold.columns, layout: layout) + self = folded } } diff --git a/apple/TablePro/Models/Query/QueryResult.swift b/apple/TablePro/Models/Query/QueryResult.swift index fbe1717905..fbe773af9a 100644 --- a/apple/TablePro/Models/Query/QueryResult.swift +++ b/apple/TablePro/Models/Query/QueryResult.swift @@ -11,7 +11,8 @@ import TableProPluginKit struct QueryResult { let columns: [String] let columnTypes: [ColumnType] - let rows: [[PluginCellValue]] + // Mutable so a fold can cut the trailing columns off each row in place. + var rows: [[PluginCellValue]] let rowsAffected: Int let executionTime: TimeInterval let error: DatabaseError? diff --git a/apple/TablePro/Models/Query/Row.swift b/apple/TablePro/Models/Query/Row.swift index 69de1147aa..5561222cef 100644 --- a/apple/TablePro/Models/Query/Row.swift +++ b/apple/TablePro/Models/Query/Row.swift @@ -38,10 +38,12 @@ struct SparseRowState: Equatable, Sendable { private(set) var absentColumns: [RowID: Set] = [:] // Column to byte length of a value the page left on the server; it reads `.null` until loaded. private(set) var unloadedColumns: [RowID: [Int: Int]] = [:] + // The first characters of an unloaded text, for the grid to show. Never a value: a reader of the row sees `.null`. + private(set) var unloadedHeads: [RowID: [Int: String]] = [:] private(set) var exportSnapshots: [RowID: DocumentExportSnapshot] = [:] var isEmpty: Bool { - absentColumns.isEmpty && unloadedColumns.isEmpty && exportSnapshots.isEmpty + absentColumns.isEmpty && unloadedColumns.isEmpty && unloadedHeads.isEmpty && exportSnapshots.isEmpty } mutating func setAbsentColumns(_ columns: Set, for id: RowID) { @@ -50,6 +52,21 @@ struct SparseRowState: Equatable, Sendable { mutating func setUnloadedColumns(_ columns: [Int: Int], for id: RowID) { Self.set(columns, for: id, in: &unloadedColumns) + guard var heads = unloadedHeads[id] else { return } + heads = heads.filter { columns[$0.key] != nil } + Self.set(heads, for: id, in: &unloadedHeads) + } + + mutating func setUnloadedHeads(_ heads: [Int: String], for id: RowID) { + Self.set(heads, for: id, in: &unloadedHeads) + } + + // A column masked after its rows arrived shows only the sizes of its cut values. + mutating func dropUnloadedHeads(inColumns columns: Set) { + guard !unloadedHeads.isEmpty, !columns.isEmpty else { return } + for (id, heads) in unloadedHeads { + Self.set(heads.filter { !columns.contains($0.key) }, for: id, in: &unloadedHeads) + } } mutating func setExportSnapshot(_ snapshot: DocumentExportSnapshot?, for id: RowID) { @@ -86,6 +103,7 @@ struct SparseRowState: Equatable, Sendable { guard !isEmpty else { return } absentColumns.removeValue(forKey: id) unloadedColumns.removeValue(forKey: id) + unloadedHeads.removeValue(forKey: id) exportSnapshots.removeValue(forKey: id) } diff --git a/apple/TablePro/Models/Query/TableRows.swift b/apple/TablePro/Models/Query/TableRows.swift index 1d166e20e0..dc13a896cd 100644 --- a/apple/TablePro/Models/Query/TableRows.swift +++ b/apple/TablePro/Models/Query/TableRows.swift @@ -182,6 +182,14 @@ struct TableRows: Sendable { sparse.unloadedColumns[id] ?? [:] } + func unloadedHead(_ id: RowID, column: Int) -> String? { + sparse.unloadedHeads[id]?[column] + } + + func unloadedHeads(of id: RowID) -> [Int: String] { + sparse.unloadedHeads[id] ?? [:] + } + func hasUnloadedValues(_ id: RowID) -> Bool { sparse.unloadedColumns[id] != nil } @@ -235,6 +243,7 @@ struct TableRows: Sendable { rows[index].values[column] = addedMasks.value(rows[index].values[column], column: column) } } + sparse.dropUnloadedHeads(inColumns: Set(added.keys)) let columns = columns let policy = exportPolicy let table = exportTable @@ -398,11 +407,14 @@ struct TableRows: Sendable { guard !pageRows.isEmpty else { return .none } let firstIndex = rows.count rows.reserveCapacity(rows.count + pageRows.count) - for (idx, values) in pageRows.enumerated() { + for (idx, read) in pageRows.enumerated() { + let unloaded = Self.clamp(unloadedCells[idx] ?? [:], toCount: columns.count) + let (values, heads) = Self.liftingHeads(read, unloaded: unloaded, masks: masks) let normalized = Self.normalize(values: masks.row(values), toCount: columns.count) let id = RowID.existing(offset + idx) sparse.setAbsentColumns(Self.clamp(absentCells[idx] ?? [], toCount: columns.count), for: id) - sparse.setUnloadedColumns(Self.clamp(unloadedCells[idx] ?? [:], toCount: columns.count), for: id) + sparse.setUnloadedColumns(unloaded, for: id) + sparse.setUnloadedHeads(heads, for: id) sparse.setExportSnapshot( Self.exportSnapshot( documents: exportDocuments, index: idx, count: pageRows.count, @@ -727,12 +739,14 @@ struct TableRows: Sendable { isComplete: false ) } - let values = queryRows[rowIndex] + let unloaded = clamp(unloadedCells[position] ?? [:], toCount: columnCount) + let (values, heads) = liftingHeads(queryRows[rowIndex], unloaded: unloaded, masks: shape.masks) let normalized = normalize(values: shape.masks.row(values), toCount: columnCount) let absent = absentCells[position] ?? [] let id = RowID.existing(offset + position) sparse.setAbsentColumns(clamp(absent, toCount: columnCount), for: id) - sparse.setUnloadedColumns(clamp(unloadedCells[position] ?? [:], toCount: columnCount), for: id) + sparse.setUnloadedColumns(unloaded, for: id) + sparse.setUnloadedHeads(heads, for: id) sparse.setExportSnapshot( exportSnapshot( documents: exportDocuments, index: position, count: count, @@ -839,6 +853,26 @@ struct TableRows: Sendable { guard unloadedColumns.keys.contains(where: { $0 < 0 || $0 >= targetCount }) else { return unloadedColumns } return unloadedColumns.filter { $0.key >= 0 && $0.key < targetCount } } + + // A cut text arrives with its first characters in the cell. The row holds NULL there, as for any value left on the + // server, so no reader takes the characters for the value; the grid shows them. A masked column shows only the size, + // since a mask over the first characters is not the mask of the value. + static func liftingHeads( + _ values: [PluginCellValue], + unloaded: [Int: Int], + masks: ColumnMasks + ) -> (values: [PluginCellValue], heads: [Int: String]) { + guard !unloaded.isEmpty else { return (values, [:]) } + var values = values + var heads: [Int: String] = [:] + for column in unloaded.keys where values.indices.contains(column) { + if case .text(let head) = values[column], !head.isEmpty, !masks.isMasked(column) { + heads[column] = head + } + values[column] = .null + } + return (values, heads) + } } extension TableRows { diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 399a3e85c5..9c02b7b98a 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -18489,6 +18489,9 @@ }, "A larger binary value stays on the server until you open, copy or export it. Applies to tables with a primary key." : { + }, + "A larger text, JSON or binary value stays on the server until you open, copy or export it. The grid shows the start of a text value. Applies to tables with a primary key." : { + }, "A link you chose Always Allow for connects without asking again. Only connections on this Mac can be trusted." : { "localizations" : { @@ -114668,6 +114671,9 @@ } } } + }, + "Large Value Limit" : { + }, "Larger tables show an estimated count, which avoids a slow COUNT(*)." : { "localizations" : { diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift index 32c5eac9b4..1b6c8cced9 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionEditorEngine+Layout.swift @@ -609,8 +609,8 @@ extension ConnectionEditorEngine { id: "tableData", title: String(localized: "Table Data"), footer: String(localized: """ - A larger binary value stays on the server until you open, copy or export it. \ - Applies to tables with a primary key. + A larger text, JSON or binary value stays on the server until you open, copy or export it. \ + The grid shows the start of a text value. Applies to tables with a primary key. """), rows: [.builtIn(.binaryInlineLimit)] )) diff --git a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionTypeTraits.swift b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionTypeTraits.swift index cab561586c..157538516d 100644 --- a/apple/TablePro/Views/ConnectionForm/Engine/ConnectionTypeTraits.swift +++ b/apple/TablePro/Views/ConnectionForm/Engine/ConnectionTypeTraits.swift @@ -136,7 +136,7 @@ struct ConnectionTypeTraits: Sendable { traits.ssl = sslTraits(for: type, pluginManager: pluginManager) traits.isEngineReadOnly = pluginManager.isEngineReadOnly(for: type) traits.manualCommitAvailable = ManualCommit.isAvailable(for: type) - traits.supportsBinaryInlineLimit = pluginManager.binaryLengthFunction(for: type) != nil + traits.supportsBinaryInlineLimit = pluginManager.largeValueFunctions(for: type) != nil traits.supportsIdentifierCase = type.identifierRules != nil traits.storedSecureFieldIds = pluginManager.secureConnectionFieldIds(for: type) return traits diff --git a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift index 07e86ef31c..2b29f4710a 100644 --- a/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift +++ b/apple/TablePro/Views/ConnectionForm/Facets/AdvancedFacetView.swift @@ -50,7 +50,7 @@ struct AdvancedFacetView: View { AdvancedQueryTimeoutRow(row: row, store: store, generalSettings: store.services.appSettings.generalSlice) case .builtIn(.binaryInlineLimit): EditorOptionalNumberRow( - String(localized: "Binary Value Limit"), + String(localized: "Large Value Limit"), value: store.binding(\.options.binaryInlineLimitKilobytes), defaultValue: UnloadedValuePlan.defaultInlineByteLimit / 1_024, range: DatabaseConnection.binaryInlineLimitKilobytesRange, diff --git a/apple/TablePro/Views/DataGrid/Cells/DataGridCellContent.swift b/apple/TablePro/Views/DataGrid/Cells/DataGridCellContent.swift index 1f918e38b5..a3d4b0e81b 100644 --- a/apple/TablePro/Views/DataGrid/Cells/DataGridCellContent.swift +++ b/apple/TablePro/Views/DataGrid/Cells/DataGridCellContent.swift @@ -57,7 +57,8 @@ struct DataGridCellContent { case .absent: return absentFieldText case .unloaded(let byteCount): - return unloadedText(byteCount: byteCount) + // A text value left on the server arrives with its first characters, shown as the start of a longer value. + return displayText.isEmpty ? unloadedText(byteCount: byteCount) : displayText + "…" } } diff --git a/apple/TablePro/Views/DataGrid/Cells/DataGridCellPresenter.swift b/apple/TablePro/Views/DataGrid/Cells/DataGridCellPresenter.swift index 71c141c7d8..24c5f4f728 100644 --- a/apple/TablePro/Views/DataGrid/Cells/DataGridCellPresenter.swift +++ b/apple/TablePro/Views/DataGrid/Cells/DataGridCellPresenter.swift @@ -205,7 +205,11 @@ final class DataGridCellPresenter { if let existing, dataIndex < existing.values.count, let cached = existing.values[dataIndex] { return (cached, existing.isFormatted(at: dataIndex)) } - let rawValue = row.values[dataIndex] + // A cut text holds NULL and shows its first characters, which the row keeps beside its values. + let stored = row.values[dataIndex] + let rawValue = stored.isNull + ? model?.rows.unloadedHead(row.id, column: dataIndex).map(PluginCellValue.text) ?? stored + : stored let format = dataIndex < formats.count ? formats[dataIndex] : nil let formatted = CellDisplayFormatter.display( rawValue, @@ -323,16 +327,22 @@ final class DataGridCellPresenter { let order = model.order let cache = model.display.cache var copied: [Row] = [] + var heads: [RowID: [Int: String]] = [:] var index = start while index < window.upperBound, copied.count < DataGridPrewarmBatch.rowLimit { if let row = order.row(at: index, in: rows), cache.box(forID: row.id) == nil { copied.append(row) + if rows.hasUnloadedValues(row.id) { + let rowHeads = rows.unloadedHeads(of: row.id) + if !rowHeads.isEmpty { heads[row.id] = rowHeads } + } } index += 1 } guard !copied.isEmpty else { return (nil, index) } let batch = DataGridPrewarmBatch( rows: copied, + unloadedHeads: heads, columnCount: rows.columns.count, columnTypes: rows.columnTypes, formats: model.store.displayFormats, @@ -474,7 +484,10 @@ final class DataGridCellPresenter { case .empty: return String(localized: "Empty") case .defaultMarker: return String(localized: "DEFAULT") case .absent: return DataGridCellContent.absentFieldText - case .unloaded(let byteCount): return DataGridCellContent.unloadedSpokenText(byteCount: byteCount) + case .unloaded(let byteCount): + // A cut text shows its first characters, so they are read before its size. + let size = DataGridCellContent.unloadedSpokenText(byteCount: byteCount) + return text.isEmpty ? size : String(format: String(localized: "%@, %@"), spokenText(of: text), size) case .none: return spokenText(of: text) } } diff --git a/apple/TablePro/Views/DataGrid/Cells/DataGridColumnWidthCalculator.swift b/apple/TablePro/Views/DataGrid/Cells/DataGridColumnWidthCalculator.swift index 88021d9cb7..6f92c41e1d 100644 --- a/apple/TablePro/Views/DataGrid/Cells/DataGridColumnWidthCalculator.swift +++ b/apple/TablePro/Views/DataGrid/Cells/DataGridColumnWidthCalculator.swift @@ -75,8 +75,9 @@ struct DataGridColumnWidthCalculator { for index in stride(from: 0, to: totalRows, by: step) { let rawValue = rows.value(at: index, column: dataIndex) + let head = rawValue.isNull ? rows.unloadedHead(rows.rows[index].id, column: dataIndex) : nil let formatted = CellDisplayFormatter.format( - rawValue, + head.map(PluginCellValue.text) ?? rawValue, columnType: input.column.type, displayFormat: input.displayFormat, databaseType: databaseType diff --git a/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+RowDrag.swift b/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+RowDrag.swift index e36468b966..daebc6ad4d 100644 --- a/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+RowDrag.swift +++ b/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+RowDrag.swift @@ -4,6 +4,7 @@ // import AppKit +import TableProPluginKit extension DataGridViewController { // Dropped in another app a row is a copy, as tab-separated text and an HTML table; the reorder type rides along @@ -12,9 +13,16 @@ extension DataGridViewController { guard let rowModel = model.row(at: row) else { return nil } let rows = model.rows let projection = gridCommands.visibleProjection + // A drag cannot wait for a read, so a value left on the server says so, as text even in a binary column. + var values = Array(rowModel.values) + var columnTypes = rows.columnTypes + for (column, byteCount) in rows.unloadedColumns(of: rowModel.id) where values.indices.contains(column) { + values[column] = .text(UnloadedValueText.notLoaded(byteCount: byteCount)) + if columnTypes.indices.contains(column) { columnTypes[column] = .text(rawType: nil) } + } let formatted = DataGridCommands.formatRowValues( - projection.values(Array(rowModel.values)), - columnTypes: projection.columnTypes(rows.columnTypes) + projection.values(values), + columnTypes: projection.columnTypes(columnTypes) ) let item = NSPasteboardItem() if model.configuration.rowReorder.isEnabled { diff --git a/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift b/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift index 80a28626ef..5583958ca0 100644 --- a/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift +++ b/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift @@ -59,9 +59,10 @@ final class DataTabGridAdapter: DataGridDataSource, DataGridActions { return coordinator.tabManager.tabs[index].pagination.currentOffset } + // A cut value holds only its first characters, so a find over it covers part of the page, as over a page of more. var gridHasUnloadedRows: Bool { guard let tab else { return false } - return tab.pagination.hasUnloadedRows(loadedRowCount: gridRows.rows.count) + return tab.pagination.hasUnloadedRows(loadedRowCount: gridRows.rows.count) || gridRows.hasUnloadedValues } var gridHighlightRules: [HighlightRule] { diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnFetchScope.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnFetchScope.swift index 488f5241ea..7a689a636a 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnFetchScope.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnFetchScope.swift @@ -71,17 +71,17 @@ extension MainContentCoordinator { ) } - // The byte-length columns a query ends with, from the list its SQL was built on: a rerun sends that SQL unchanged. - func unloadedValueLengthColumns(for tab: QueryTab, sql: String) -> [String] { + // The size and head columns a query ends with, from the list its SQL was built on: a rerun sends that SQL unchanged. + func unloadedValueLayout(for tab: QueryTab, sql: String) -> UnloadedValueLayout? { let schema = catalogPageList(of: tab, sql: sql) ?? tableSchemaColumns(for: tab) guard let plan = unloadedValuePlan(for: tab, schema: schema), let selected = selectColumns(for: tab, schema: schema) - else { return [] } - return plan.lengthColumns(for: selected) + else { return nil } + return plan.layout(for: selected) } - var defersBinaryValues: Bool { - PluginManager.shared.binaryLengthFunction(for: connection.type) != nil + var defersLargeValues: Bool { + PluginManager.shared.largeValueFunctions(for: connection.type) != nil } private func tableSchemaColumns(for tab: QueryTab) -> SchemaColumnStore.Entry? { @@ -111,7 +111,7 @@ extension MainContentCoordinator { primaryKeys: schema.primaryKeys, sortColumns: tab.sortState.columns.compactMap(\.columnName), valueFilteredColumns: valueFilteredColumnNames(of: tab), - byteLengthFunction: PluginManager.shared.binaryLengthFunction(for: connection.type), + functions: PluginManager.shared.largeValueFunctions(for: connection.type), inlineByteLimit: connection.binaryInlineLimitBytes ) } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableFirstLoad.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableFirstLoad.swift index ad4f64f239..af4b598a8d 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableFirstLoad.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableFirstLoad.swift @@ -94,11 +94,11 @@ extension MainContentCoordinator { /// Applied filters wait for the schema because no rows have arrived to type their values, and /// an untyped value is guessed from its text: `123` goes to a text column as a number, which - /// PostgreSQL rejects and MySQL answers by comparing numerically. An engine that defers binary + /// PostgreSQL rejects and MySQL answers by comparing numerically. An engine that defers large /// values needs the column types to leave them out of the first page. func firstLoadNeedsSchemaColumns(for tab: QueryTab, hint: DefaultSortHint) -> Bool { wantsDefaultSort(for: tab, hint: hint) - || defersBinaryValues + || defersLargeValues || !tab.columnLayout.hiddenColumns.isEmpty || tab.filterState.isFiltering || tab.pendingRestoredSort != nil diff --git a/apple/TablePro/Views/Main/Extensions/MainContentView+Helpers.swift b/apple/TablePro/Views/Main/Extensions/MainContentView+Helpers.swift index dc0e023039..30835e31c1 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentView+Helpers.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentView+Helpers.swift @@ -124,7 +124,11 @@ extension MainContentView { let values = columns.indices.map { i -> String in guard i < row.values.count else { return "NULL" } if let byteCount = tableRows.unloadedByteCount(row.id, column: i) { - return DataGridCellContent.unloadedSpokenText(byteCount: byteCount) + // A cut text's first characters say more than its size, unless the summary masks the column. + guard !overlay.isMasked(i), let head = tableRows.unloadedHead(row.id, column: i) else { + return DataGridCellContent.unloadedSpokenText(byteCount: byteCount) + } + return String(head.prefix(200)) + "…" } let raw: String switch overlay.value(row.values[i], column: i) { diff --git a/apple/TableProTests/Core/ChangeTracking/UnloadedValueWriteTests.swift b/apple/TableProTests/Core/ChangeTracking/UnloadedValueWriteTests.swift index 57d158297e..f977c9ac5a 100644 --- a/apple/TableProTests/Core/ChangeTracking/UnloadedValueWriteTests.swift +++ b/apple/TableProTests/Core/ChangeTracking/UnloadedValueWriteTests.swift @@ -79,6 +79,50 @@ struct UnloadedValueWriteTests { #expect(build.operations.first?.refusal == nil) } + private static func cutTextPage() -> TableRows { + TableRows.from( + queryRows: [["1", "a", "lorem ipsum"]], + columns: columns, + columnTypes: [.integer(rawType: "INT"), .text(rawType: "VARCHAR"), .text(rawType: "LONGTEXT")], + unloadedCells: [0: [2: 5_242_880]] + ) + } + + @Test("An edit beside a cut text writes only the edited column, and the text's load completes the pre-image") + func editBesideCutText() throws { + let row = Self.cutTextPage().rows[0] + let manager = Self.manager() + manager.recordCellChange( + rowID: row.id, + columnIndex: 1, + columnName: "name", + oldValue: "a", + newValue: "b", + originalRow: Array(row.values) + ) + + let statements = try manager.generateSQL() + #expect(statements.map(\.sql) == ["UPDATE `files` SET `name` = ? WHERE `id` = ?"]) + + let full = PluginCellValue.text("lorem ipsum dolor sit amet") + manager.adoptLoadedValues([row.id: [2: full]]) + let build = try manager.buildRowWrites(database: "d", schema: nil, containsTableOperation: false) + #expect(build.operations.first?.preImage?[2] == full) + } + + @Test("A cut text's first characters never stand in for it in a deletion's pre-image") + func cutTextLoadedAfterDelete() throws { + let row = Self.cutTextPage().rows[0] + let manager = Self.manager() + manager.recordRowDeletion(rowID: row.id, originalRow: Array(row.values)) + #expect(row.values[2] == .null) + let full = PluginCellValue.text("lorem ipsum dolor sit amet") + manager.adoptLoadedValues([row.id: [2: full]]) + + let build = try manager.buildRowWrites(database: "d", schema: nil, containsTableOperation: false) + #expect(build.operations.first?.preImage?[2] == full) + } + @Test("A value loaded while a deletion was undone completes the image its redo records") func redoAfterLoadKeepsLoadedValue() throws { let row = Self.page().rows[0] diff --git a/apple/TableProTests/Core/DataGrid/Engine/GridFindEngineTests.swift b/apple/TableProTests/Core/DataGrid/Engine/GridFindEngineTests.swift index 1017472355..a9fcce4a3c 100644 --- a/apple/TableProTests/Core/DataGrid/Engine/GridFindEngineTests.swift +++ b/apple/TableProTests/Core/DataGrid/Engine/GridFindEngineTests.swift @@ -470,6 +470,27 @@ struct GridFindEngineTests { #expect(result.edits.map { $0.value } == [.enteredText("ann@test.dev"), .enteredText("bob@test.dev")]) } + @Test("Replace leaves a cut value alone and does not count it") + func replaceSkipsCutValue() { + let rows = TableRows.from( + queryRows: [["1", "foo at the start"], ["2", "foo"]], + columns: ["id", "body"], + columnTypes: [.integer(rawType: "INT"), .text(rawType: "LONGTEXT")], + unloadedCells: [0: [1: 5_242_880]] + ) + let source = self.source(rows) + let found = GridFindEngine.search("foo", options: GridFindState.Options(), in: source) + let result = GridFindEngine.replacements( + for: found.matches, term: "foo", options: GridFindState.Options(), template: "bar", + in: source, isWritable: { _ in true } + ) + + #expect(result.edits == [ + DataGridCellEdit(rowID: .existing(1), columnID: DataGridColumnID(name: "body", occurrence: 0), value: .enteredText("bar")) + ]) + #expect(result.replacements == 1) + } + @Test("Replace skips a column it may not write") func replaceSkipsUnwritableColumn() { let result = replace("example", with: "test") { $0.name != "email" } diff --git a/apple/TableProTests/Core/Services/Query/UnloadedValuePlanTests.swift b/apple/TableProTests/Core/Services/Query/UnloadedValuePlanTests.swift index 5e3a769548..770dcc7719 100644 --- a/apple/TableProTests/Core/Services/Query/UnloadedValuePlanTests.swift +++ b/apple/TableProTests/Core/Services/Query/UnloadedValuePlanTests.swift @@ -11,17 +11,19 @@ import Testing struct UnloadedValuePlanTests { private static let types: [String: ColumnType] = [ "id": .integer(rawType: "INT"), - "name": .text(rawType: "VARCHAR"), + "name": .text(rawType: "VARCHAR(255)"), "data": .blob(rawType: "LONGBLOB"), "thumb": .blob(rawType: "MEDIUMBLOB") ] private static let columns = ["id", "name", "data", "thumb"] private static func plan( + columns: [String] = columns, + types: [String: ColumnType] = types, primaryKeys: [String] = ["id"], sortColumns: [String] = [], valueFilteredColumns: [String] = [], - function: String? = "OCTET_LENGTH", + functions: LargeValueFunctions? = .mySQL, limit: Int = 65_536 ) -> UnloadedValuePlan? { UnloadedValuePlan.resolve( @@ -30,37 +32,85 @@ struct UnloadedValuePlanTests { primaryKeys: primaryKeys, sortColumns: sortColumns, valueFilteredColumns: valueFilteredColumns, - byteLengthFunction: function, + functions: functions, inlineByteLimit: limit ) } - private static var mysqlBuilder: TableQueryBuilder { + private static func builder(_ type: DatabaseType, quote: Character) -> TableQueryBuilder { TableQueryBuilder( - databaseType: .mysql, + databaseType: type, dialect: SQLDialectDescriptor( - identifierQuote: "`", keywords: [], functions: [], dataTypes: [], + identifierQuote: String(quote), keywords: [], functions: [], dataTypes: [], regexSyntax: .regexp, booleanLiteralStyle: .numeric, likeEscapeStyle: .implicit, paginationStyle: .limit ), pagination: .offset, - dialectQuote: { "`\($0)`" } + dialectQuote: { "\(quote)\($0)\(quote)" } ) } + private static var mysqlBuilder: TableQueryBuilder { builder(.mysql, quote: "`") } + + private static let documentTypes: [String: ColumnType] = [ + "id": .integer(rawType: "integer"), + "body": .text(rawType: "text"), + "doc": .json(rawType: "jsonb"), + "code": .text(rawType: "character varying(20)"), + "note": .text(rawType: "character varying"), + "uuid": .blob(rawType: "BINARY(16)"), + "made": .timestamp(rawType: "timestamp") + ] + private static let documentColumns = ["id", "body", "doc", "code", "note", "uuid", "made"] + @Test("Binary columns are deferred, the key and other columns are not") func defersBinaryColumns() { #expect(Self.plan()?.columns == ["data", "thumb"]) } + @Test("Text and JSON that can outgrow the limit are deferred with a head; a declared size under it is not") + func defersLargeTextAndJSON() throws { + let plan = try #require(Self.plan(columns: Self.documentColumns, types: Self.documentTypes, functions: .postgreSQL)) + #expect(plan.columns == ["body", "doc", "note"]) + #expect(plan.kinds == ["body": .text, "doc": .document, "note": .text]) + } + + @Test("A declared size counts four bytes a character against the limit") + func declaredTextSizeAgainstLimit() { + #expect(UnloadedValuePlan.kind(of: .text(rawType: "varchar(255)"), inlineByteLimit: 1_024) == nil) + #expect(UnloadedValuePlan.kind(of: .text(rawType: "varchar(300)"), inlineByteLimit: 1_024) == .text) + #expect(UnloadedValuePlan.kind(of: .text(rawType: "NVARCHAR(MAX)"), inlineByteLimit: 1_024) == .text) + #expect(UnloadedValuePlan.kind(of: .text(rawType: "uuid"), inlineByteLimit: 1_024) == nil) + #expect(UnloadedValuePlan.kind(of: .blob(rawType: "VARBINARY(4096)"), inlineByteLimit: 1_024) == .binary) + #expect(UnloadedValuePlan.kind(of: .text(rawType: "xml"), inlineByteLimit: 1_024) == .document) + } + + @Test("A MySQL TEXT or BLOB, at most 64 KB, is never cut under the default limit") + func mySQLBoundedTypes() { + let bounds = LargeValueFunctions.mySQL.boundedTypeBytes + #expect(UnloadedValuePlan.kind(of: .text(rawType: "TINYTEXT"), inlineByteLimit: 1_024, boundedTypeBytes: bounds) == nil) + #expect(UnloadedValuePlan.kind(of: .text(rawType: "TEXT"), inlineByteLimit: 65_536, boundedTypeBytes: bounds) == nil) + #expect(UnloadedValuePlan.kind(of: .blob(rawType: "BLOB"), inlineByteLimit: 65_536, boundedTypeBytes: bounds) == nil) + #expect(UnloadedValuePlan.kind(of: .text(rawType: "TEXT"), inlineByteLimit: 1_024, boundedTypeBytes: bounds) == .text) + #expect(UnloadedValuePlan.kind(of: .text(rawType: "text"), inlineByteLimit: 65_536) == .text) + } + + @Test("SQLite does not enforce a declared size, so a varchar(255) column is still deferred there") + func sqliteIgnoresDeclaredSize() throws { + let types: [String: ColumnType] = ["id": .integer(rawType: "INTEGER"), "title": .text(rawType: "VARCHAR(255)")] + #expect(Self.plan(columns: ["id", "title"], types: types, functions: .mySQL, limit: 1_024) == nil) + let plan = try #require(Self.plan(columns: ["id", "title"], types: types, functions: .sqlite, limit: 1_024)) + #expect(plan.kinds == ["title": .text]) + } + @Test("A table without a primary key keeps every value in the page") func noPrimaryKeyNoPlan() { #expect(Self.plan(primaryKeys: []) == nil) } - @Test("An engine without a byte length function keeps every value in the page") - func noFunctionNoPlan() { - #expect(Self.plan(function: nil) == nil) + @Test("An engine without large value functions keeps every value in the page") + func noFunctionsNoPlan() { + #expect(Self.plan(functions: nil) == nil) } @Test("Sorted and value-filtered columns keep their values") @@ -84,6 +134,69 @@ struct UnloadedValuePlanTests { """) } + @Test("MySQL reads a long text's first characters after the lengths") + func mysqlTextProjection() throws { + let types: [String: ColumnType] = ["id": .integer(rawType: "INT"), "body": .text(rawType: "LONGTEXT")] + let plan = try #require(Self.plan(columns: ["id", "body"], types: types, limit: 1_024)) + let query = Self.mysqlBuilder.buildBaseQuery( + tableName: "posts", columns: ["id", "body"], selectColumns: ["id", "body"], + unloadedValues: plan, limit: 200, offset: 0 + ) + #expect(query == """ + SELECT `id`, CASE WHEN OCTET_LENGTH(`body`) <= 1024 THEN `body` END AS `body`, \ + OCTET_LENGTH(`body`) AS `__tablepro_byte_length_1`, \ + CASE WHEN OCTET_LENGTH(`body`) > 1024 THEN LEFT(`body`, 256) END AS `__tablepro_head_1` \ + FROM `posts` LIMIT 200 OFFSET 0 + """) + } + + @Test("PostgreSQL settles a jsonb cut by its stored size before measuring its text; bytea is measured as stored") + func postgreSQLProjection() throws { + let types: [String: ColumnType] = [ + "id": .integer(rawType: "integer"), "doc": .json(rawType: "jsonb"), "raw": .blob(rawType: "bytea") + ] + let plan = try #require(Self.plan(columns: ["id", "doc", "raw"], types: types, functions: .postgreSQL, limit: 1_024)) + let cut = #"(CASE WHEN pg_column_size("doc") > 1024 THEN TRUE WHEN pg_column_size("doc") <= 128 THEN FALSE "# + + #"ELSE octet_length("doc"::text) > 1024 END)"# + #expect(plan.selectList(for: ["id", "doc", "raw"], quote: { "\"\($0)\"" }) == """ + "id", CASE WHEN \(cut) THEN NULL ELSE "doc" END AS "doc", \ + CASE WHEN octet_length("raw") <= 1024 THEN "raw" END AS "raw", \ + CASE WHEN \(cut) THEN octet_length("doc"::text) END AS "__tablepro_byte_length_1", \ + octet_length("raw") AS "__tablepro_byte_length_2", \ + CASE WHEN \(cut) THEN substr("doc"::text, 1, 256) END AS "__tablepro_head_1" + """) + #expect(plan.layout(for: ["id", "doc", "raw"]).trailingColumns == [ + "__tablepro_byte_length_1", "__tablepro_byte_length_2", "__tablepro_head_1" + ]) + } + + @Test("PostgreSQL measures a text by its length, which it reads without loading the value") + func postgreSQLTextProjection() throws { + let types: [String: ColumnType] = ["id": .integer(rawType: "integer"), "body": .text(rawType: "text")] + let plan = try #require(Self.plan(columns: ["id", "body"], types: types, functions: .postgreSQL, limit: 1_024)) + #expect(plan.selectList(for: ["id", "body"], quote: { "\"\($0)\"" }) == """ + "id", CASE WHEN octet_length("body"::text) <= 1024 THEN "body" END AS "body", \ + octet_length("body"::text) AS "__tablepro_byte_length_1", \ + CASE WHEN octet_length("body"::text) > 1024 THEN substr("body"::text, 1, 256) END AS "__tablepro_head_1" + """) + } + + @Test("SQLite counts a text's bytes through a cast") + func sqliteProjection() throws { + let types: [String: ColumnType] = ["id": .integer(rawType: "INTEGER"), "body": .text(rawType: "TEXT")] + let plan = try #require(Self.plan(columns: ["id", "body"], types: types, functions: .sqlite, limit: 1_024)) + #expect(plan.selectList(for: ["id", "body"], quote: { "\"\($0)\"" }) == """ + "id", CASE WHEN length(CAST("body" AS BLOB)) <= 1024 THEN "body" END AS "body", \ + length(CAST("body" AS BLOB)) AS "__tablepro_byte_length_1", \ + CASE WHEN length(CAST("body" AS BLOB)) > 1024 THEN substr("body", 1, 256) END AS "__tablepro_head_1" + """) + } + + @Test("A placeholder in a quoted name is not filled in") + func renderKeepsQuotedName() { + #expect(LargeValueFunctions.render("LEFT({}, {count})", column: "`a{count}{}`", count: 5) == "LEFT(`a{count}{}`, 5)") + } + @Test("A filtered page defers the same way") func filteredQueryProjection() throws { let plan = try #require(Self.plan()) @@ -100,9 +213,14 @@ struct UnloadedValuePlanTests { #expect(query.contains("WHERE")) } + private static let binaryLayout = UnloadedValueLayout(deferred: [ + .init(position: 2, type: .blob(rawType: "LONGBLOB"), readsHead: false), + .init(position: 3, type: .blob(rawType: "LONGBLOB"), readsHead: false) + ]) + @Test("Folding strips the length columns and marks only withheld values") func foldMarksWithheldValues() throws { - let rows: [[PluginCellValue]] = [ + var rows: [[PluginCellValue]] = [ ["1", "a", .null, .bytes(Data([1])), "5242880", "1"], ["2", "b", .bytes(Data([2, 3])), .null, "2", .null], ["3", "c", .null, .null, .null, .null] @@ -113,38 +231,62 @@ struct UnloadedValuePlanTests { .integer(rawType: "INT"), .text(rawType: "VARCHAR"), .blob(rawType: "LONGBLOB"), .blob(rawType: "LONGBLOB"), .integer(rawType: "BIGINT"), .integer(rawType: "BIGINT") ], - rows: rows, + rows: &rows, columnMeta: nil, - lengthColumns: ["__tablepro_byte_length_2", "__tablepro_byte_length_3"] + layout: Self.binaryLayout )) #expect(fold.columns == ["id", "name", "data", "thumb"]) #expect(fold.columnTypes.count == 4) - #expect(fold.rows.allSatisfy { $0.count == 4 }) + #expect(rows.allSatisfy { $0.count == 4 }) #expect(fold.unloadedCells == [0: [2: 5_242_880]]) - #expect(fold.rows[1][2] == .bytes(Data([2, 3]))) + #expect(rows[1][2] == .bytes(Data([2, 3]))) } - @Test("A result without the planned length columns is left alone") + @Test("A cut text keeps its head in the cell, and the column keeps the table's type") + func foldKeepsHeads() throws { + let layout = UnloadedValueLayout(deferred: [.init(position: 1, type: .json(rawType: "JSON"), readsHead: true)]) + var rows: [[PluginCellValue]] = [ + ["1", .null, "2000000", "{\"a\": [1, 2"], + ["2", "{}", "2", .null], + ["3", .null, .null, .null] + ] + let fold = try #require(UnloadedValueFold.fold( + columns: ["id", "doc", "__tablepro_byte_length_1", "__tablepro_head_1"], + columnTypes: [.integer(rawType: "INT"), .text(rawType: ""), .integer(rawType: "BIGINT"), .text(rawType: "")], + rows: &rows, + columnMeta: nil, + layout: layout + )) + #expect(fold.columns == ["id", "doc"]) + #expect(fold.columnTypes == [.integer(rawType: "INT"), .json(rawType: "JSON")]) + #expect(fold.unloadedCells == [0: [1: 2_000_000]]) + #expect(rows == [["1", "{\"a\": [1, 2"], ["2", "{}"], ["3", .null]]) + } + + @Test("A result without the planned trailing columns is left alone") func foldIgnoresOtherResults() { + var rows: [[PluginCellValue]] = [["1", "a"]] #expect(UnloadedValueFold.fold( - columns: ["id", "name"], columnTypes: [], rows: [["1", "a"]], columnMeta: nil, - lengthColumns: ["__tablepro_byte_length_1"] + columns: ["id", "name"], columnTypes: [], rows: &rows, columnMeta: nil, + layout: UnloadedValueLayout(deferred: [.init(position: 1, type: nil, readsHead: false)]) ) == nil) + var other: [[PluginCellValue]] = [[.null, "1"]] #expect(UnloadedValueFold.fold( - columns: ["id", "__tablepro_byte_length_0"], columnTypes: [], rows: [[.null, "1"]], columnMeta: nil, - lengthColumns: [] + columns: ["id", "__tablepro_byte_length_0"], columnTypes: [], rows: &other, columnMeta: nil, + layout: nil ) == nil) + #expect(other == [[.null, "1"]]) } - @Test("The length aliases follow the deferred columns' places in the select list") - func lengthColumnsMatchSelectList() throws { + @Test("The trailing aliases follow the deferred columns' places in the select list") + func trailingColumnsMatchSelectList() throws { let plan = try #require(Self.plan()) - #expect(plan.lengthColumns(for: Self.columns) == ["__tablepro_byte_length_2", "__tablepro_byte_length_3"]) + #expect(plan.layout(for: Self.columns).trailingColumns == ["__tablepro_byte_length_2", "__tablepro_byte_length_3"]) } @Test("A folded page builds rows that know which values are on the server") func foldedPageBuildsUnloadedRows() { - let result = QueryFetchResult( + var result = QueryFetchResult( columns: ["id", "data", "__tablepro_byte_length_1"], columnTypes: [.integer(rawType: "INT"), .blob(rawType: "LONGBLOB"), .integer(rawType: "BIGINT")], rows: [["1", .null, "70000"]], @@ -153,7 +295,8 @@ struct UnloadedValuePlanTests { statusMessage: nil, isTruncated: false, resultColumnMeta: nil - ).foldingUnloadedValues(lengthColumns: ["__tablepro_byte_length_1"]) + ) + result.foldUnloadedValues(UnloadedValueLayout(deferred: [.init(position: 1, type: nil, readsHead: false)])) let tableRows = TableRows.from( queryRows: result.rows, columns: result.columns, columnTypes: result.columnTypes, unloadedCells: result.unloadedCells @@ -178,8 +321,26 @@ struct UnloadedValuePlanTests { resultColumnMeta: nil ) fetched.columnOrigins = [id, data, nil] - let folded = fetched.foldingUnloadedValues(lengthColumns: ["__tablepro_byte_length_1"]) - #expect(folded.columnOrigins == [id, data]) + fetched.foldUnloadedValues(UnloadedValueLayout(deferred: [.init(position: 1, type: nil, readsHead: false)])) + #expect(fetched.columnOrigins == [id, data]) + } + + @Test("A deferred column, which the engine reports no origin for, takes the key's table") + func foldedPageNamesDeferredOrigin() { + let id = PluginColumnOrigin(schema: "public", table: "posts", column: "id") + var fetched = QueryFetchResult( + columns: ["id", "body", "__tablepro_byte_length_1", "__tablepro_head_1"], + columnTypes: [.integer(rawType: "int4"), .text(rawType: "text"), .integer(rawType: "int4"), .text(rawType: "text")], + rows: [["1", .null, "70000", "lorem"]], + executionTime: 0, + rowsAffected: 0, + statusMessage: nil, + isTruncated: false, + resultColumnMeta: nil + ) + fetched.columnOrigins = [id, nil, nil, nil] + fetched.foldUnloadedValues(UnloadedValueLayout(deferred: [.init(position: 1, type: nil, readsHead: true)])) + #expect(fetched.columnOrigins == [id, PluginColumnOrigin(schema: "public", table: "posts", column: "body")]) } } @@ -237,4 +398,49 @@ struct TableRowsUnloadedValueTests { ) #expect(text == ByteCountFormatter.string(fromByteCount: 5_242_880, countStyle: .file)) } + + private static func cutText() -> TableRows { + TableRows.from( + queryRows: [["1", "lorem ipsum"]], + columns: ["id", "body"], + columnTypes: [.integer(rawType: "INT"), .text(rawType: "LONGTEXT")], + unloadedCells: [0: [1: 5_242_880]] + ) + } + + @Test("A cut text reads NULL, and its first characters are kept beside the row for the grid") + func cutTextReadsNull() { + let tableRows = Self.cutText() + let id = tableRows.rows[0].id + #expect(tableRows.value(at: 0, column: 1) == .null) + #expect(tableRows.unloadedHead(id, column: 1) == "lorem ipsum") + #expect(tableRows.unloadedByteCount(row: 0, column: 1) == 5_242_880) + } + + @Test("Loading a cut text drops its first characters with its mark") + func fillDropsHead() { + var tableRows = Self.cutText() + let id = tableRows.rows[0].id + tableRows.fillUnloaded([id: [1: .text("lorem ipsum dolor")]]) + #expect(tableRows.value(at: 0, column: 1) == .text("lorem ipsum dolor")) + #expect(tableRows.unloadedHead(id, column: 1) == nil) + } + + @Test("A masked column keeps no first characters, so its cut cells show only their size") + func maskedColumnKeepsNoHead() { + var tableRows = Self.cutText() + let id = tableRows.rows[0].id + tableRows.addMasks(ColumnMasks(styles: [1: .full])) + #expect(tableRows.unloadedHead(id, column: 1) == nil) + #expect(tableRows.unloadedByteCount(row: 0, column: 1) == 5_242_880) + } + + @Test("The grid shows a cut text's first characters, marked as the start of a longer value") + func placeholderShowsHead() { + let placeholder = DataGridCellContent.placeholder(for: "lorem ipsum", unloadedByteCount: 5_242_880) + let text = DataGridCellContent.resolvedDisplayText( + "lorem ipsum", placeholder: placeholder, nullDisplayString: "NULL" + ) + #expect(text == "lorem ipsum…") + } } diff --git a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift index cabfcf090c..2d54bb6ebc 100644 --- a/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/Engine/ConnectionEditorEngineIssueTests.swift @@ -67,9 +67,9 @@ struct ConnectionEditorEngineIssueTests { draft.options.binaryInlineLimitKilobytes = 0 #expect(issues(draft, mysql).contains { $0.row == .builtIn(.binaryInlineLimit) } == mysql.supportsBinaryInlineLimit) - let postgres = traits(.postgresql) - draft.retype(to: postgres, from: mysql) - #expect(!issues(draft, postgres).contains { $0.row == .builtIn(.binaryInlineLimit) }) + let sqlServer = traits(.mssql) + draft.retype(to: sqlServer, from: mysql) + #expect(!issues(draft, sqlServer).contains { $0.row == .builtIn(.binaryInlineLimit) }) } @Test("A client certificate without a key blocks nothing while SSL Mode is Disabled") diff --git a/apple/TableProTests/Views/DataGrid/DataGridCommandTests.swift b/apple/TableProTests/Views/DataGrid/DataGridCommandTests.swift index 565e4eba21..05fe3c75fc 100644 --- a/apple/TableProTests/Views/DataGrid/DataGridCommandTests.swift +++ b/apple/TableProTests/Views/DataGrid/DataGridCommandTests.swift @@ -639,6 +639,22 @@ struct DataGridResponderCommandTests { #expect(item.string(forType: DataGridViewController.rowDragType) == nil) } + @Test("A row dragged out names a value left on the server instead of dropping its first characters") + func rowDragNamesCutValue() throws { + let rows = TableRows.from( + queryRows: [[.text("1"), .text("lorem ipsum"), .null]], + columns: ["id", "body", "data"], + columnTypes: [.integer(rawType: "INT"), .text(rawType: "LONGTEXT"), .blob(rawType: "LONGBLOB")], + unloadedCells: [0: [1: 5_242_880, 2: 70_000]] + ) + let grid = CommandGrid(rows) + let item = try #require(grid.controller.rowDragPasteboardItem(forRow: 0)) + + let text = UnloadedValueText.notLoaded(byteCount: 5_242_880) + let binary = UnloadedValueText.notLoaded(byteCount: 70_000) + #expect(item.string(forType: .string) == "1\t\(text)\t\(binary)") + } + @Test("A focused grid answers Find itself; Find Next waits for a term") func findOpensTheGridsOwnBar() { let grid = CommandGrid(CommandRows.people) diff --git a/apple/TableProTests/Views/DataGrid/DataGridDisplayCacheTests.swift b/apple/TableProTests/Views/DataGrid/DataGridDisplayCacheTests.swift index c9d8a0741f..e53417072c 100644 --- a/apple/TableProTests/Views/DataGrid/DataGridDisplayCacheTests.swift +++ b/apple/TableProTests/Views/DataGrid/DataGridDisplayCacheTests.swift @@ -171,6 +171,23 @@ struct DataGridDisplayCacheTests { #expect(grid.model.display.cache.box(forID: .existing(1))?.values[0] == "C") } + @Test("The prewarm formats a cut text's first characters, as the draw does") + func prewarmShowsCutTextHead() async throws { + let grid = DisplayGrid(TableRows.from( + queryRows: [[.text("lorem ipsum")], [.text("dolor")]], + columns: ["body"], + columnTypes: [.text(rawType: "LONGTEXT")], + unloadedCells: [0: [0: 5_242_880]] + )) + let walk = try #require(grid.presenter.prewarmBatch(in: 0..<2, from: 0)) + let batch = try #require(walk.batch) + let formatted = await batch.formatted() + + #expect(grid.presenter.installPrewarmed(formatted, of: batch)) + #expect(grid.model.display.cache.box(forID: .existing(0))?.values[0] == "lorem ipsum") + #expect(grid.model.display.cache.box(forID: .existing(1))?.values[0] == "dolor") + } + @Test("A batch copies only rows with no text yet, and stops at its limit") func prewarmBatchSkipsCachedRows() throws { let rowCount = DataGridPrewarmBatch.rowLimit * 2 diff --git a/apple/TableProTests/Views/Main/ColumnCatalogLoadTests.swift b/apple/TableProTests/Views/Main/ColumnCatalogLoadTests.swift index 3d3d73cad6..293469b9fc 100644 --- a/apple/TableProTests/Views/Main/ColumnCatalogLoadTests.swift +++ b/apple/TableProTests/Views/Main/ColumnCatalogLoadTests.swift @@ -461,8 +461,8 @@ extension GlobalStateSuites { ) let stored = tabManager.tabs[0] - #expect(coordinator.unloadedValueLengthColumns(for: stored, sql: stored.content.query).count == 1) - #expect(coordinator.unloadedValueLengthColumns(for: stored, sql: "SELECT * FROM `files`").count == 2) + #expect(coordinator.unloadedValueLayout(for: stored, sql: stored.content.query)?.trailingColumns.count == 1) + #expect(coordinator.unloadedValueLayout(for: stored, sql: "SELECT * FROM `files`")?.trailingColumns.count == 2) } @Test("Reload sorts by the confirmed key, built on the confirmed columns rather than the rows on screen") diff --git a/apple/TableProTests/Views/Main/UnloadedValueFirstLoadTests.swift b/apple/TableProTests/Views/Main/UnloadedValueFirstLoadTests.swift index a3eddc910a..7637ae6a29 100644 --- a/apple/TableProTests/Views/Main/UnloadedValueFirstLoadTests.swift +++ b/apple/TableProTests/Views/Main/UnloadedValueFirstLoadTests.swift @@ -71,13 +71,24 @@ extension GlobalStateSuites { #expect(!query.contains("OCTET_LENGTH")) } - @Test("An engine with no byte length function reads every value inline", .unloadedNoDefaultSort) - func otherEngineReadsInline() async throws { + @Test("A PostgreSQL page leaves a large binary value on the server and reads its size", .unloadedNoDefaultSort) + func postgreSQLFirstPageDefersBinaryValues() async throws { let (coordinator, tabManager, tabId) = makeCoordinator(type: .postgresql) defer { coordinator.teardown() } let query = try #require(await firstLoadQuery(coordinator, tabManager, tabId: tabId)) + #expect(query.contains(#"CASE WHEN octet_length("data") <= 65536 THEN "data" END AS "data""#)) + #expect(query.contains(#"octet_length("data") AS "__tablepro_byte_length_2""#)) + } + + @Test("An engine with no large value functions reads every value inline", .unloadedNoDefaultSort) + func otherEngineReadsInline() async throws { + let (coordinator, tabManager, tabId) = makeCoordinator(type: .mssql) + defer { coordinator.teardown() } + + let query = try #require(await firstLoadQuery(coordinator, tabManager, tabId: tabId)) + #expect(!query.contains("CASE WHEN")) } } diff --git a/apple/changelog.d/4603.changed.1.md b/apple/changelog.d/4603.changed.1.md new file mode 100644 index 0000000000..72d69ed4e6 --- /dev/null +++ b/apple/changelog.d/4603.changed.1.md @@ -0,0 +1 @@ +Binary Value Limit in the connection editor is now Large Value Limit, and covers text and JSON too. diff --git a/apple/changelog.d/4603.changed.md b/apple/changelog.d/4603.changed.md new file mode 100644 index 0000000000..49d2dc622c --- /dev/null +++ b/apple/changelog.d/4603.changed.md @@ -0,0 +1 @@ +Tables on PostgreSQL, MySQL, MariaDB and SQLite leave large text, JSON and binary values on the server until needed.