diff --git a/src/autocomplete/content-assist.ts b/src/autocomplete/content-assist.ts index 0845bb9..ed3d2cb 100644 --- a/src/autocomplete/content-assist.ts +++ b/src/autocomplete/content-assist.ts @@ -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 /** The tokens before the cursor */ @@ -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 { @@ -1520,7 +1524,7 @@ 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; @@ -1528,6 +1532,7 @@ function queryOutputScope( * 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( @@ -1538,8 +1543,27 @@ function objectColumnScope( | { tables: TableRef[] columns: Record + 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[] => { @@ -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++) { @@ -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 + } } } @@ -1914,6 +1944,7 @@ export function getContentAssist( return { nextTokenTypes, tablesInScope, + compactFilterTable, cteColumns, tokensBefore: tokens, isMidWord, diff --git a/src/autocomplete/provider.ts b/src/autocomplete/provider.ts index 6df2966..ac47f76 100644 --- a/src/autocomplete/provider.ts +++ b/src/autocomplete/provider.ts @@ -188,6 +188,7 @@ export function createAutocompleteProvider( const { nextTokenTypes, tablesInScope, + compactFilterTable, cteColumns, tokensBefore, isMidWord, @@ -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 diff --git a/src/formatter/context.ts b/src/formatter/context.ts index 301d3b8..4658fe6 100644 --- a/src/formatter/context.ts +++ b/src/formatter/context.ts @@ -17,6 +17,8 @@ const selectStarters: ReadonlySet = new Set([ "Declare", "Identifier", "QuotedIdentifier", + "Compact", + "Residual", "LParen", ]) diff --git a/src/formatter/phrases.ts b/src/formatter/phrases.ts index 6ee86c7..e959656 100644 --- a/src/formatter/phrases.ts +++ b/src/formatter/phrases.ts @@ -1,4 +1,4 @@ -import { StatementKind } from "./context" +import { isSignificant, StatementKind } from "./context" import { StreamToken } from "./lexer" export type PhraseRole = "clause" | "join" | "setOp" | "action" @@ -153,7 +153,11 @@ export const clausePhrases: Record = { ...clause(["Create", "Live", "View"]), ...createOptionPhrases, ], - alterTable: [...clause(["Alter", "Table"]), ...alterActionPhrases], + alterTable: [ + ...clause(["Alter", "Table"]), + ...alterActionPhrases, + ...action(["Compact"]), + ], alterMaterializedView: [ ...clause(["Alter", "Materialized", "View"]), ...alterActionPhrases, @@ -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, @@ -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 } } diff --git a/src/grammar/functions.ts b/src/grammar/functions.ts index 8467f8e..b847ff4 100644 --- a/src/grammar/functions.ts +++ b/src/grammar/functions.ts @@ -50,6 +50,7 @@ export const scalarFunctions: string[] = [ "ceil", "ceiling", "coalesce", + "cold_storage_release_pins", "concat", "cos", "cot", @@ -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", diff --git a/src/grammar/keywords.ts b/src/grammar/keywords.ts index 2a92610..f9d9463 100644 --- a/src/grammar/keywords.ts +++ b/src/grammar/keywords.ts @@ -45,6 +45,7 @@ export const keywords: string[] = [ "columns", "commit", "commitLag", + "compact", "compile", "compression_codec", "compression_level", @@ -186,6 +187,7 @@ export const keywords: string[] = [ "replace", "replica", "reset", + "residual", "resource", "respect", "resume", diff --git a/src/parser/ast.ts b/src/parser/ast.ts index 0b352c9..4f20530 100644 --- a/src/parser/ast.ts +++ b/src/parser/ast.ts @@ -593,6 +593,8 @@ export type AlterTableAction = | SquashPartitionsAction | ForceDropPartitionAction | ForceReindexParquetAction + | CompactPartitionAction + | CompactCancelAction | SetParamAction | SetTtlAction | SetTableFormatAction @@ -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[] diff --git a/src/parser/cst-types.d.ts b/src/parser/cst-types.d.ts index 64a2ace..724ddda 100644 --- a/src/parser/cst-types.d.ts +++ b/src/parser/cst-types.d.ts @@ -1682,6 +1682,7 @@ export type AlterTableActionCstChildren = { Squash?: IToken[]; Partitions?: IToken[]; alterTableForceAction?: AlterTableForceActionCstNode[]; + alterTableCompactAction?: AlterTableCompactActionCstNode[]; Param?: IToken[]; tableParam?: (TableParamCstNode)[]; Ttl?: IToken[]; @@ -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; @@ -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)[]; @@ -3557,6 +3587,8 @@ export interface ICstNodeVisitor extends ICstVisitor { 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; diff --git a/src/parser/lexer.ts b/src/parser/lexer.ts index 4c3125c..a29d82d 100644 --- a/src/parser/lexer.ts +++ b/src/parser/lexer.ts @@ -55,6 +55,7 @@ import { Checkpoint, Column, Columns, + Compact, Compile, Complete, CompressionCodec, @@ -225,6 +226,7 @@ import { Rename, Repair, Replace, + Residual, Rest, Respect, Resume, @@ -427,6 +429,7 @@ export { Checkpoint, Column, Columns, + Compact, Compile, Complete, CompressionCodec, @@ -597,6 +600,7 @@ export { Rename, Repair, Replace, + Residual, Rest, Respect, Resume, diff --git a/src/parser/parser.ts b/src/parser/parser.ts index 2a4d21a..911a85c 100644 --- a/src/parser/parser.ts +++ b/src/parser/parser.ts @@ -422,6 +422,9 @@ import { Policy, Local, Remote, + // ALTER TABLE ... COMPACT tokens (Enterprise cold storage) + Compact, + Residual, IdentifierKeyword, } from "./lexer" @@ -3602,6 +3605,8 @@ class QuestDBParser extends CstParser { }, // FORCE (DROP PARTITION LIST ... | REINDEX PARQUET ...) { ALT: () => this.SUBRULE(this.alterTableForceAction) }, + // COMPACT (CANCEL | [BASE | RESIDUAL] PARTITION ...) + { ALT: () => this.SUBRULE(this.alterTableCompactAction) }, // SET (PARAM ... | TTL ... | TYPE WAL ... | STORAGE POLICY ...) { ALT: () => { @@ -3810,6 +3815,54 @@ class QuestDBParser extends CstParser { ]) }) + // COMPACT [BASE | RESIDUAL] PARTITION { LIST '

' [, ...] | WHERE } + // COMPACT CANCEL + // Enterprise cold storage (EntSqlCompilerImpl.compileCompactPartition) + private alterTableCompactAction = this.RULE("alterTableCompactAction", () => { + this.CONSUME(Compact) + this.OR([ + { ALT: () => this.CONSUME(Cancel) }, + { + ALT: () => { + this.OPTION(() => { + this.OR1([ + { ALT: () => this.CONSUME(Base) }, + { ALT: () => this.CONSUME(Residual) }, + ]) + }) + this.CONSUME(Partition) + this.OR2([ + { + ALT: () => { + this.CONSUME(List) + this.SUBRULE(this.compactPartitionName) + this.MANY(() => { + this.CONSUME(Comma) + this.SUBRULE1(this.compactPartitionName) + }) + }, + }, + { + ALT: () => { + this.CONSUME(Where) + this.SUBRULE(this.expression) + }, + }, + ]) + }, + }, + ]) + }) + + private compactPartitionName = this.RULE("compactPartitionName", () => { + // The server unquotes the name before validation and accepts bare years. + this.OR([ + { ALT: () => this.CONSUME(StringLiteral) }, + { ALT: () => this.CONSUME(QuotedIdentifier) }, + { ALT: () => this.CONSUME(NumberLiteral) }, + ]) + }) + private convertPartitionTarget = this.RULE("convertPartitionTarget", () => { // Optional LIST before TO this.OPTION(() => { diff --git a/src/parser/toSql.ts b/src/parser/toSql.ts index ff2e6a6..3884ce8 100644 --- a/src/parser/toSql.ts +++ b/src/parser/toSql.ts @@ -1056,6 +1056,23 @@ function alterTableToSql(stmt: AST.AlterTableStatement): string { parts.push(action.partitions.map((p) => escapeString(p)).join(", ")) } break + case "compactPartition": + parts.push("COMPACT") + if (action.mode) { + parts.push(action.mode.toUpperCase()) + } + parts.push("PARTITION") + if (action.partitions && action.partitions.length > 0) { + parts.push("LIST") + parts.push(action.partitions.map((p) => escapeString(p)).join(", ")) + } else if (action.where) { + parts.push("WHERE") + parts.push(expressionToSql(action.where)) + } + break + case "compactCancel": + parts.push("COMPACT CANCEL") + break case "setParam": parts.push("SET PARAM") parts.push( diff --git a/src/parser/tokens.ts b/src/parser/tokens.ts index c9dbf57..e3e4d65 100644 --- a/src/parser/tokens.ts +++ b/src/parser/tokens.ts @@ -297,6 +297,10 @@ export const IDENTIFIER_KEYWORD_NAMES = new globalThis.Set([ "Suspend", "Resume", "Release", + // ALTER TABLE ... COMPACT [BASE | RESIDUAL] (Enterprise); not reserved on + // the server, which has tables named `residual` in its own tests. + "Compact", + "Residual", // COPY/export parameters "Parquet", "ParquetVersion", @@ -606,6 +610,7 @@ export const Cast = getToken("Cast") export const Checkpoint = getToken("Checkpoint") export const Column = getToken("Column") export const Columns = getToken("Columns") +export const Compact = getToken("Compact") export const Compile = getToken("Compile") export const Complete = getToken("Complete") export const CompressionCodec = getToken("CompressionCodec") @@ -743,6 +748,7 @@ export const Remove = getToken("Remove") export const Rename = getToken("Rename") export const Repair = getToken("Repair") export const Replace = getToken("Replace") +export const Residual = getToken("Residual") export const Rest = getToken("Rest") export const Respect = getToken("Respect") export const Resume = getToken("Resume") diff --git a/src/parser/visitor.ts b/src/parser/visitor.ts index 05878bd..fad75f5 100644 --- a/src/parser/visitor.ts +++ b/src/parser/visitor.ts @@ -20,6 +20,8 @@ import type { AlterServiceAccountStatementCstChildren, AlterStatementCstChildren, AlterTableActionCstChildren, + AlterTableCompactActionCstChildren, + CompactPartitionNameCstChildren, AlterTableForceActionCstChildren, AlterTableStatementCstChildren, AlterUserActionCstChildren, @@ -2897,11 +2899,48 @@ class QuestDBVisitor extends BaseVisitor { return result } + alterTableCompactAction( + ctx: AlterTableCompactActionCstChildren, + ): AST.CompactPartitionAction | AST.CompactCancelAction { + if (ctx.Cancel) { + return { actionType: "compactCancel" } + } + const result: AST.CompactPartitionAction = { + actionType: "compactPartition", + } + if (ctx.Base) { + result.mode = "base" + } else if (ctx.Residual) { + result.mode = "residual" + } + if (ctx.compactPartitionName) { + result.partitions = ctx.compactPartitionName.map( + (name) => this.visit(name) as string, + ) + } + if (ctx.Where && ctx.expression) { + result.where = this.visit(ctx.expression) as AST.Expression + } + return result + } + + compactPartitionName(ctx: CompactPartitionNameCstChildren): string { + if (ctx.StringLiteral) return unquoteSingle(ctx.StringLiteral[0].image) + if (ctx.QuotedIdentifier) { + return unquoteIdentifier(ctx.QuotedIdentifier[0].image) + } + return ctx.NumberLiteral![0].image + } + alterTableAction(ctx: AlterTableActionCstChildren): AST.AlterTableAction { // FORCE DROP PARTITION / FORCE REINDEX PARQUET if (ctx.alterTableForceAction) { return this.visit(ctx.alterTableForceAction) as AST.AlterTableAction } + // COMPACT CANCEL / COMPACT [BASE | RESIDUAL] PARTITION + if (ctx.alterTableCompactAction) { + return this.visit(ctx.alterTableCompactAction) as AST.AlterTableAction + } // SET STORAGE POLICY(...) — must come before generic SET branches below if (ctx.Set && ctx.storagePolicy) { return { diff --git a/tests/autocomplete.test.ts b/tests/autocomplete.test.ts index adaeced..dd5d631 100644 --- a/tests/autocomplete.test.ts +++ b/tests/autocomplete.test.ts @@ -179,9 +179,55 @@ describe("createAutocompleteProvider", () => { }, ]) }) + + it("walks through ALTER TABLE COMPACT", () => { + assertSuggestionsWalkthrough(provider, [ + { typed: "ALTER TABLE trades ", expects: ["COMPACT"] }, + { + typed: "ALTER TABLE trades COMPACT ", + expects: ["CANCEL", "BASE", "RESIDUAL", "PARTITION"], + }, + { + typed: "ALTER TABLE trades COMPACT BASE ", + expects: ["PARTITION"], + rejects: ["CANCEL", "RESIDUAL"], + }, + { + typed: "ALTER TABLE trades COMPACT RESIDUAL ", + expects: ["PARTITION"], + rejects: ["BASE", "CANCEL"], + }, + { + typed: "ALTER TABLE trades COMPACT PARTITION ", + expects: ["LIST", "WHERE"], + }, + { + typed: "ALTER TABLE trades COMPACT PARTITION WHERE ", + expects: ["timestamp"], + }, + ]) + }) }) describe("column suggestions", () => { + it.each([ + "ALTER TABLE trades COMPACT PARTITION WHERE ", + 'SELECT * FROM orders; ALTER TABLE "TRADES" COMPACT BASE PARTITION WHERE ', + "ALTER TABLE trades COMPACT RESIDUAL PARTITION WHERE (timestamp < now() AND ", + ])("suggests only the designated timestamp in %s", (sql) => { + const columns = getSuggestionsOfKind(provider, sql, SuggestionKind.Column) + expect(columns.map((column) => column.label)).toEqual(["timestamp"]) + }) + + it("omits columns in a COMPACT filter without a designated timestamp", () => { + const columns = getSuggestionsOfKind( + provider, + "ALTER TABLE orders COMPACT PARTITION WHERE ", + SuggestionKind.Column, + ) + expect(columns).toHaveLength(0) + }) + it("suggests columns after SELECT (with FROM clause)", () => { const columns = getSuggestionsOfKind( provider, diff --git a/tests/fixtures/docs-queries.json b/tests/fixtures/docs-queries.json index 256b104..51cf609 100644 --- a/tests/fixtures/docs-queries.json +++ b/tests/fixtures/docs-queries.json @@ -7999,5 +7999,47 @@ }, { "query": "ALTER TABLE trades FORCE REINDEX PARQUET COLUMN symbol PARTITION LIST '2026-03-01', '2026-03-02'" + }, + { + "query": "ALTER TABLE trades COMPACT PARTITION LIST '2026-02-10'" + }, + { + "query": "ALTER TABLE trades COMPACT RESIDUAL PARTITION LIST '2026-02-10', '2026-02-11'" + }, + { + "query": "ALTER TABLE trades COMPACT BASE PARTITION WHERE timestamp < '2026-03-01'" + }, + { + "query": "ALTER TABLE trades COMPACT CANCEL" + }, + { + "query": "ALTER TABLE trades COMPACT BASE PARTITION LIST '2026-02-10'" + }, + { + "query": "SELECT * FROM cold_storage_compactions() WHERE table_name = 'trades'" + }, + { + "query": "SELECT * FROM cold_storage_compactions()" + }, + { + "query": "SELECT * FROM cold_storage_compactions() WHERE status = 'failed'" + }, + { + "query": "SELECT table_name, partition_name, kind, origin, since, error\nFROM cold_storage_compactions()\nWHERE status = 'failed'" + }, + { + "query": "SELECT * FROM cold_storage_pin_owners()" + }, + { + "query": "SELECT * FROM cold_storage_pins('trades')" + }, + { + "query": "SELECT cold_storage_release_pins('')" + }, + { + "query": "SELECT timestamp, seq_txn, partition_path\nFROM table_cold_partitions('trades')\nWHERE state = 'active'" + }, + { + "query": "SELECT name, readOnly, isRemotelyServed\nFROM table_partitions('trades')\nWHERE isRemotelyServed AND readOnly = false" } ] diff --git a/tests/fixtures/server-queries.json b/tests/fixtures/server-queries.json index 68edf1f..dd2d856 100644 --- a/tests/fixtures/server-queries.json +++ b/tests/fixtures/server-queries.json @@ -2128,5 +2128,89 @@ "feature": "ent-users-groups", "toSql": "ALTER USER minion WITH PASSWORD 'null'", "skipAutocomplete": "password values are free text; NULL/TRUE/FALSE are deliberately not suggested there" + }, + { + "query": "ALTER TABLE raced COMPACT BASE PARTITION LIST '2020-01-01'", + "source": "questdb-enterprise:questdb-ent/src/test/java/com/questdb/cairo/delta/DeltaCompactionRequestTest.java:109", + "feature": "ent-cold-storage", + "toSql": "ALTER TABLE raced COMPACT BASE PARTITION LIST '2020-01-01'" + }, + { + "query": "ALTER TABLE partial COMPACT BASE PARTITION LIST '2020-01-01', '2020-01-02'", + "source": "questdb-enterprise:questdb-ent/src/test/java/com/questdb/cairo/delta/DeltaCompactionRequestTest.java:139", + "feature": "ent-cold-storage", + "toSql": "ALTER TABLE partial COMPACT BASE PARTITION LIST '2020-01-01', '2020-01-02'" + }, + { + "query": "ALTER TABLE partial COMPACT CANCEL", + "source": "questdb-enterprise:questdb-ent/src/test/java/com/questdb/cairo/delta/DeltaCompactionRequestTest.java:141", + "feature": "ent-cold-storage", + "toSql": "ALTER TABLE partial COMPACT CANCEL" + }, + { + "query": "ALTER TABLE stopped COMPACT PARTITION LIST '2020-01-01'", + "source": "questdb-enterprise:questdb-ent/src/test/java/com/questdb/cairo/delta/DeltaCompactionRequestTest.java:212", + "feature": "ent-cold-storage", + "toSql": "ALTER TABLE stopped COMPACT PARTITION LIST '2020-01-01'" + }, + { + "query": "ALTER TABLE demoted COMPACT RESIDUAL PARTITION LIST '2020-01-01'", + "source": "questdb-enterprise:questdb-ent/src/test/java/com/questdb/cairo/delta/DeltaCompactionRequestTest.java:237", + "feature": "ent-cold-storage", + "toSql": "ALTER TABLE demoted COMPACT RESIDUAL PARTITION LIST '2020-01-01'" + }, + { + "query": "ALTER TABLE residual COMPACT RESIDUAL PARTITION LIST '2020-01-01'", + "source": "questdb-enterprise:questdb-ent/src/test/java/com/questdb/cairo/delta/DeltaMaintenanceTest.java:77", + "feature": "ent-cold-storage", + "toSql": "ALTER TABLE residual COMPACT RESIDUAL PARTITION LIST '2020-01-01'" + }, + { + "query": "ALTER TABLE residual COMPACT RESIDUAL PARTITION WHERE ts < '2020-01-02'", + "source": "questdb-enterprise:questdb-ent/src/test/java/com/questdb/cairo/delta/DeltaMaintenanceTest.java:85", + "feature": "ent-cold-storage", + "toSql": "ALTER TABLE residual COMPACT RESIDUAL PARTITION WHERE ts < '2020-01-02'" + }, + { + "query": "ALTER TABLE selected COMPACT PARTITION LIST '2020-01-01', '2020-01-02'", + "source": "questdb-enterprise:questdb-ent/src/test/java/com/questdb/cairo/delta/BaseCompactionTest.java:693", + "feature": "ent-cold-storage", + "toSql": "ALTER TABLE selected COMPACT PARTITION LIST '2020-01-01', '2020-01-02'" + }, + { + "query": "SELECT table_name, partition_name, kind, origin, status, error FROM cold_storage_compactions()", + "source": "questdb-enterprise:questdb-ent/src/test/java/com/questdb/cairo/delta/DeltaCompactionRequestTest.java:77", + "feature": "ent-cold-storage", + "toSql": "SELECT table_name, partition_name, kind, origin, status, error FROM cold_storage_compactions()" + }, + { + "query": "SELECT count() FROM cold_storage_compactions() WHERE since > '2020-01-01'", + "source": "questdb-enterprise:questdb-ent/src/test/java/com/questdb/cairo/delta/DeltaCompactionRequestTest.java:426", + "feature": "ent-cold-storage", + "toSql": "SELECT count() FROM cold_storage_compactions() WHERE since > '2020-01-01'" + }, + { + "query": "SELECT owner_id, kind, origin, pinned_bases FROM cold_storage_pin_owners()", + "source": "questdb-enterprise:questdb-ent/src/test/java/com/questdb/cairo/cold/storage/ColdStoragePinAdminTest.java:85", + "feature": "ent-cold-storage", + "toSql": "SELECT owner_id, kind, origin, pinned_bases FROM cold_storage_pin_owners()" + }, + { + "query": "SELECT count() FROM cold_storage_pin_owners() WHERE registered_at > '2000-01-01'", + "source": "questdb-enterprise:questdb-ent/src/test/java/com/questdb/cairo/cold/storage/ColdStoragePinAdminTest.java:89", + "feature": "ent-cold-storage", + "toSql": "SELECT count() FROM cold_storage_pin_owners() WHERE registered_at > '2000-01-01'" + }, + { + "query": "SELECT * FROM cold_storage_pins()", + "source": "questdb-enterprise:questdb-ent/src/test/java/com/questdb/cairo/cold/storage/ColdStoragePinAdminTest.java:181", + "feature": "ent-cold-storage", + "toSql": "SELECT * FROM cold_storage_pins()" + }, + { + "query": "SELECT cold_storage_release_pins('an-owner')", + "source": "questdb-enterprise:questdb-ent/src/test/java/com/questdb/cairo/cold/storage/ColdStoragePinAdminTest.java:204", + "feature": "ent-cold-storage", + "toSql": "SELECT cold_storage_release_pins('an-owner')" } ] diff --git a/tests/formatter/fixtures.ts b/tests/formatter/fixtures.ts index 4c18b20..9d7183c 100644 --- a/tests/formatter/fixtures.ts +++ b/tests/formatter/fixtures.ts @@ -92,6 +92,34 @@ export const fixtures: Fixture[] = [ "FORCE DROP PARTITION LIST '2026-03-01'", ].join("\n"), }, + { + name: "ALTER TABLE COMPACT starts a line", + input: + "ALTER TABLE trades COMPACT BASE PARTITION WHERE timestamp < '2026-03-01'", + expected: [ + "ALTER TABLE trades", + "COMPACT BASE PARTITION WHERE timestamp < '2026-03-01'", + ].join("\n"), + }, + { + name: "ALTER TABLE COMPACT CANCEL starts a line", + input: "ALTER TABLE trades COMPACT CANCEL", + expected: ["ALTER TABLE trades", "COMPACT CANCEL"].join("\n"), + }, + { + name: "COMPACT stays inline as a table or column name", + input: "ALTER TABLE compact ADD COLUMN compact INT", + expected: ["ALTER TABLE compact", "ADD COLUMN compact INT"].join("\n"), + }, + { + name: "only the COMPACT action starts a line", + input: + "ALTER TABLE metrics.compact /* target */ COMPACT PARTITION WHERE compact < now()", + expected: [ + "ALTER TABLE metrics.compact /* target */", + "COMPACT PARTITION WHERE compact < now()", + ].join("\n"), + }, { name: "ALTER TABLE DROP STORAGE POLICY starts a line", input: "ALTER TABLE t DROP STORAGE POLICY", @@ -552,6 +580,16 @@ export const fixtures: Fixture[] = [ input: "trades WHERE symbol = 'BTC-USD'", expected: ["trades", "WHERE symbol = 'BTC-USD'"].join("\n"), }, + { + name: "implicit SELECT from a table named compact", + input: "compact WHERE ts > 0 ORDER BY ts", + expected: ["compact", "WHERE ts > 0", "ORDER BY ts"].join("\n"), + }, + { + name: "implicit SELECT from a table named residual", + input: "residual WHERE ts > 0 ORDER BY ts", + expected: ["residual", "WHERE ts > 0", "ORDER BY ts"].join("\n"), + }, { name: "DECLARE with one variable stays inline", input: "DECLARE OVERRIDABLE @x := 1 SELECT @x FROM t", diff --git a/tests/functions-list.test.ts b/tests/functions-list.test.ts index 401d7dc..3940dd3 100644 --- a/tests/functions-list.test.ts +++ b/tests/functions-list.test.ts @@ -33,6 +33,9 @@ describe("function lists", () => { "information_schema.character_sets", "information_schema.questdb_columns", "backup_status", + "cold_storage_compactions", + "cold_storage_pin_owners", + "cold_storage_pins", "table_cold_partitions", "tick_calendars", "files", @@ -55,10 +58,13 @@ describe("function lists", () => { "node_role", "reload_tick_calendars", "glob", + "cold_storage_release_pins", ]) { expect(scalarFunctions).toContain(f) } expect(scalarFunctions).not.toContain("files") + expect(scalarFunctions).not.toContain("cold_storage_pins") + expect(tableValuedFunctions).not.toContain("cold_storage_release_pins") }) it("autocomplete", () => { @@ -66,6 +72,19 @@ describe("function lists", () => { expect(functionsAt("SELECT from_b")).toContain("from_base64") expect(functionsAt("SELECT fil")).not.toContain("files") expect(functionsAt("SELECT * FROM storage_p")).toContain("storage_policies") + expect(functionsAt("SELECT * FROM cold_storage_")).toEqual( + expect.arrayContaining([ + "cold_storage_compactions", + "cold_storage_pin_owners", + "cold_storage_pins", + ]), + ) + expect(functionsAt("SELECT * FROM cold_storage_")).not.toContain( + "cold_storage_release_pins", + ) + expect(functionsAt("SELECT cold_storage_rel")).toContain( + "cold_storage_release_pins", + ) }) it.each([ diff --git a/tests/lexer.test.ts b/tests/lexer.test.ts index 888050d..f61e4f1 100644 --- a/tests/lexer.test.ts +++ b/tests/lexer.test.ts @@ -95,6 +95,20 @@ describe("QuestDB Lexer", () => { ]) }) + it("should tokenize cold storage compaction keywords", () => { + const result = tokenize("COMPACT BASE RESIDUAL PARTITION LIST CANCEL") + + expect(result.errors).toHaveLength(0) + expect(result.tokens.map((token) => token.tokenType.name)).toEqual([ + "Compact", + "Base", + "Residual", + "Partition", + "List", + "Cancel", + ]) + }) + it("should skip whitespace and comments", () => { const result = tokenize(` -- This is a comment diff --git a/tests/parser.test.ts b/tests/parser.test.ts index bb0b7ce..0137dff 100644 --- a/tests/parser.test.ts +++ b/tests/parser.test.ts @@ -8030,6 +8030,96 @@ orders PIVOT (sum(amount) FOR status IN ('open'))` }) }) + describe("COMPACT (Enterprise cold storage) — parse & AST", () => { + it("COMPACT PARTITION LIST in the default mode", () => { + const r = parseToAst( + "ALTER TABLE trades COMPACT PARTITION LIST '2026-02-10', '2026-02-11'", + ) + expect(r.errors).toHaveLength(0) + const s = r.ast[0] as AST.AlterTableStatement + expect(s.action).toEqual({ + actionType: "compactPartition", + partitions: ["2026-02-10", "2026-02-11"], + }) + }) + it("COMPACT BASE PARTITION LIST", () => { + const r = parseToAst( + "ALTER TABLE trades COMPACT BASE PARTITION LIST '2026-02-10'", + ) + expect(r.errors).toHaveLength(0) + const s = r.ast[0] as AST.AlterTableStatement + expect(s.action).toEqual({ + actionType: "compactPartition", + mode: "base", + partitions: ["2026-02-10"], + }) + }) + it.each([ + ["\"2026-02-10\", '2026-02-11'", ["2026-02-10", "2026-02-11"]], + ["2026, \"2025\", '2024', `2023`", ["2026", "2025", "2024", "2023"]], + ])("normalizes partition names in LIST %s", (list, partitions) => { + const r = parseToAst(`ALTER TABLE trades COMPACT PARTITION LIST ${list}`) + expect(r.errors).toHaveLength(0) + expect((r.ast[0] as AST.AlterTableStatement).action).toEqual({ + actionType: "compactPartition", + partitions, + }) + const roundTrip = parseToAst(toSql(r.ast[0])) + expect(roundTrip.errors).toHaveLength(0) + expect(roundTrip.ast).toEqual(r.ast) + }) + it("COMPACT RESIDUAL PARTITION WHERE", () => { + const r = parseToAst( + "ALTER TABLE trades COMPACT RESIDUAL PARTITION WHERE timestamp < '2026-03-01'", + ) + expect(r.errors).toHaveLength(0) + const action = (r.ast[0] as AST.AlterTableStatement) + .action as AST.CompactPartitionAction + expect(action.actionType).toBe("compactPartition") + expect(action.mode).toBe("residual") + expect(action.partitions).toBeUndefined() + expect(action.where).toMatchObject({ type: "binary", operator: "<" }) + }) + it("COMPACT CANCEL", () => { + const r = parseToAst("ALTER TABLE trades COMPACT CANCEL") + expect(r.errors).toHaveLength(0) + const s = r.ast[0] as AST.AlterTableStatement + expect(s.action).toEqual({ actionType: "compactCancel" }) + }) + it("keeps COMPACT, BASE and RESIDUAL usable as names", () => { + const r = parseToAst( + "ALTER TABLE residual COMPACT RESIDUAL PARTITION LIST '2020-01-01'", + ) + expect(r.errors).toHaveLength(0) + expect((r.ast[0] as AST.AlterTableStatement).action).toEqual({ + actionType: "compactPartition", + mode: "residual", + partitions: ["2020-01-01"], + }) + expect( + parseToAst("SELECT compact, base, residual FROM compact").errors, + ).toHaveLength(0) + }) + it("rejects COMPACT BASE without PARTITION", () => { + expect( + parseToAst("ALTER TABLE t COMPACT BASE").errors.length, + ).toBeGreaterThan(0) + }) + it("rejects COMPACT PARTITION without LIST or WHERE", () => { + expect( + parseToAst("ALTER TABLE t COMPACT PARTITION '2020-01-01'").errors + .length, + ).toBeGreaterThan(0) + }) + it("rejects BASE and RESIDUAL together", () => { + expect( + parseToAst( + "ALTER TABLE t COMPACT BASE RESIDUAL PARTITION LIST '2020-01-01'", + ).errors.length, + ).toBeGreaterThan(0) + }) + }) + describe("SHOW CREATE DATABASE — parse & AST", () => { it("bare", () => { const s = parseToAst("SHOW CREATE DATABASE").ast[0] as AST.ShowStatement @@ -8397,6 +8487,26 @@ orders PIVOT (sum(amount) FOR status IN ('open'))` } }) + describe("COMPACT (Enterprise cold storage) — round-trip", () => { + const queries = [ + "alter table t compact partition list '2024-01-01'", + "alter table t compact base partition list '2024-01-01', '2024-01-02'", + "alter table t compact residual partition list '2024-01-02'", + "alter table t compact base partition where ts < '2024-03-01'", + "alter table t compact partition where ts in '2024-02'", + "alter table t compact cancel", + ] + for (const query of queries) { + it(`round-trips: ${query.slice(0, 64)}`, () => { + const r = parseToAst(query) + expect(r.errors, JSON.stringify(r.errors)).toHaveLength(0) + const r2 = parseToAst(toSql(r.ast[0])) + expect(r2.errors).toHaveLength(0) + expect(r2.ast[0]).toEqual(r.ast[0]) + }) + } + }) + describe("SHOW CREATE DATABASE (QuestDB #7232) — round-trip", () => { const queries = [ "SHOW CREATE DATABASE",