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
47 changes: 39 additions & 8 deletions src/autocomplete/content-assist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ export interface ContentAssistResult {
nextTokenTypes: TokenType[]
/** Tables/aliases found in the query (for column suggestions) */
tablesInScope: TableRef[]
/** Target table of a COMPACT PARTITION WHERE predicate, if applicable. */
compactFilterTable?: string
/** Columns from CTEs, keyed by CTE name (lowercase) */
cteColumns: Record<string, { name: string; type: string }[]>
/** The tokens before the cursor */
Expand Down Expand Up @@ -1350,7 +1352,9 @@ function computeSuggestions(tokens: IToken[]): ComputeResult {
const objectColumnRuleStack = suggestions.find(
(s) =>
s.nextTokenType.name === "IdentifierKeyword" &&
(s.ruleStack.includes("keyColumn") || isExpiryPredicatePath(s.ruleStack)),
(s.ruleStack.includes("keyColumn") ||
s.ruleStack.includes("alterTableCompactAction") ||
isExpiryPredicatePath(s.ruleStack)),
)?.ruleStack

return {
Expand Down Expand Up @@ -1520,14 +1524,15 @@ function queryOutputScope(
}

/**
* Scope for DEDUP keys and EXPIRE ROWS KEEP / WHEN columns. These name a
* Scope for DEDUP keys, EXPIRE ROWS KEEP / WHEN columns, and COMPACT filters. These name a
* column of the table or view being defined or altered (the server resolves
* them against the new table's columns / the query's output metadata):
* - CREATE TABLE (cols ...): the column definitions of the statement;
* - CREATE TABLE ... AS (query) and CREATE MATERIALIZED VIEW: the query's
* output (see queryOutput);
* - ALTER MATERIALIZED VIEW: the named target, even with an unfinished policy;
* - ALTER TABLE: the target, already in scope.
* - COMPACT PARTITION WHERE: only the target's designated timestamp.
* Returns undefined when the default scope applies.
*/
function objectColumnScope(
Expand All @@ -1538,8 +1543,27 @@ function objectColumnScope(
| {
tables: TableRef[]
columns: Record<string, { name: string; type: string }[]>
compactFilterTable?: string
}
| undefined {
if (ruleStack.includes("alterTableCompactAction")) {
const table = statementTokens.findIndex(
(token, i) =>
token.tokenType.name === "Table" &&
statementTokens[i - 1]?.tokenType.name === "Alter",
)
if (table < 0) return undefined
let target = table + 1
while (statementTokens[target + 1]?.tokenType.name === "Dot") target += 2
const token = statementTokens[target]
if (!token) return undefined
const name =
token.tokenType.name === "StringLiteral"
? token.image.slice(1, -1)
: namePart(token)
return { tables: [{ table: name }], columns: {}, compactFilterTable: name }
}

// The query after AS: `AS ( query )` or an unparenthesized query that ends
// before the clause the slot belongs to.
const queryAfter = (as: number, stopAt: string): IToken[] => {
Expand Down Expand Up @@ -1867,8 +1891,9 @@ export function getContentAssist(
}
}

// DEDUP keys and retention expressions bind against the object being
// defined or altered, rather than the defining SELECT's source tables.
// DEDUP keys, retention expressions, and COMPACT predicates bind against
// the object being defined or altered.
let compactFilterTable: string | undefined
if (objectColumnRuleStack) {
let start = 0
for (let j = 0; j < tokensForAssist.length; j++) {
Expand All @@ -1882,10 +1907,15 @@ export function getContentAssist(
if (scope) {
tablesInScope.splice(0, tablesInScope.length, ...scope.tables)
Object.assign(cteColumns, scope.columns)
// Policy expressions can suggest functions, but table names and the
// synthetic output scope are not operands. Nested SELECT paths retain
// their ordinary table suggestions.
if (isExpiryPredicatePath(objectColumnRuleStack)) suggestTables = false
compactFilterTable = scope.compactFilterTable
// These predicates can suggest functions, but table names and the
// synthetic output scope are not operands.
if (
compactFilterTable !== undefined ||
isExpiryPredicatePath(objectColumnRuleStack)
) {
suggestTables = false
}
}
}

Expand Down Expand Up @@ -1914,6 +1944,7 @@ export function getContentAssist(
return {
nextTokenTypes,
tablesInScope,
compactFilterTable,
cteColumns,
tokensBefore: tokens,
isMidWord,
Expand Down
18 changes: 17 additions & 1 deletion src/autocomplete/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ export function createAutocompleteProvider(
const {
nextTokenTypes,
tablesInScope,
compactFilterTable,
cteColumns,
tokensBefore,
isMidWord,
Expand All @@ -205,13 +206,28 @@ export function createAutocompleteProvider(
} = getContentAssist(query, cursorOffset)

// Merge CTE columns into the schema so getColumnsInScope() can find them
const effectiveSchema =
let effectiveSchema =
Object.keys(cteColumns).length > 0
? {
...normalizedSchema,
columns: { ...normalizedSchema.columns, ...cteColumns },
}
: normalizedSchema
if (compactFilterTable !== undefined) {
const table = compactFilterTable.toLowerCase()
const timestamp = normalizedSchema.tables
.find((t) => t.name.toLowerCase() === table)
?.designatedTimestamp?.toLowerCase()
const columns = normalizedSchema.columns[table] ?? []
effectiveSchema = {
...normalizedSchema,
columns: {
[table]: columns.filter(
(col) => col.name.toLowerCase() === timestamp,
),
},
}
}

// When mid-word, the last token in tokensBefore is a partial word
// the user is still typing. It may have been captured as a table name
Expand Down
2 changes: 2 additions & 0 deletions src/formatter/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ const selectStarters: ReadonlySet<string> = new Set([
"Declare",
"Identifier",
"QuotedIdentifier",
"Compact",
"Residual",
"LParen",
])

Expand Down
39 changes: 37 additions & 2 deletions src/formatter/phrases.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { StatementKind } from "./context"
import { isSignificant, StatementKind } from "./context"
import { StreamToken } from "./lexer"

export type PhraseRole = "clause" | "join" | "setOp" | "action"
Expand Down Expand Up @@ -153,7 +153,11 @@ export const clausePhrases: Record<StatementKind, Phrase[]> = {
...clause(["Create", "Live", "View"]),
...createOptionPhrases,
],
alterTable: [...clause(["Alter", "Table"]), ...alterActionPhrases],
alterTable: [
...clause(["Alter", "Table"]),
...alterActionPhrases,
...action(["Compact"]),
],
alterMaterializedView: [
...clause(["Alter", "Materialized", "View"]),
...alterActionPhrases,
Expand All @@ -171,6 +175,31 @@ export const continuesPhrase = (current: Phrase | null, next: Phrase) =>
current !== null &&
(continuations[phraseKey(current)]?.has(phraseKey(next)) ?? false)

const isAlterTableActionStart = (tokens: StreamToken[], start: number) => {
const nextSignificant = (from: number) => {
while (from < start && !isSignificant(tokens[from])) from++
return from
}
let alter = nextSignificant(0)
if (tokens[alter]?.tokenName === "Explain") {
alter = nextSignificant(alter + 1)
}
const table = nextSignificant(alter + 1)
if (
tokens[alter]?.tokenName !== "Alter" ||
tokens[table]?.tokenName !== "Table"
) {
return false
}
let target = nextSignificant(table + 1)
let actionStart = nextSignificant(target + 1)
while (actionStart < start && tokens[actionStart].tokenName === "Dot") {
target = nextSignificant(actionStart + 1)
actionStart = nextSignificant(target + 1)
}
return actionStart === start
}

const matchSingle = (
tokens: StreamToken[],
start: number,
Expand All @@ -182,6 +211,12 @@ const matchSingle = (
if (index >= tokens.length || tokens[index].tokenName !== name) return null
index++
}
if (
phrase.names[0] === "Compact" &&
!isAlterTableActionStart(tokens, start)
) {
return null
}
return { phrase, endIndex: index }
}

Expand Down
4 changes: 4 additions & 0 deletions src/grammar/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export const scalarFunctions: string[] = [
"ceil",
"ceiling",
"coalesce",
"cold_storage_release_pins",
"concat",
"cos",
"cot",
Expand Down Expand Up @@ -327,6 +328,9 @@ export const tableValuedFunctions: string[] = [
"backup_status",
"backups",
"checkpoint_status",
"cold_storage_compactions",
"cold_storage_pin_owners",
"cold_storage_pins",
"export_activity",
"files",
"generate_series",
Expand Down
2 changes: 2 additions & 0 deletions src/grammar/keywords.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export const keywords: string[] = [
"columns",
"commit",
"commitLag",
"compact",
"compile",
"compression_codec",
"compression_level",
Expand Down Expand Up @@ -186,6 +187,7 @@ export const keywords: string[] = [
"replace",
"replica",
"reset",
"residual",
"resource",
"respect",
"resume",
Expand Down
16 changes: 16 additions & 0 deletions src/parser/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,8 @@ export type AlterTableAction =
| SquashPartitionsAction
| ForceDropPartitionAction
| ForceReindexParquetAction
| CompactPartitionAction
| CompactCancelAction
| SetParamAction
| SetTtlAction
| SetTableFormatAction
Expand Down Expand Up @@ -686,6 +688,20 @@ export interface ForceReindexParquetAction {
partitions?: string[]
}

/** Enterprise: COMPACT [BASE | RESIDUAL] PARTITION { LIST ... | WHERE ... } */
export interface CompactPartitionAction {
actionType: "compactPartition"
/** Omitted for the default mode, which does both */
mode?: "base" | "residual"
partitions?: string[]
where?: Expression
}

/** Enterprise: COMPACT CANCEL */
export interface CompactCancelAction {
actionType: "compactCancel"
}

export interface SetParamAction {
actionType: "setParam"
params: TableParam[]
Expand Down
34 changes: 33 additions & 1 deletion src/parser/cst-types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1682,6 +1682,7 @@ export type AlterTableActionCstChildren = {
Squash?: IToken[];
Partitions?: IToken[];
alterTableForceAction?: AlterTableForceActionCstNode[];
alterTableCompactAction?: AlterTableCompactActionCstNode[];
Param?: IToken[];
tableParam?: (TableParamCstNode)[];
Ttl?: IToken[];
Expand Down Expand Up @@ -1761,6 +1762,35 @@ export type AlterTableForceActionCstChildren = {
identifier?: IdentifierCstNode[];
};

export interface AlterTableCompactActionCstNode extends CstNode {
name: "alterTableCompactAction";
children: AlterTableCompactActionCstChildren;
}

export type AlterTableCompactActionCstChildren = {
Compact: IToken[];
Cancel?: IToken[];
Base?: IToken[];
Residual?: IToken[];
Partition?: IToken[];
List?: IToken[];
compactPartitionName?: (CompactPartitionNameCstNode)[];
Comma?: IToken[];
Where?: IToken[];
expression?: ExpressionCstNode[];
};

export interface CompactPartitionNameCstNode extends CstNode {
name: "compactPartitionName";
children: CompactPartitionNameCstChildren;
}

export type CompactPartitionNameCstChildren = {
StringLiteral?: IToken[];
QuotedIdentifier?: IToken[];
NumberLiteral?: IToken[];
};

export interface ConvertPartitionTargetCstNode extends CstNode {
name: "convertPartitionTarget";
children: ConvertPartitionTargetCstChildren;
Expand Down Expand Up @@ -2956,13 +2986,13 @@ export type PrimaryExpressionCstChildren = {
castExpression?: CastExpressionCstNode[];
caseExpression?: CaseExpressionCstNode[];
timestampWithTimeZoneLiteral?: TimestampWithTimeZoneLiteralCstNode[];
doublePrecisionLiteral?: DoublePrecisionLiteralCstNode[];
arrayLiteral?: ArrayLiteralCstNode[];
functionCall?: FunctionCallCstNode[];
literal?: LiteralCstNode[];
VariableReference?: IToken[];
BindVariable?: IToken[];
identifierExpression?: IdentifierExpressionCstNode[];
doublePrecisionLiteral?: DoublePrecisionLiteralCstNode[];
LParen?: IToken[];
selectStatement?: SelectStatementCstNode[];
expression?: (ExpressionCstNode)[];
Expand Down Expand Up @@ -3557,6 +3587,8 @@ export interface ICstNodeVisitor<IN, OUT> extends ICstVisitor<IN, OUT> {
addColumnItem(children: AddColumnItemCstChildren, param?: IN): OUT;
alterColumnTypeIndex(children: AlterColumnTypeIndexCstChildren, param?: IN): OUT;
alterTableForceAction(children: AlterTableForceActionCstChildren, param?: IN): OUT;
alterTableCompactAction(children: AlterTableCompactActionCstChildren, param?: IN): OUT;
compactPartitionName(children: CompactPartitionNameCstChildren, param?: IN): OUT;
convertPartitionTarget(children: ConvertPartitionTargetCstChildren, param?: IN): OUT;
alterMaterializedViewStatement(children: AlterMaterializedViewStatementCstChildren, param?: IN): OUT;
suspendWalWith(children: SuspendWalWithCstChildren, param?: IN): OUT;
Expand Down
4 changes: 4 additions & 0 deletions src/parser/lexer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import {
Checkpoint,
Column,
Columns,
Compact,
Compile,
Complete,
CompressionCodec,
Expand Down Expand Up @@ -225,6 +226,7 @@ import {
Rename,
Repair,
Replace,
Residual,
Rest,
Respect,
Resume,
Expand Down Expand Up @@ -427,6 +429,7 @@ export {
Checkpoint,
Column,
Columns,
Compact,
Compile,
Complete,
CompressionCodec,
Expand Down Expand Up @@ -597,6 +600,7 @@ export {
Rename,
Repair,
Replace,
Residual,
Rest,
Respect,
Resume,
Expand Down
Loading
Loading