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 @@ -5,6 +5,8 @@ public protocol SQLCompletionCatalog: Sendable {
func resolveAlias(_ aliasOrName: String, in references: [TableReference]) async -> String?
func columnCompletionItems(for tableName: String, schema: String?) async -> [SQLCompletionItem]
func tableCompletionItems() async -> [SQLCompletionItem]
// The same tables, in the same order, folded once per list; nil ranks `tableCompletionItems()` instead.
func tableNameIndex() async -> SQLCompletionNameIndex?
func tableCompletionItems(inSchema schema: String) async -> [SQLCompletionItem]
func tableCompletionItems(inSchema schema: String, isQuoted: Bool) async -> [SQLCompletionItem]
func schemaCompletionItems() async -> [SQLCompletionItem]
Expand All @@ -25,6 +27,8 @@ public extension SQLCompletionCatalog {
await tableCompletionItems(inSchema: schema)
}

func tableNameIndex() async -> SQLCompletionNameIndex? { nil }

func foreignKeys(of tableName: String, schema: String?) async -> [SQLCompletionForeignKey] { [] }

func writtenText(of identifier: SQLCompletionIdentifier) -> String? { nil }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import Foundation

// A catalog's table list, folded once per list so a request ranks it without building an item per table.
// Names of printable ASCII rank on their UTF-16 keys, where the provider's string matching reads the same units;
// any other name goes through the provider's own matcher, so the order never depends on which path a name took.
public struct SQLCompletionNameIndex: Sendable {
let names: [String]
let isView: [Bool]
// The folded key of every simple row, back to back; a row's key is `units[starts[row]..<starts[row + 1]]`.
let units: [UInt16]
let starts: [Int32]
let isSimple: [Bool]
// Simple rows in key order, ties in list order, so a typed prefix is one contiguous range.
let sortedRows: [Int32]
let complexRows: [Int32]

public var count: Int { names.count }

public init(tables: [(name: String, isView: Bool)]) {
var names: [String] = []
var isView: [Bool] = []
var units: [UInt16] = []
var starts: [Int32] = [0]
var isSimple: [Bool] = []
var complexRows: [Int32] = []
names.reserveCapacity(tables.count)
isView.reserveCapacity(tables.count)
starts.reserveCapacity(tables.count + 1)
isSimple.reserveCapacity(tables.count)

for (row, table) in tables.enumerated() {
names.append(table.name)
isView.append(table.isView)
if let key = Self.simpleKey(table.name) {
units.append(contentsOf: key)
isSimple.append(true)
} else {
isSimple.append(false)
complexRows.append(Int32(row))
}
starts.append(Int32(units.count))
}

var sortedRows = (0..<Int32(tables.count)).filter { isSimple[Int($0)] }
units.withUnsafeBufferPointer { buffer in
sortedRows.sort { lhs, rhs in
let order = Self.compare(
buffer, Int(starts[Int(lhs)]), Int(starts[Int(lhs) + 1]),
buffer, Int(starts[Int(rhs)]), Int(starts[Int(rhs) + 1])
)
return order == 0 ? lhs < rhs : order < 0
}
}

self.names = names
self.isView = isView
self.units = units
self.starts = starts
self.isSimple = isSimple
self.sortedRows = sortedRows
self.complexRows = complexRows
}

func item(at row: Int) -> SQLCompletionItem {
SQLCompletionItem.table(names[row], isView: isView[row])
}

// The provider's matcher lowercases the label; on printable ASCII that is the same units, one per character.
static func simpleKey(_ text: String) -> [UInt16]? {
var key: [UInt16] = []
key.reserveCapacity(text.utf8.count)
for byte in text.utf8 {
guard byte >= 0x20, byte <= 0x7E else { return nil }
key.append(UInt16(byte >= 0x41 && byte <= 0x5A ? byte + 0x20 : byte))
}
return key
}

static func compare(
_ left: UnsafeBufferPointer<UInt16>, _ leftStart: Int, _ leftEnd: Int,
_ right: UnsafeBufferPointer<UInt16>, _ rightStart: Int, _ rightEnd: Int
) -> Int {
var leftIndex = leftStart
var rightIndex = rightStart
while leftIndex < leftEnd, rightIndex < rightEnd {
let lhs = left[leftIndex]
let rhs = right[rightIndex]
if lhs != rhs { return lhs < rhs ? -1 : 1 }
leftIndex += 1
rightIndex += 1
}
let leftLength = leftEnd - leftStart
let rightLength = rightEnd - rightStart
return leftLength == rightLength ? 0 : (leftLength < rightLength ? -1 : 1)
}

// The `sortedRows` slice whose keys start with `prefix`.
func prefixRange(_ prefix: [UInt16]) -> Range<Int> {
units.withUnsafeBufferPointer { keys in
prefix.withUnsafeBufferPointer { typed in
// Below the range a key orders before the prefix; in it, its first units equal the prefix.
func ordersBelow(_ row: Int32, inclusive: Bool) -> Bool {
let start = Int(starts[Int(row)])
let end = min(Int(starts[Int(row) + 1]), start + typed.count)
let order = Self.compare(keys, start, end, typed, 0, typed.count)
return inclusive ? order <= 0 : order < 0
}
let lower = partition { !ordersBelow($0, inclusive: false) }
let upper = partition { !ordersBelow($0, inclusive: true) }
return lower..<max(lower, upper)
}
}
}

private func partition(_ isAtOrAbove: (Int32) -> Bool) -> Int {
var low = 0
var high = sortedRows.count
while low < high {
let middle = (low + high) / 2
if isAtOrAbove(sortedRows[middle]) {
high = middle
} else {
low = middle + 1
}
}
return low
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public final class SQLCompletionProvider: Sendable {
private let defaultMaxSuggestions = 20

// What a quoted name can hold: a keyword or a call typed between the quotes would be read as a name.
private static let nameKinds: Set<SQLCompletionKind> = [.table, .view, .column, .schema, .alias]
static let nameKinds: Set<SQLCompletionKind> = [.table, .view, .column, .schema, .alias]

private func maxSuggestions(for clauseType: SQLClauseType) -> Int {
switch clauseType {
Expand Down Expand Up @@ -68,14 +68,17 @@ public final class SQLCompletionProvider: Sendable {
public func completionSession(
text: String,
cursorPosition: Int,
forcedTableReferences: [TableReference]? = nil
forcedTableReferences: [TableReference]? = nil,
suppressesEmptyPrefix: Bool = false
) async -> SQLCompletionSession {
var context = contextAnalyzer.analyze(query: text, cursorPosition: cursorPosition, grammar: grammar)
if let forcedTableReferences {
context = context.replacingTableReferences(forcedTableReferences)
}

if context.isInsideString || context.isInsideComment || Task.isCancelled {
// A suppressed request never reads the catalog: at a statement start that is every table.
if context.isInsideString || context.isInsideComment || Task.isCancelled
|| suppressesEmptyPrefix && SQLCompletionTriggerPolicy.suppressesEmptyPrefix(context, isManualTrigger: false) {
return SQLCompletionSession(items: [], candidates: [], context: context, candidatesTruncated: false)
}

Expand All @@ -92,33 +95,6 @@ public final class SQLCompletionProvider: Sendable {
)
}

// A catalog can list tens of thousands of tables, so joining, filtering and sorting them leaves the caller's actor.
@concurrent
private static func rankedSession(
_ segments: [[SQLCompletionItem]],
context: SQLContext,
limit: Int,
pool: Int
) async -> SQLCompletionSession {
var candidates = Array(segments.joined())
if context.quotedName != nil {
candidates = candidates.filter { nameKinds.contains($0.kind) }
}

if !context.prefix.isEmpty {
candidates = filterByPrefix(candidates, prefix: context.prefix)
}

candidates = rankResults(candidates, prefix: context.prefix, context: context)

return SQLCompletionSession(
items: Array(candidates.prefix(limit)),
candidates: Array(candidates.prefix(pool)),
context: context,
candidatesTruncated: candidates.count > pool
)
}

// A candidate cut at the opening prefix can never lead for a longer one, and PostgreSQL declares more `T`
// functions than the popup shows rows, every one outranking `TRUE` for the letter `t`.
public func filterRankAndLimit(
Expand Down Expand Up @@ -158,8 +134,8 @@ public final class SQLCompletionProvider: Sendable {
// In emission order. The catalog's table list stays a segment of its own, so the caller never copies it.
private func getCandidates( // swiftlint:disable:this function_body_length
for context: SQLContext
) async -> [[SQLCompletionItem]] {
var segments: [[SQLCompletionItem]] = []
) async -> [CandidateSegment] {
var segments: [CandidateSegment] = []
var items: [SQLCompletionItem] = []

// A dot prefix is a table or alias first, then a schema (its tables) or a database (its schemas, or its
Expand All @@ -174,7 +150,7 @@ public final class SQLCompletionProvider: Sendable {
}) {
let columns = await derivedColumns(of: derived)
if !columns.isEmpty {
return [columns.map { SQLCompletionItem.column($0, dataType: nil, tableName: derived.identifier) }]
return [.items(columns.map { SQLCompletionItem.column($0, dataType: nil, tableName: derived.identifier) })]
}
}
if let tableName = await catalog.resolveAlias(dotPrefix, in: context.tableReferences) {
Expand All @@ -194,12 +170,12 @@ public final class SQLCompletionProvider: Sendable {
}
}
}
return [items]
return [.items(items)]
}

switch context.clauseType {
case .from, .join:
segments = [await catalog?.tableCompletionItems() ?? []]
segments = [await tableSegment()]
items = await catalog?.namespaceCompletionItems() ?? []
items += filterKeywords([
"INNER JOIN", "LEFT JOIN", "RIGHT JOIN", "FULL JOIN",
Expand All @@ -210,7 +186,7 @@ public final class SQLCompletionProvider: Sendable {
])

case .into:
segments = [await catalog?.tableCompletionItems() ?? []]
segments = [await tableSegment()]
items = filterKeywords([
"VALUES", "SELECT", "SET",
"INNER JOIN", "LEFT JOIN", "RIGHT JOIN", "FULL JOIN",
Expand Down Expand Up @@ -448,31 +424,38 @@ public final class SQLCompletionProvider: Sendable {
])

case .dropObject:
segments = [await catalog?.tableCompletionItems() ?? []]
segments = [await tableSegment()]
items = filterKeywords(["IF EXISTS", "CASCADE", "RESTRICT"])

case .createIndex:
if context.tableReferences.isEmpty {
segments = [await catalog?.tableCompletionItems() ?? []]
segments = [await tableSegment()]
items = filterKeywords(["ON"])
} else {
items = await columnItems(for: context.tableReferences)
items += filterKeywords(["USING", "BTREE", "HASH", "GIN", "GIST"])
}

case .createView:
segments = [filterKeywords(["SELECT", "AS"]), await catalog?.tableCompletionItems() ?? []]
segments = [.items(filterKeywords(["SELECT", "AS"])), await tableSegment()]

case .castTarget:
items = castTargetCompletionItems()

case .unknown:
segments = [statementStartCompletionItems(), await catalog?.tableCompletionItems() ?? []]
segments = [.items(statementStartCompletionItems()), await tableSegment()]
}

items += favoriteCompletions(matching: context.prefix)

return segments + [items]
return segments + [.items(items)]
}

// A catalog with an index ranks its table list without an item per table; any other hands the items over.
private func tableSegment() async -> CandidateSegment {
guard let catalog else { return .items([]) }
if let index = await catalog.tableNameIndex() { return .tables(index) }
return .items(await catalog.tableCompletionItems())
}

private func favoriteCompletions(matching prefix: String) -> [SQLCompletionItem] {
Expand Down Expand Up @@ -750,7 +733,7 @@ public final class SQLCompletionProvider: Sendable {

// Resolves `matchedRanges` and the fuzzy-only `fuzzyPenalty` once per candidate, so ranking never matches again.
// Both are assigned rather than accumulated, so filtering a filtered list is idempotent.
private static func filterByPrefix(_ items: [SQLCompletionItem], prefix: String) -> [SQLCompletionItem] {
static func filterByPrefix(_ items: [SQLCompletionItem], prefix: String) -> [SQLCompletionItem] {
guard !prefix.isEmpty else {
var reset = items
for i in reset.indices {
Expand Down Expand Up @@ -887,49 +870,69 @@ public final class SQLCompletionProvider: Sendable {
Self.calculateScore(for: item, prefix: prefix, context: context)
}

// Lower is better.
private static func calculateScore(for item: SQLCompletionItem, prefix: String, context: SQLContext) -> Int {
var score = item.sortPriority + item.fuzzyPenalty
static func calculateScore(for item: SQLCompletionItem, prefix: String, context: SQLContext) -> Int {
score(
kind: item.kind,
priority: item.sortPriority + item.fuzzyPenalty,
startsWithPrefix: item.filterText.hasPrefix(prefix),
equalsPrefix: item.filterText == prefix,
labelLength: (item.label as NSString).length,
prefixIsEmpty: prefix.isEmpty,
context: context
)
}

// Lower is better. Takes the parts of a candidate the score reads, so an indexed name scores without an item.
static func score(
kind: SQLCompletionKind,
priority: Int,
startsWithPrefix: Bool,
equalsPrefix: Bool,
labelLength: Int,
prefixIsEmpty: Bool,
context: SQLContext
) -> Int {
var score = priority

if item.filterText.hasPrefix(prefix) {
if startsWithPrefix {
score -= 500
}

if item.filterText == prefix {
if equalsPrefix {
score -= 1_000
}

// With nothing typed and tables in scope, tables lead in an operand slot (`... JOIN |`) and keywords lead at
// a clause transition (`FROM users |`).
if prefix.isEmpty && !context.tableReferences.isEmpty && !context.isAfterComma {
if prefixIsEmpty && !context.tableReferences.isEmpty && !context.isAfterComma {
if context.expectsObjectName {
if item.kind == .table || item.kind == .view || item.kind == .schema {
if kind == .table || kind == .view || kind == .schema {
score -= 300
}
} else if item.kind == .keyword {
} else if kind == .keyword {
score -= 300
}
} else {
switch context.clauseType {
case .from, .join, .into, .dropObject, .createIndex:
if item.kind == .table || item.kind == .view {
if kind == .table || kind == .view {
score -= 200
}
case .select, .where_, .and, .on, .having, .groupBy, .orderBy,
.returning, .using, .window:
if item.kind == .column || item.kind == .joinCondition {
if kind == .column || kind == .joinCondition {
score -= 200
}
case .set, .insertColumns:
if item.kind == .column {
if kind == .column {
score -= 300
}
default:
break
}
}

score += (item.label as NSString).length
score += labelLength

return score
}
Expand Down
Loading
Loading