Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,15 @@ public enum BigtableRowWrites {
BigtableRequest(verb: .delete, table: table, key: key)
}

// The locator is the base64 of the key the row was read with; the _key text is only the fallback.
public static func originalKey(locator: String?, keyCell: BigtableRowSet.Cell?) throws -> Data? {
guard let locator else { return try keyCell.flatMap { try key($0) } }
guard let decoded = Data(base64Encoded: locator), !decoded.isEmpty else {
throw BigtableError.malformedResponse(String(localized: "This row cannot be found again from what was read. Reload the table."))
}
return decoded
}

public static func key(_ cell: BigtableRowSet.Cell) throws -> Data? {
switch cell {
case .absent: return nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,18 @@ public enum BigtableBytes {

/// The bytes as text when `display` would show them as themselves.
public static func printableText(_ data: Data) -> String? {
guard let text = String(data: data, encoding: .utf8), isPrintable(text), !text.hasPrefix(base64Prefix) else {
guard let text = exactText(data), isPrintable(text), !text.hasPrefix(base64Prefix) else {
return nil
}
return text
}

// String(data:encoding:) drops a leading byte order mark, which names a different row or column.
static func exactText(_ data: Data) -> String? {
let text = String(decoding: data, as: UTF8.self) // swiftlint:disable:this optional_data_string_conversion
return text.utf8.elementsEqual(data) ? text : nil
}

public static func parse(_ text: String) throws -> Data {
guard text.hasPrefix(base64Prefix) else { return Data(text.utf8) }
guard let data = Data(base64Encoded: String(text.dropFirst(base64Prefix.count))) else {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
//
// CassandraCellLifetime.swift
// TableProCassandraCore
//

import Foundation

// A write resets the TTL of every cell it writes to its own USING TTL, or to the table's default without one, so an
// edit has to carry what each cell had left when it was read.
public enum CassandraCellLifetime: Hashable, Sendable {
case expiring(seconds: Int)
case permanent

// Nil for a cell read as null, whose edit is written without a TTL as before.
public init?(valueIsNull: Bool, timeToLive: String?) {
guard !valueIsNull else { return nil }
guard let timeToLive else {
self = .permanent
return
}
guard let seconds = Int(timeToLive), seconds > 0 else { return nil }
self = .expiring(seconds: seconds)
}

public static func remaining(seconds: Int, after elapsed: Duration) -> Int {
max(1, seconds - Int(max(elapsed.components.seconds, 0)))
}
}

// The lifetimes of one row's cells as a browse read them, with what the table says about naming the row.
public struct CassandraRowLifetimes: Sendable, Equatable {
public let columns: [String]
public let lifetimes: [CassandraCellLifetime?]
public let readAt: ContinuousClock.Instant
public let layout: CassandraTableLayout

// Nil when every cell would be written the way a write without USING writes it, so nothing is kept for the row.
public init?(
columns: [String],
lifetimes: [CassandraCellLifetime?],
readAt: ContinuousClock.Instant,
layout: CassandraTableLayout
) {
guard columns.count == lifetimes.count else { return nil }
let changesAWrite = lifetimes.contains { lifetime in
switch lifetime {
case .expiring: return true
case .permanent: return layout.defaultTimeToLive != 0
case nil: return false
}
}
guard changesAWrite else { return nil }
self.columns = columns
self.lifetimes = lifetimes
self.readAt = readAt
self.layout = layout
}

// A cell whose TTL ran out since the read is gone from the server, so an edit of it would live for one second.
public func hasExpired(_ column: String, at now: ContinuousClock.Instant) -> Bool {
guard let index = columns.firstIndex(of: column), case .expiring(let seconds) = lifetimes[index] else {
return false
}
return readAt.duration(to: now) >= .seconds(seconds)
}

// The USING TTL a write of `column` keeps the cell's lifetime with, or nil for none. A cell that never expired
// is written with 0 unless the table's default TTL is 0, where a write without USING keeps it the same.
public func timeToLive(of column: String, at now: ContinuousClock.Instant) -> Int? {
guard let index = columns.firstIndex(of: column), let lifetime = lifetimes[index] else { return nil }
switch lifetime {
case .expiring(let seconds):
return CassandraCellLifetime.remaining(seconds: seconds, after: readAt.duration(to: now))
case .permanent:
return layout.defaultTimeToLive == 0 ? nil : 0
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//

import Foundation
import TableProSQLGrammar

// A grid write names its row by key and is conditioned on it: an INSERT is an upsert, and an UPDATE writes its cells
// whether or not the row is there, so either would otherwise replace or recreate a row the grid never showed.
Expand All @@ -13,6 +14,9 @@ public enum CassandraConditionalWrite {
public static let insertCondition = "IF NOT EXISTS"
public static let updateCondition = "IF EXISTS"

private static let grammar = SQLLexicalReadings.resolve(databaseTypeId: "Cassandra", declared: nil, session: nil)
.execution

public enum Refusal: Sendable, Equatable {
case keyTaken
case rowMissing
Expand All @@ -23,12 +27,29 @@ public enum CassandraConditionalWrite {
+ insertCondition
}

public static func updateStatement(target: String, assignments: [String], keyCondition: String) -> String {
"UPDATE \(target) SET \(assignments.joined(separator: ", ")) WHERE \(keyCondition) \(updateCondition)"
public static func updateStatement(
target: String,
assignments: [String],
keyCondition: String,
timeToLive: Int? = nil
) -> String {
"UPDATE \(target)\(usingClause(timeToLive: timeToLive)) SET \(assignments.joined(separator: ", ")) "
+ "WHERE \(keyCondition) \(updateCondition)"
}

public static func usingClause(timeToLive: Int?) -> String {
timeToLive.map { " USING TTL \($0)" } ?? ""
}

public static func batch(_ statements: [String]) -> String {
"BEGIN BATCH " + statements.map { $0 + "; " }.joined() + "APPLY BATCH"
}

public static func refusal(statement: String, firstColumn: String?, firstValue: String?) -> Refusal? {
guard firstColumn == appliedColumn, firstValue?.lowercased() == "false" else { return nil }
if let statements = CQLBatch.statements(in: statement, grammar: grammar) {
return batchRefusal(statements)
}
let normalized = statement.uppercased()
if normalized.hasPrefix("INSERT"), normalized.hasSuffix(" " + insertCondition) {
return .keyTaken
Expand All @@ -38,4 +59,25 @@ public enum CassandraConditionalWrite {
}
return nil
}

// An edit whose cells keep different TTLs is a batch of UPDATEs on the row, each IF EXISTS or, for static
// cells, unconditioned. A batch with any other statement or condition is left to its result.
private static func batchRefusal(_ statements: [String]) -> Refusal? {
var holdsRow = false
for statement in statements {
let words = codeWords(statement)
guard words.first == "UPDATE" else { return nil }
guard let condition = words.firstIndex(of: "IF") else { continue }
guard words[condition...].elementsEqual(["IF", "EXISTS"]) else { return nil }
holdsRow = true
}
return holdsRow ? .rowMissing : nil
}

private static func codeWords(_ statement: String) -> [String] {
SQLCodeProjection.code(of: statement, grammar: grammar)
.uppercased()
.split { !($0.isLetter || $0.isNumber || $0 == "_") }
.map(String.init)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//
// CassandraLifetimeRead.swift
// TableProCassandraCore
//

import Foundation

// The browse the plugin sends with a TTL() selector after the shown columns for each one that can carry its own
// TTL. `SELECT *` takes no other selector, so it is spelled out in the order the server returns it.
public enum CassandraLifetimeRead {
public struct Plan: Equatable, Sendable {
public let cql: String
public let shownColumns: [String]
// The column of each TTL() selector, in the order the selectors follow the shown columns.
public let lifetimeColumns: [String]
public let lifetimeValueIndices: [Int]
public let keyIndices: [String: Int]
}

// Nil unless `cql` is a browse of `target` as the renderer writes it, every key column is shown, and at least one
// shown column takes a TTL() selector.
public static func plan(cql: String, target: String, layout: CassandraTableLayout) -> Plan? {
guard let select = select(of: cql, target: target) else { return nil }
let shown = select.columns ?? layout.selectOrder
var lifetimeColumns: [String] = []
var lifetimeValueIndices: [Int] = []
for (index, column) in shown.enumerated()
where layout.acceptsTimeToLive(column) && !lifetimeColumns.contains(column) {
lifetimeColumns.append(column)
lifetimeValueIndices.append(index)
}
guard !lifetimeColumns.isEmpty else { return nil }
var keyIndices: [String: Int] = [:]
for key in layout.primaryKey {
guard let index = shown.firstIndex(of: key) else { return nil }
keyIndices[key] = index
}
let selectors = shown.map(CassandraObjectQueries.quote)
+ lifetimeColumns.map { "TTL(\(CassandraObjectQueries.quote($0)))" }
return Plan(
cql: "SELECT \(selectors.joined(separator: ", ")) FROM \(target)\(select.tail)",
shownColumns: shown,
lifetimeColumns: lifetimeColumns,
lifetimeValueIndices: lifetimeValueIndices,
keyIndices: keyIndices
)
}

private struct Select {
// Nil for `*`.
let columns: [String]?
let tail: String
}

private static func select(of cql: String, target: String) -> Select? {
var rest = Substring(cql).unicodeScalars
guard consume("SELECT ", from: &rest) else { return nil }
var columns: [String]?
if !consume("* ", from: &rest) {
var names: [String] = []
repeat {
guard let name = quotedName(from: &rest) else { return nil }
names.append(name)
} while consume(", ", from: &rest)
guard consume(" ", from: &rest) else { return nil }
columns = names
}
guard consume("FROM " + target, from: &rest) else { return nil }
let tail = String(Substring(rest))
guard tail.isEmpty || tail.hasPrefix(" WHERE ") else { return nil }
return Select(columns: columns, tail: tail)
}

private static func consume(_ text: String, from rest: inout Substring.UnicodeScalarView) -> Bool {
guard rest.starts(with: text.unicodeScalars) else { return false }
rest = rest.dropFirst(text.unicodeScalars.count)
return true
}

// A double-quoted identifier, `""` standing for one quote, as SQLQuoting.identifier writes it.
private static func quotedName(from rest: inout Substring.UnicodeScalarView) -> String? {
guard consume("\"", from: &rest) else { return nil }
var name = String.UnicodeScalarView()
while let scalar = rest.first {
rest = rest.dropFirst()
guard scalar == "\"" else {
name.append(scalar)
continue
}
guard consume("\"", from: &rest) else { return String(name) }
name.append(scalar)
}
return nil
}
}
Loading
Loading