feat(sql): add ClickHouse function completion
This commit is contained in:
1 parent
a83925d6ba
commit
9bc1c1b0fb
16 files changed
+2326
-53
No files matched your search
@@ -0,0 +1,115 @@
|
||||
import { CLICKHOUSE_AGGREGATE_FUNCTIONS } from "./aggregateFunctions";
|
||||
import type { ClickHouseFunctionDefinition, ClickHouseFunctionSignature } from "./functionTypes";
|
||||
|
||||
type CombinatorName = "Array" | "Map" | "ForEach" | "Distinct" | "OrDefault" | "OrNull" | "If" | "Resample" | "SimpleState" | "State" | "Merge" | "MergeState";
|
||||
|
||||
const COLLECTION_COMBINATORS = [undefined, "Array", "Map", "ForEach"] as const;
|
||||
const DEFAULT_COMBINATORS = [undefined, "OrDefault", "OrNull"] as const;
|
||||
const TERMINAL_COMBINATORS = [undefined, "SimpleState", "State", "Merge", "MergeState"] as const;
|
||||
|
||||
function buildCombinatorSequences(): CombinatorName[][] {
|
||||
const sequences: CombinatorName[][] = [];
|
||||
for (const collection of COLLECTION_COMBINATORS) {
|
||||
for (const distinct of [false, true]) {
|
||||
for (const fallback of DEFAULT_COMBINATORS) {
|
||||
for (const conditional of [false, true]) {
|
||||
for (const terminal of TERMINAL_COMBINATORS) {
|
||||
const sequence: CombinatorName[] = [];
|
||||
if (collection) sequence.push(collection);
|
||||
if (distinct) sequence.push("Distinct");
|
||||
if (fallback) sequence.push(fallback);
|
||||
if (conditional) sequence.push("If");
|
||||
if (terminal) sequence.push(terminal);
|
||||
if (sequence.length > 0) sequences.push(sequence);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const conditional of [false, true]) {
|
||||
for (const terminal of TERMINAL_COMBINATORS) {
|
||||
const sequence: CombinatorName[] = ["Resample"];
|
||||
if (conditional) sequence.push("If");
|
||||
if (terminal) sequence.push(terminal);
|
||||
sequences.push(sequence);
|
||||
}
|
||||
}
|
||||
return sequences;
|
||||
}
|
||||
|
||||
const COMBINATOR_SEQUENCES = buildCombinatorSequences();
|
||||
|
||||
function cloneSignature(signature: ClickHouseFunctionSignature): ClickHouseFunctionSignature {
|
||||
return { ...signature, parameterGroups: signature.parameterGroups.map((group) => [...group]) };
|
||||
}
|
||||
|
||||
function transformLastGroup(signature: ClickHouseFunctionSignature, transform: (group: string[]) => string[]): ClickHouseFunctionSignature {
|
||||
const transformed = cloneSignature(signature);
|
||||
const last = transformed.parameterGroups.length - 1;
|
||||
transformed.parameterGroups[last] = transform(transformed.parameterGroups[last]);
|
||||
return transformed;
|
||||
}
|
||||
|
||||
function applyCombinator(signature: ClickHouseFunctionSignature, combinator: CombinatorName): ClickHouseFunctionSignature {
|
||||
switch (combinator) {
|
||||
case "Array":
|
||||
case "ForEach":
|
||||
return transformLastGroup(signature, (group) =>
|
||||
group.map((parameter, index) => {
|
||||
if (parameter.startsWith("...")) return "...arrays";
|
||||
return index === 0 ? "array" : `array_${index + 1}`;
|
||||
}),
|
||||
);
|
||||
case "Map":
|
||||
return transformLastGroup(signature, () => ["map"]);
|
||||
case "If":
|
||||
return transformLastGroup(signature, (group) => [...group, "condition"]);
|
||||
case "Resample": {
|
||||
const transformed = transformLastGroup(signature, (group) => [...group, "resampling_key"]);
|
||||
transformed.parameterGroups.splice(Math.max(0, transformed.parameterGroups.length - 1), 0, ["start", "end", "step"]);
|
||||
return transformed;
|
||||
}
|
||||
case "Merge":
|
||||
case "MergeState":
|
||||
return transformLastGroup(signature, () => ["state"]);
|
||||
case "Distinct":
|
||||
case "OrDefault":
|
||||
case "OrNull":
|
||||
case "SimpleState":
|
||||
case "State":
|
||||
return cloneSignature(signature);
|
||||
}
|
||||
}
|
||||
|
||||
function generateDefinition(base: ClickHouseFunctionDefinition, sequence: readonly CombinatorName[]): ClickHouseFunctionDefinition {
|
||||
const signatures = base.signatures.map((signature) => sequence.reduce(applyCombinator, signature));
|
||||
return {
|
||||
...base,
|
||||
name: `${base.name}${sequence.join("")}`,
|
||||
signatures,
|
||||
aliases: undefined,
|
||||
combinators: false,
|
||||
generated: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function generateAggregateCombinatorCandidates(prefix: string, limit: number): ClickHouseFunctionDefinition[] {
|
||||
if (limit <= 0) return [];
|
||||
const normalized = prefix.toLowerCase();
|
||||
const results: ClickHouseFunctionDefinition[] = [];
|
||||
|
||||
for (const base of CLICKHOUSE_AGGREGATE_FUNCTIONS) {
|
||||
if (base.combinators === false) continue;
|
||||
const baseName = base.name.toLowerCase();
|
||||
if (normalized && !baseName.startsWith(normalized) && !normalized.startsWith(baseName)) continue;
|
||||
|
||||
for (const sequence of COMBINATOR_SEQUENCES) {
|
||||
const candidate = generateDefinition(base, sequence);
|
||||
if (!candidate.name.toLowerCase().startsWith(normalized)) continue;
|
||||
results.push(candidate);
|
||||
if (results.length === limit) return results;
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { ClickHouseFunctionDefinition, ClickHouseFunctionSignature } from "./functionTypes";
|
||||
import { CLICKHOUSE_WINDOW_FUNCTION_NAMES } from "./regularFunctions";
|
||||
|
||||
/**
|
||||
* Static aggregate-function snapshot verified against the official ClickHouse
|
||||
* Playground on 2026-07-31. Runtime completion never queries a server.
|
||||
*/
|
||||
const CLICKHOUSE_AGGREGATE_NAMES =
|
||||
"aggThrow analysisOfVariance any any_respect_nulls anyHeavy anyLast anyLast_respect_nulls approx_top_k approx_top_sum argAndMax argAndMin argMax argMin avg avgWeighted boundingRatio categoricalInformationValue contingency corr corrMatrix corrStable count covarPop covarPopMatrix covarPopStable covarSamp covarSampMatrix covarSampStable cramersV cramersVBiasCorrected cume_dist deltaSum deltaSumTimestamp denseRank distinctDynamicTypes distinctJSONPaths distinctJSONPathsAndTypes entropy estimateCompressionRatio exponentialMovingAverage exponentialTimeDecayedAvg exponentialTimeDecayedCount exponentialTimeDecayedMax exponentialTimeDecayedSum flameGraph groupArray groupArrayInsertAt groupArrayIntersect groupArrayLast groupArrayMovingAvg groupArrayMovingSum groupArraySample groupArraySorted groupBitAnd groupBitmap groupBitmapAnd groupBitmapOr groupBitmapXor groupBitOr groupBitXor groupConcat groupFormat groupNumericIndexedVector groupUniqArray histogram intervalLengthSum kolmogorovSmirnovTest kurtPop kurtSamp lag lagInFrame largestTriangleThreeBuckets lead leadInFrame mannWhitneyUTest max maxIntersections maxIntersectionsPosition maxMappedArrays meanZTest min minMappedArrays MVTEncode nonNegativeDerivative nothing nothingNull nothingUInt64 nth_value ntile percentRank quantile quantileBFloat16 quantileBFloat16Weighted quantileDD quantileDeterministic quantileExact quantileExactExclusive quantileExactHigh quantileExactInclusive quantileExactLow quantileExactWeighted quantileExactWeightedInterpolated quantileGK quantileInterpolatedWeighted quantilePrometheusHistogram quantiles quantilesBFloat16 quantilesBFloat16Weighted quantilesDD quantilesDeterministic quantilesExact quantilesExactExclusive quantilesExactHigh quantilesExactInclusive quantilesExactLow quantilesExactWeighted quantilesExactWeightedInterpolated quantilesGK quantilesInterpolatedWeighted quantilesPrometheusHistogram quantilesTDigest quantilesTDigestWeighted quantilesTiming quantilesTimingWeighted quantileTDigest quantileTDigestWeighted quantileTiming quantileTimingWeighted rank rankCorr retention row_number sequenceCount sequenceMatch sequenceMatchEvents sequenceNextNode simpleLinearRegression singleValueOrNull skewPop skewSamp sparkbar stddevPop stddevPopStable stddevSamp stddevSampStable stochasticLinearRegression stochasticLogisticRegression studentTTest studentTTestOneSample sum sumCount sumKahan sumMapFiltered sumMapFilteredWithOverflow sumMappedArrays sumMapWithOverflow sumWithOverflow theilsU timeSeriesChangesToGrid timeSeriesDeltaToGrid timeSeriesDerivToGrid timeSeriesGroupArray timeSeriesInstantDeltaToGrid timeSeriesInstantRateToGrid timeSeriesLastTwoSamples timeSeriesPredictLinearToGrid timeSeriesRateToGrid timeSeriesResampleToGridWithStaleness timeSeriesResetsToGrid topK topKWeighted uniq uniqCombined uniqCombined64 uniqExact uniqHLL12 uniqTheta uniqUpTo varPop varPopStable varSamp varSampStable welchTTest windowFunnel";
|
||||
|
||||
const CLICKHOUSE_AGGREGATE_ALIASES: Record<string, string[]> = {
|
||||
analysisOfVariance: ["anova"],
|
||||
any: ["any_value"],
|
||||
any_respect_nulls: ["any_value_respect_nulls", "anyRespectNulls", "anyValueRespectNulls", "first_value_respect_nulls", "firstValueRespectNulls"],
|
||||
anyLast_respect_nulls: ["anyLastRespectNulls", "last_value_respect_nulls", "lastValueRespectNulls"],
|
||||
approx_top_k: ["approx_top_count"],
|
||||
argMax: ["max_by"],
|
||||
argMin: ["min_by"],
|
||||
covarPop: ["COVAR_POP"],
|
||||
covarSamp: ["COVAR_SAMP"],
|
||||
groupArray: ["array_agg"],
|
||||
groupBitAnd: ["BIT_AND"],
|
||||
groupBitOr: ["BIT_OR"],
|
||||
groupBitXor: ["BIT_XOR"],
|
||||
groupConcat: ["group_concat", "string_agg"],
|
||||
largestTriangleThreeBuckets: ["lttb"],
|
||||
MVTEncode: ["ST_AsMVT"],
|
||||
quantile: ["median"],
|
||||
quantileBFloat16: ["medianBFloat16"],
|
||||
quantileBFloat16Weighted: ["medianBFloat16Weighted"],
|
||||
quantileDD: ["medianDD"],
|
||||
quantileDeterministic: ["medianDeterministic"],
|
||||
quantileExact: ["medianExact"],
|
||||
quantileExactHigh: ["medianExactHigh"],
|
||||
quantileExactLow: ["medianExactLow"],
|
||||
quantileExactWeighted: ["medianExactWeighted"],
|
||||
quantileExactWeightedInterpolated: ["medianExactWeightedInterpolated"],
|
||||
quantileGK: ["medianGK"],
|
||||
quantileInterpolatedWeighted: ["medianInterpolatedWeighted"],
|
||||
quantileTDigest: ["medianTDigest"],
|
||||
quantileTDigestWeighted: ["medianTDigestWeighted"],
|
||||
quantileTiming: ["medianTiming"],
|
||||
quantileTimingWeighted: ["medianTimingWeighted"],
|
||||
stddevPop: ["STD", "STDDEV_POP"],
|
||||
stddevSamp: ["STDDEV", "STDDEV_SAMP"],
|
||||
timeSeriesResampleToGridWithStaleness: ["timeSeriesLastToGrid"],
|
||||
varPop: ["VAR_POP"],
|
||||
varSamp: ["VAR_SAMP"],
|
||||
};
|
||||
|
||||
const sig = (...parameterGroups: string[][]): ClickHouseFunctionSignature => ({ parameterGroups });
|
||||
|
||||
const SIGNATURE_OVERRIDES: Record<string, ClickHouseFunctionSignature[]> = {
|
||||
count: [sig([]), sig(["expression"])],
|
||||
sum: [sig(["value"])],
|
||||
sumWithOverflow: [sig(["value"])],
|
||||
avg: [sig(["value"])],
|
||||
min: [sig(["value"])],
|
||||
max: [sig(["value"])],
|
||||
any: [sig(["value"])],
|
||||
anyLast: [sig(["value"])],
|
||||
anyHeavy: [sig(["value"])],
|
||||
argMin: [sig(["argument", "value"])],
|
||||
argMax: [sig(["argument", "value"])],
|
||||
groupArray: [sig(["expression"]), sig(["max_size"], ["expression"])],
|
||||
groupUniqArray: [sig(["expression"]), sig(["max_size"], ["expression"])],
|
||||
groupArrayArray: [sig(["array"])],
|
||||
groupArrayInsertAt: [sig(["default_value?", "size?"]), sig(["value", "position"])],
|
||||
groupConcat: [sig(["delimiter?", "limit?"]), sig(["expression"])],
|
||||
uniq: [sig(["expression", "...expressions"])],
|
||||
uniqExact: [sig(["expression", "...expressions"])],
|
||||
uniqCombined: [sig(["HLL_precision?"]), sig(["expression", "...expressions"])],
|
||||
uniqCombined64: [sig(["HLL_precision?"]), sig(["expression", "...expressions"])],
|
||||
uniqHLL12: [sig(["expression", "...expressions"])],
|
||||
uniqTheta: [sig(["expression", "...expressions"])],
|
||||
quantile: [sig(["level?"]), sig(["expression"])],
|
||||
quantiles: [sig(["level", "...levels"], ["expression"])],
|
||||
quantileExact: [sig(["level?"]), sig(["expression"])],
|
||||
quantilesExact: [sig(["level", "...levels"], ["expression"])],
|
||||
quantileTDigest: [sig(["level?"]), sig(["expression"])],
|
||||
quantilesTDigest: [sig(["level", "...levels"], ["expression"])],
|
||||
quantileTiming: [sig(["level?"]), sig(["expression"])],
|
||||
quantilesTiming: [sig(["level", "...levels"], ["expression"])],
|
||||
quantileBFloat16: [sig(["level?"]), sig(["expression"])],
|
||||
quantilesBFloat16: [sig(["level", "...levels"], ["expression"])],
|
||||
median: [sig(["level?"]), sig(["expression"])],
|
||||
topK: [sig(["N?", "load_factor?", "counts?"]), sig(["expression"])],
|
||||
topKWeighted: [sig(["N?", "load_factor?", "counts?"]), sig(["expression", "weight"])],
|
||||
histogram: [sig(["bins"]), sig(["values"])],
|
||||
sequenceMatch: [sig(["pattern"]), sig(["timestamp", "...conditions"])],
|
||||
sequenceCount: [sig(["pattern"]), sig(["timestamp", "...conditions"])],
|
||||
windowFunnel: [sig(["window", "mode?"]), sig(["timestamp", "...conditions"])],
|
||||
retention: [sig(["condition", "...conditions"])],
|
||||
};
|
||||
|
||||
const aggregate = (name: string): ClickHouseFunctionDefinition => {
|
||||
const signatures = Object.prototype.hasOwnProperty.call(SIGNATURE_OVERRIDES, name) ? SIGNATURE_OVERRIDES[name] : [sig(["expression", "...expressions?"])];
|
||||
const aliases = Object.prototype.hasOwnProperty.call(CLICKHOUSE_AGGREGATE_ALIASES, name) ? CLICKHOUSE_AGGREGATE_ALIASES[name] : undefined;
|
||||
return {
|
||||
name,
|
||||
kind: "aggregate",
|
||||
category: "aggregate",
|
||||
signatures,
|
||||
aliases,
|
||||
combinators: true,
|
||||
};
|
||||
};
|
||||
|
||||
export const CLICKHOUSE_AGGREGATE_FUNCTIONS: ClickHouseFunctionDefinition[] = CLICKHOUSE_AGGREGATE_NAMES.split(" ")
|
||||
.filter(Boolean)
|
||||
.filter((name) => !CLICKHOUSE_WINDOW_FUNCTION_NAMES.has(name))
|
||||
.map(aggregate);
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { ClickHouseFunctionDefinition, ClickHouseFunctionKind, ClickHouseFunctionRegistry } from "./functionTypes";
|
||||
import { generateAggregateCombinatorCandidates } from "./aggregateCombinators";
|
||||
import { CLICKHOUSE_AGGREGATE_FUNCTIONS } from "./aggregateFunctions";
|
||||
import { CLICKHOUSE_REGULAR_FUNCTIONS } from "./regularFunctions";
|
||||
import { CLICKHOUSE_TABLE_FUNCTIONS } from "./tableFunctions";
|
||||
|
||||
function definitionKeys(definition: ClickHouseFunctionDefinition): string[] {
|
||||
return [definition.name, ...(definition.aliases ?? [])].map((name) => name.toLowerCase());
|
||||
}
|
||||
|
||||
function validateDefinition(definition: ClickHouseFunctionDefinition): void {
|
||||
if (!definition.name.trim()) throw new Error("ClickHouse function name must not be empty");
|
||||
if (definition.signatures.length === 0) throw new Error(`ClickHouse function ${definition.name} must define a signature`);
|
||||
if (definition.signatures.some((signature) => signature.parameterGroups.length === 0)) {
|
||||
throw new Error(`ClickHouse function ${definition.name} must define a parameter group`);
|
||||
}
|
||||
const preferred = definition.preferredSignature ?? 0;
|
||||
if (preferred < 0 || preferred >= definition.signatures.length) {
|
||||
throw new Error(`ClickHouse function ${definition.name} has an invalid preferred signature`);
|
||||
}
|
||||
}
|
||||
|
||||
export function createClickHouseFunctionRegistry(definitions: readonly ClickHouseFunctionDefinition[]): ClickHouseFunctionRegistry {
|
||||
const byKey = new Map<string, ClickHouseFunctionDefinition>();
|
||||
for (const definition of definitions) {
|
||||
validateDefinition(definition);
|
||||
for (const key of definitionKeys(definition)) {
|
||||
if (byKey.has(key)) throw new Error(`Duplicate ClickHouse function or alias: ${key}`);
|
||||
byKey.set(key, definition);
|
||||
}
|
||||
}
|
||||
const ordered = [...definitions].sort((left, right) => left.name.localeCompare(right.name));
|
||||
return {
|
||||
get: (name) => byKey.get(name.toLowerCase()),
|
||||
search: (prefix, limit, kind?: ClickHouseFunctionKind) => {
|
||||
const normalized = prefix.toLowerCase();
|
||||
return ordered.filter((definition) => (!kind || definition.kind === kind) && definitionKeys(definition).some((key) => key.startsWith(normalized))).slice(0, limit);
|
||||
},
|
||||
all: () => ordered,
|
||||
};
|
||||
}
|
||||
|
||||
export const CLICKHOUSE_FUNCTION_REGISTRY = createClickHouseFunctionRegistry([...CLICKHOUSE_REGULAR_FUNCTIONS, ...CLICKHOUSE_AGGREGATE_FUNCTIONS, ...CLICKHOUSE_TABLE_FUNCTIONS]);
|
||||
|
||||
export function searchClickHouseFunctions(prefix: string, limit: number, kind?: ClickHouseFunctionKind): ClickHouseFunctionDefinition[] {
|
||||
const direct = CLICKHOUSE_FUNCTION_REGISTRY.search(prefix, limit, kind);
|
||||
if (direct.length >= limit || (kind && kind !== "aggregate")) return direct;
|
||||
const generated = generateAggregateCombinatorCandidates(prefix, limit - direct.length);
|
||||
return [...direct, ...generated].slice(0, limit);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
export type ClickHouseFunctionKind = "regular" | "aggregate" | "window" | "table";
|
||||
export type ClickHouseFunctionStatus = "stable" | "experimental" | "deprecated";
|
||||
|
||||
export type ClickHouseFunctionCategory = "aggregate" | "array" | "bitmap" | "comparison" | "conversion" | "date-time" | "dictionary" | "encoding" | "geo" | "hash" | "ip" | "json" | "map" | "math" | "nullable" | "random" | "string" | "table" | "tuple" | "url" | "window" | "other";
|
||||
|
||||
export interface ClickHouseFunctionSignature {
|
||||
parameterGroups: string[][];
|
||||
returnType?: string;
|
||||
}
|
||||
|
||||
export interface ClickHouseFunctionDefinition {
|
||||
name: string;
|
||||
kind: ClickHouseFunctionKind;
|
||||
category: ClickHouseFunctionCategory;
|
||||
signatures: ClickHouseFunctionSignature[];
|
||||
description?: string;
|
||||
preferredSignature?: number;
|
||||
status?: ClickHouseFunctionStatus;
|
||||
aliases?: string[];
|
||||
combinators?: boolean;
|
||||
generated?: boolean;
|
||||
}
|
||||
|
||||
export interface ClickHouseFunctionRegistry {
|
||||
get(name: string): ClickHouseFunctionDefinition | undefined;
|
||||
search(prefix: string, limit: number, kind?: ClickHouseFunctionKind): ClickHouseFunctionDefinition[];
|
||||
all(): readonly ClickHouseFunctionDefinition[];
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
import type { ClickHouseFunctionCategory, ClickHouseFunctionDefinition, ClickHouseFunctionSignature } from "./functionTypes";
|
||||
|
||||
/**
|
||||
* Static name snapshot from ClickHouse Playground system.functions on 2026-07-31.
|
||||
* Runtime completion never queries a ClickHouse server.
|
||||
*/
|
||||
const CLICKHOUSE_REGULAR_NAMES_BY_CATEGORY: Partial<Record<ClickHouseFunctionCategory, string>> = {
|
||||
array:
|
||||
"array arrayAll arrayAUCPR arrayAutocorrelation arrayAvg arrayBottomK arrayCompact arrayConcat arrayCount arrayCumSum arrayCumSumNonNegative arrayDifference arrayDistinct arrayDotProduct arrayElement arrayElementOrNull arrayEnumerate arrayEnumerateDense arrayEnumerateDenseRanked arrayEnumerateUniq arrayEnumerateUniqRanked arrayExcept arrayExists arrayFill arrayFilter arrayFirst arrayFirstIndex arrayFirstOrNull arrayFlatten arrayFold arrayIntersect arrayJaccardIndex arrayJoin arrayLast arrayLastIndex arrayLastOrNull arrayLevenshteinDistance arrayLevenshteinDistanceWeighted arrayMap arrayMax arrayMin arrayNormalizedGini arrayPartialReverseSort arrayPartialShuffle arrayPartialSort arrayPopBack arrayPopFront arrayProduct arrayPushBack arrayPushFront arrayRandomSample arrayReduce arrayReduceInRanges arrayRemove arrayResize arrayReverse arrayReverseFill arrayReverseSort arrayReverseSplit arrayROCAUC arrayRotateLeft arrayRotateRight arrayShiftLeft arrayShiftRight arrayShingles arrayShuffle arraySimilarity arraySlice arraySort arraySplit arrayStringConcat arraySum arraySymmetricDifference arrayTopK arrayTranspose arrayUnion arrayUniq arrayWithConstant arrayZip arrayZipUnaligned",
|
||||
bitmap:
|
||||
"bitmapAnd bitmapAndCardinality bitmapAndnot bitmapAndnotCardinality bitmapBuild bitmapCardinality bitmapContains bitmapHasAll bitmapHasAny bitmapMax bitmapMin bitmapOr bitmapOrCardinality bitmapSubsetInRange bitmapSubsetLimit bitmapToArray bitmapTransform bitmapXor bitmapXorCardinality bitmaskToArray bitmaskToList subBitmap",
|
||||
comparison:
|
||||
"and empty emptyArrayDate emptyArrayDateTime emptyArrayFloat32 emptyArrayFloat64 emptyArrayInt16 emptyArrayInt32 emptyArrayInt64 emptyArrayInt8 emptyArrayString emptyArrayToSingle emptyArrayUInt16 emptyArrayUInt32 emptyArrayUInt64 emptyArrayUInt8 equals globalIn globalInIgnoreSet globalNotIn globalNotInIgnoreSet globalNotNullIn globalNotNullInIgnoreSet greater greaterOrEquals greatest has hasAll hasAllTokens hasAny hasAnyTokens if in isDistinctFrom isNotDistinctFrom least less lessOrEquals multiIf not notEmpty notEquals notIn notInIgnoreSet or xor",
|
||||
conversion:
|
||||
"accurateCast accurateCastOrDefault accurateCastOrNull CAST defaultValueOfArgumentType defaultValueOfTypeName dynamicElement dynamicType materialize reinterpret reinterpretAsDate reinterpretAsDateTime reinterpretAsFixedString reinterpretAsFloat32 reinterpretAsFloat64 reinterpretAsInt128 reinterpretAsInt16 reinterpretAsInt256 reinterpretAsInt32 reinterpretAsInt64 reinterpretAsInt8 reinterpretAsString reinterpretAsUInt128 reinterpretAsUInt16 reinterpretAsUInt256 reinterpretAsUInt32 reinterpretAsUInt64 reinterpretAsUInt8 reinterpretAsUUID toBFloat16 toBFloat16OrNull toBFloat16OrZero toBool toColumnTypeName toDecimal128 toDecimal128OrDefault toDecimal128OrNull toDecimal128OrZero toDecimal256 toDecimal256OrDefault toDecimal256OrNull toDecimal256OrZero toDecimal32 toDecimal32OrDefault toDecimal32OrNull toDecimal32OrZero toDecimal64 toDecimal64OrDefault toDecimal64OrNull toDecimal64OrZero toDecimalString toFixedString toFloat32 toFloat32OrDefault toFloat32OrNull toFloat32OrZero toFloat64 toFloat64OrDefault toFloat64OrNull toFloat64OrZero toInt128 toInt128OrDefault toInt128OrNull toInt128OrZero toInt16 toInt16OrDefault toInt16OrNull toInt16OrZero toInt256 toInt256OrDefault toInt256OrNull toInt256OrZero toInt32 toInt32OrDefault toInt32OrNull toInt32OrZero toInt64 toInt64OrDefault toInt64OrNull toInt64OrZero toInt8 toInt8OrDefault toInt8OrNull toInt8OrZero toInterval toIntervalDay toIntervalHour toIntervalMicrosecond toIntervalMillisecond toIntervalMinute toIntervalMonth toIntervalNanosecond toIntervalQuarter toIntervalSecond toIntervalWeek toIntervalYear toIPv4 toIPv4OrDefault toIPv4OrNull toIPv4OrZero toIPv6 toIPv6OrDefault toIPv6OrNull toIPv6OrZero toLowCardinality toNullable toString toStringCutToZero toTypeName toUInt128 toUInt128OrDefault toUInt128OrNull toUInt128OrZero toUInt16 toUInt16OrDefault toUInt16OrNull toUInt16OrZero toUInt256 toUInt256OrDefault toUInt256OrNull toUInt256OrZero toUInt32 toUInt32OrDefault toUInt32OrNull toUInt32OrZero toUInt64 toUInt64OrDefault toUInt64OrNull toUInt64OrZero toUInt8 toUInt8OrDefault toUInt8OrNull toUInt8OrZero toUUID toUUIDOrDefault toUUIDOrNull toUUIDOrZero variantElement variantType",
|
||||
"date-time":
|
||||
"addDate addDays addHours addInterval addMicroseconds addMilliseconds addMinutes addMonths addNanoseconds addQuarters addSeconds addWeeks addYears age changeDay changeHour changeMinute changeMonth changeSecond changeYear DATE dateDiff dateName dateTime64ToSnowflakeID dateTimeToSnowflakeID dateTimeToUUIDv7 dateTrunc formatDateTime formatDateTimeInJodaSyntax fromDaysSinceYearZero fromDaysSinceYearZero32 fromModifiedJulianDay fromModifiedJulianDayOrNull fromUnixTimestamp fromUnixTimestamp64Micro fromUnixTimestamp64Milli fromUnixTimestamp64Nano fromUnixTimestamp64Second fromUnixTimestampInJodaSyntax fromUTCTimestamp hop hopEnd hopStart makeDate makeDate32 makeDateTime makeDateTime64 monthName now now64 nowInBlock nowInBlock64 parseDateTime parseDateTime32BestEffort parseDateTime32BestEffortOrNull parseDateTime32BestEffortOrZero parseDateTime64 parseDateTime64BestEffort parseDateTime64BestEffortOrNull parseDateTime64BestEffortOrZero parseDateTime64BestEffortUS parseDateTime64BestEffortUSOrNull parseDateTime64BestEffortUSOrZero parseDateTime64InJodaSyntax parseDateTime64InJodaSyntaxOrNull parseDateTime64InJodaSyntaxOrZero parseDateTime64OrNull parseDateTime64OrZero parseDateTimeBestEffort parseDateTimeBestEffortOrNull parseDateTimeBestEffortOrZero parseDateTimeBestEffortUS parseDateTimeBestEffortUSOrNull parseDateTimeBestEffortUSOrZero parseDateTimeInJodaSyntax parseDateTimeInJodaSyntaxOrNull parseDateTimeInJodaSyntaxOrZero parseDateTimeOrNull parseDateTimeOrZero parseTimeDelta snowflakeIDToDateTime snowflakeIDToDateTime64 subtractDays subtractHours subtractInterval subtractMicroseconds subtractMilliseconds subtractMinutes subtractMonths subtractNanoseconds subtractQuarters subtractSeconds subtractWeeks subtractYears timeDiff timeSeriesCopyTag timeSeriesCopyTags timeSeriesExtractTag timeSeriesFromGrid timeSeriesGroupToSamplingKey timeSeriesGroupToTags timeSeriesIdToGroup timeSeriesIdToTags timeSeriesJoinTags timeSeriesRange timeSeriesRemoveAllTagsExcept timeSeriesRemoveTag timeSeriesRemoveTags timeSeriesReplaceTag timeSeriesStoreTags timeSeriesTagsToGroup timeSeriesThrowDuplicateSeriesIf timeSlot timeSlots timestamp timezone timezoneOf timezoneOffset toDate toDate32 toDate32OrDefault toDate32OrNull toDate32OrZero toDateOrDefault toDateOrNull toDateOrZero toDateTime toDateTime32 toDateTime64 toDateTime64OrDefault toDateTime64OrNull toDateTime64OrZero toDateTimeOrDefault toDateTimeOrNull toDateTimeOrZero today toDayOfMonth toDayOfWeek toDayOfYear toDaysInMonth toDaysSinceYearZero toHour toISOWeek toISOYear toLastDayOfMonth toLastDayOfWeek toMicrosecond toMillisecond toMinute toModifiedJulianDay toModifiedJulianDayOrNull toMonday toMonth toMonthNumSinceEpoch toNanosecond toQuarter toRelativeDayNum toRelativeHourNum toRelativeMinuteNum toRelativeMonthNum toRelativeQuarterNum toRelativeSecondNum toRelativeWeekNum toRelativeYearNum toSecond toStartOfDay toStartOfFifteenMinutes toStartOfFiveMinutes toStartOfHour toStartOfInterval toStartOfISOYear toStartOfMicrosecond toStartOfMillisecond toStartOfMinute toStartOfMonth toStartOfNanosecond toStartOfQuarter toStartOfSecond toStartOfTenMinutes toStartOfWeek toStartOfYear toTime toTime64 toTime64OrNull toTime64OrZero toTimeOrNull toTimeOrZero toTimeWithFixedDate toTimezone toUnixTimestamp toUnixTimestamp64Micro toUnixTimestamp64Milli toUnixTimestamp64Nano toUnixTimestamp64Second toUTCTimestamp toWeek toYear toYearNumSinceEpoch toYearWeek toYYYYMM toYYYYMMDD toYYYYMMDDhhmmss tumble tumbleEnd tumbleStart ULIDStringToDateTime UTCTimestamp yesterday YYYYMMDDhhmmssToDateTime YYYYMMDDhhmmssToDateTime64 YYYYMMDDToDate YYYYMMDDToDate32",
|
||||
dictionary:
|
||||
"dictGet dictGetAll dictGetChildren dictGetDate dictGetDateOrDefault dictGetDateTime dictGetDateTimeOrDefault dictGetDescendants dictGetFloat32 dictGetFloat32OrDefault dictGetFloat64 dictGetFloat64OrDefault dictGetHierarchy dictGetInt16 dictGetInt16OrDefault dictGetInt32 dictGetInt32OrDefault dictGetInt64 dictGetInt64OrDefault dictGetInt8 dictGetInt8OrDefault dictGetIPv4 dictGetIPv4OrDefault dictGetIPv6 dictGetIPv6OrDefault dictGetKeys dictGetOrDefault dictGetOrNull dictGetString dictGetStringOrDefault dictGetUInt16 dictGetUInt16OrDefault dictGetUInt32 dictGetUInt32OrDefault dictGetUInt64 dictGetUInt64OrDefault dictGetUInt8 dictGetUInt8OrDefault dictGetUUID dictGetUUIDOrDefault dictHas dictIsIn",
|
||||
encoding:
|
||||
"aes_decrypt_mysql aes_encrypt_mysql base32Decode base32Encode base58Decode base58Encode base64Decode base64Encode base64URLDecode base64URLEncode bech32Decode bech32Encode bin decodeHTMLComponent decodeURLComponent decodeURLFormComponent decodeXMLComponent decrypt encodeURLComponent encodeURLFormComponent encodeXMLComponent encrypt hex idnaDecode idnaEncode punycodeDecode punycodeEncode sqidDecode sqidEncode tryBase32Decode tryBase58Decode tryBase64Decode tryBase64URLDecode unbin unhex",
|
||||
geo: "areaCartesian areaSpherical flipCoordinates geoDistance geohashDecode geohashEncode geohashesInBox geoToH3 geoToS2 greatCircleAngle greatCircleDistance h3CellAreaM2 h3CellAreaRads2 h3Distance h3EdgeAngle h3EdgeLengthKm h3EdgeLengthM h3ExactEdgeLengthKm h3ExactEdgeLengthM h3ExactEdgeLengthRads h3GetBaseCell h3GetDestinationIndexFromUnidirectionalEdge h3GetFaces h3GetIndexesFromUnidirectionalEdge h3GetOriginIndexFromUnidirectionalEdge h3GetPentagonIndexes h3GetRes0Indexes h3GetResolution h3GetUnidirectionalEdge h3GetUnidirectionalEdgeBoundary h3GetUnidirectionalEdgesFromHexagon h3HexAreaKm2 h3HexAreaM2 h3HexRing h3IndexesAreNeighbors h3IsPentagon h3IsResClassIII h3IsValid h3kRing h3Line h3NumHexagons h3PointDistKm h3PointDistM h3PointDistRads h3PolygonToCells h3PolygonToCellsWithContainment h3ToCenterChild h3ToChildren h3ToGeo h3ToGeoBoundary h3ToParent h3ToString h3UnidirectionalEdgeIsValid MVTBoundingBox MVTBoundingBoxMercator MVTEncodeGeom perimeterCartesian perimeterSpherical pointInEllipses pointInPolygon polygonAreaCartesian polygonAreaSpherical polygonConvexHullCartesian polygonPerimeterCartesian polygonPerimeterSpherical polygonsDistanceCartesian polygonsDistanceSpherical polygonsEqualsCartesian polygonsIntersectCartesian polygonsIntersectionCartesian polygonsIntersectionSpherical polygonsIntersectSpherical polygonsSymDifferenceCartesian polygonsSymDifferenceSpherical polygonsUnionCartesian polygonsUnionSpherical polygonsWithinCartesian polygonsWithinSpherical readWKB readWKBLineString readWKBMultiLineString readWKBMultiPolygon readWKBPoint readWKBPolygon readWKT readWKTLineString readWKTMultiLineString readWKTMultiPolygon readWKTPoint readWKTPolygon readWKTRing s2CapContains s2CapUnion s2CellsIntersect s2GetNeighbors s2RectAdd s2RectContains s2RectIntersection s2RectUnion s2ToGeo",
|
||||
hash: "BLAKE3 cityHash64 CRC32 CRC32IEEE CRC64 farmFingerprint64 farmHash64 gccMurmurHash halfMD5 hiveHash icebergHash intHash32 intHash64 isDynamicElementInSharedData javaHash javaHashUTF16LE jumpConsistentHash kafkaMurmurHash keccak256 kostikConsistentHash MD4 MD5 metroHash64 murmurHash2_32 murmurHash2_64 murmurHash3_128 murmurHash3_32 murmurHash3_64 ngramMinHash ngramMinHashArg ngramMinHashArgCaseInsensitive ngramMinHashArgCaseInsensitiveUTF8 ngramMinHashArgUTF8 ngramMinHashCaseInsensitive ngramMinHashCaseInsensitiveUTF8 ngramMinHashUTF8 ngramSimHash ngramSimHashCaseInsensitive ngramSimHashCaseInsensitiveUTF8 ngramSimHashUTF8 normalizedQueryHash normalizedQueryHashKeepNames RIPEMD160 SHA1 SHA224 SHA256 SHA384 SHA512 SHA512_256 shardCount shardNum sipHash128 sipHash128Keyed sipHash128Reference sipHash128ReferenceKeyed sipHash64 sipHash64Keyed sparseGramsHashes sparseGramsHashesUTF8 URLHash wordShingleMinHash wordShingleMinHashArg wordShingleMinHashArgCaseInsensitive wordShingleMinHashArgCaseInsensitiveUTF8 wordShingleMinHashArgUTF8 wordShingleMinHashCaseInsensitive wordShingleMinHashCaseInsensitiveUTF8 wordShingleMinHashUTF8 wordShingleSimHash wordShingleSimHashCaseInsensitive wordShingleSimHashCaseInsensitiveUTF8 wordShingleSimHashUTF8 wyHash64 xxh3 xxh3_128 xxHash32 xxHash64",
|
||||
ip: "cutIPv6 IPv4CIDRToRange IPv4NumToString IPv4NumToStringClassC IPv4StringToNum IPv4StringToNumOrDefault IPv4StringToNumOrNull IPv4ToIPv6 IPv6CIDRToRange IPv6NumToString IPv6StringToNum IPv6StringToNumOrDefault IPv6StringToNumOrNull isIPAddressInRange isIPv4String isIPv6String MACNumToString MACStringToNum MACStringToOUI",
|
||||
json: "isValidJSON JSON_EXISTS JSON_QUERY JSON_VALUE JSONAllPaths JSONAllPathsWithTypes JSONAllValues JSONArrayLength JSONDynamicPaths JSONDynamicPathsWithTypes JSONExtract JSONExtractArrayRaw JSONExtractArrayRawCaseInsensitive JSONExtractBool JSONExtractBoolCaseInsensitive JSONExtractCaseInsensitive JSONExtractFloat JSONExtractFloatCaseInsensitive JSONExtractInt JSONExtractIntCaseInsensitive JSONExtractKeys JSONExtractKeysAndValues JSONExtractKeysAndValuesCaseInsensitive JSONExtractKeysAndValuesRaw JSONExtractKeysAndValuesRawCaseInsensitive JSONExtractKeysCaseInsensitive JSONExtractRaw JSONExtractRawCaseInsensitive JSONExtractString JSONExtractStringCaseInsensitive JSONExtractUInt JSONExtractUIntCaseInsensitive JSONHas JSONKey JSONLength JSONMergePatch JSONSharedDataPaths JSONSharedDataPathsWithTypes JSONType prettyPrintJSON simpleJSONExtractBool simpleJSONExtractFloat simpleJSONExtractInt simpleJSONExtractRaw simpleJSONExtractString simpleJSONExtractUInt simpleJSONHas toJSONString",
|
||||
map: "map mapAdd mapAll mapApply mapConcat mapContainsKey mapContainsKeyLike mapContainsValue mapContainsValueLike mapExists mapExtractKeyLike mapExtractValueLike mapFilter mapFromArrays mapKeys mapPartialReverseSort mapPartialSort mapPopulateSeries mapReverseSort mapSort mapSubtract mapUpdate mapValues",
|
||||
math: "abs acos acosh asin asinh atan atan2 atanh avg2 cbrt ceil clamp cos cosh cosineDistance cosineDistanceTransposed degrees divide divideDecimal divideOrNull dotProduct dotProductTransposed e erf erfc exp exp10 exp2 factorial floor gcd hypot intDiv intDivOrNull intDivOrZero intExp10 intExp2 L1Distance L1Norm L1Normalize L2Distance L2DistanceTransposed L2Norm L2Normalize L2SquaredDistance L2SquaredNorm lcm LinfDistance LinfNorm LinfNormalize log log10 log1p log2 logTrace LpDistance LpNorm LpNormalize max2 min2 minus modulo moduloLegacy moduloOrNull moduloOrZero multiply multiplyDecimal pi plus positiveModulo positiveModuloOrNull pow proportionsZTest radians round roundAge roundBankers roundDown roundDuration roundToExp2 sigmoid sign sin sinh sqrt tan tanh trunc widthBucket",
|
||||
nullable: "assumeNotNull coalesce firstNonDefault ifNull isNotNull isNull isNullable isZeroOrNull nullIf",
|
||||
random:
|
||||
"generateSnowflakeID generateULID generateUUIDv4 generateUUIDv7 rand rand64 randBernoulli randBinomial randCanonical randChiSquared randConstant randExponential randFisherF randLogNormal randNegativeBinomial randNormal randomFixedString randomHadamardTransform randomPrintableASCII randomString randomStringUTF8 randPoisson randStudentT randUniform",
|
||||
string:
|
||||
"alphaTokens appendTrailingCharIfAbsent ascii caseFoldUTF8 char compareSubstrings concat concatAssumeInjective concatWithSeparator concatWithSeparatorAssumeInjective countEqual countMatches countMatchesCaseInsensitive countSubstrings countSubstringsCaseInsensitive countSubstringsCaseInsensitiveUTF8 damerauLevenshteinDistance editDistance editDistanceUTF8 endsWith endsWithCaseInsensitive endsWithCaseInsensitiveUTF8 endsWithUTF8 extract extractAll extractAllGroupsHorizontal extractAllGroupsVertical extractGroups extractKeyValuePairs extractKeyValuePairsWithEscaping extractTextFromHTML firstLine formatQuery formatQueryOrNull formatQuerySingleLine formatQuerySingleLineOrNull formatReadableDecimalSize formatReadableQuantity formatReadableSize formatReadableTimeDelta formatRow formatRowNoNewline hasPhrase hasSubsequence hasSubsequenceCaseInsensitive hasSubsequenceCaseInsensitiveUTF8 hasSubsequenceUTF8 hasSubstr hasToken hasTokenCaseInsensitive hasTokenCaseInsensitiveOrNull hasTokenOrNull ilike initcap initcapUTF8 jaroSimilarity jaroWinklerSimilarity left leftPad leftPadUTF8 leftUTF8 length lengthUTF8 like locate lower lowerUTF8 match multiFuzzyMatchAllIndices multiFuzzyMatchAny multiFuzzyMatchAnyIndex multiMatchAllIndices multiMatchAny multiMatchAnyIndex multiSearchAllPositions multiSearchAllPositionsCaseInsensitive multiSearchAllPositionsCaseInsensitiveUTF8 multiSearchAllPositionsUTF8 multiSearchAny multiSearchAnyCaseInsensitive multiSearchAnyCaseInsensitiveUTF8 multiSearchAnyUTF8 multiSearchFirstIndex multiSearchFirstIndexCaseInsensitive multiSearchFirstIndexCaseInsensitiveUTF8 multiSearchFirstIndexUTF8 multiSearchFirstPosition multiSearchFirstPositionCaseInsensitive multiSearchFirstPositionCaseInsensitiveUTF8 multiSearchFirstPositionUTF8 ngramDistance ngramDistanceCaseInsensitive ngramDistanceCaseInsensitiveUTF8 ngramDistanceUTF8 ngrams ngramSearch ngramSearchCaseInsensitive ngramSearchCaseInsensitiveUTF8 ngramSearchUTF8 normalizeUTF8NFC normalizeUTF8NFD normalizeUTF8NFKC normalizeUTF8NFKCCasefold normalizeUTF8NFKD overlay overlayUTF8 position positionCaseInsensitive positionCaseInsensitiveUTF8 positionUTF8 printf repeat replaceAll replaceOne replaceRegexpAll replaceRegexpOne reverse reverseBySeparator reverseUTF8 right rightPad rightPadUTF8 rightUTF8 soundex space sparseGrams sparseGramsUTF8 splitByChar splitByNonAlpha splitByRegexp splitByString splitByWhitespace startsWith startsWithCaseInsensitive startsWithCaseInsensitiveUTF8 startsWithUTF8 stem stringBytesEntropy stringBytesUniq stringJaccardIndex stringJaccardIndexUTF8 stringToH3 substring substringIndex substringIndexUTF8 substringUTF8 tokens tokensForLikePattern translate translateUTF8 trimBoth trimLeft trimRight upper upperUTF8 visibleWidth",
|
||||
tuple:
|
||||
"flattenTuple tuple tupleConcat tupleDivide tupleDivideByNumber tupleElement tupleHammingDistance tupleIntDiv tupleIntDivByNumber tupleIntDivOrZero tupleIntDivOrZeroByNumber tupleMinus tupleModulo tupleModuloByNumber tupleMultiply tupleMultiplyByNumber tupleNames tupleNegate tuplePlus tuplePositiveModuloByNumber tupleToNameValuePairs",
|
||||
url: "basename cutFragment cutQueryString cutQueryStringAndFragment cutToFirstSignificantSubdomain cutToFirstSignificantSubdomainCustom cutToFirstSignificantSubdomainCustomRFC cutToFirstSignificantSubdomainCustomWithWWW cutToFirstSignificantSubdomainCustomWithWWWRFC cutToFirstSignificantSubdomainRFC cutToFirstSignificantSubdomainWithWWW cutToFirstSignificantSubdomainWithWWWRFC cutURLParameter cutWWW domain domainRFC domainWithoutWWW domainWithoutWWWRFC extractURLParameter extractURLParameterNames extractURLParameters firstSignificantSubdomain firstSignificantSubdomainCustom firstSignificantSubdomainCustomRFC firstSignificantSubdomainRFC FQDN fragment netloc path pathFull port portRFC protocol topLevelDomain topLevelDomainRFC URLHierarchy URLPathHierarchy",
|
||||
window: "cume_dist dense_rank first_value lag lagInFrame last_value lead leadInFrame nth_value ntile percent_rank rank row_number",
|
||||
other:
|
||||
"addressToLine addressToLineWithInlines addressToSymbol addTupleOfIntervals aiClassify aiEmbed aiExtract aiGenerate aiTranslate authenticatedUser bar bitAnd bitCount bitHammingDistance bitNot bitOr bitPositionsToArray bitRotateLeft bitRotateRight bitShiftLeft bitShiftRight bitSlice bitTest bitTestAll bitTestAny bitXor blockNumber blockSerializedSize blockSize buildId byteHammingDistance byteSize byteSwap caseWithExpression catboostEvaluate colorOKLABToSRGB colorOKLCHToSRGB colorSRGBToOKLAB colorSRGBToOKLCH connectionId conv convertCharset countDigits currentDatabase currentProfiles currentQueryID currentRoles currentSchemas currentUser defaultProfiles defaultRoles demangle dequantizeInt8ToBFloat16 detectCharset detectLanguage detectLanguageMixed detectLanguageUnknown detectTonality displayName dumpColumnStructure enabledProfiles enabledRoles errorCodeToName evalMLMethod filesystemAvailable filesystemCapacity filesystemUnreserved finalizeAggregation financialInternalRateOfReturn financialInternalRateOfReturnExtended financialNetPresentValue financialNetPresentValueExtended fuzzBits generateRandomStructure generateSerialID getClientHTTPHeader getMacro getMaxTableNameLengthForDatabase getMergeTreeSetting getOSKernelVersion getServerPort getServerSetting getSetting getSettingOrDefault getSizeOfEnumType getSubcolumn getTypeSerializationStreams globalNullIn globalNullInIgnoreSet globalVariable hasColumnInTable hasThreadFuzzer highlight highlightQuery hilbertDecode hilbertEncode HMAC hostName icebergBucket icebergTruncate identity ifNotFinite ignore indexHint indexOf indexOfAssumeSorted inIgnoreSet initializeAggregation initialQueryID initialQueryStartTime isConstant isDecimalOverflow isFinite isInfinite isMergeTreePartCoveredBy isNaN isPrime isProbablePrime isValidASCII isValidUTF8 joinGet joinGetOrNull lemmatize lgamma localtime lowCardinalityIndices lowCardinalityKeys mergeTreePartInfo midpoint minSampleSizeContinuous minSampleSizeConversion mortonDecode mortonEncode naiveBayesClassifier naturalSortKey negate neighbor nested normalizeQuery normalizeQueryKeepNames notILike notLike notNullIn notNullInIgnoreSet nullIn nullInIgnoreSet numericIndexedVectorAllValueSum numericIndexedVectorBuild numericIndexedVectorCardinality numericIndexedVectorGetValue numericIndexedVectorPointwiseAdd numericIndexedVectorPointwiseDivide numericIndexedVectorPointwiseEqual numericIndexedVectorPointwiseGreater numericIndexedVectorPointwiseGreaterEqual numericIndexedVectorPointwiseLess numericIndexedVectorPointwiseLessEqual numericIndexedVectorPointwiseMultiply numericIndexedVectorPointwiseNotEqual numericIndexedVectorPointwiseSubtract numericIndexedVectorShortDebugString numericIndexedVectorToMap obfuscateQuery obfuscateQueryWithSeed parseReadableSize parseReadableSizeOrNull parseReadableSizeOrZero partitionId quantizeBFloat16ToInt8 queryID queryString queryStringAndFragment range regexpExtract regexpPosition regexpQuoteMeta regionHierarchy regionIn regionToArea regionToCity regionToContinent regionToCountry regionToDistrict regionToName regionToPopulation regionToTopContinent removeDiacriticsUTF8 replicate revision rowNumberInAllBlocks rowNumberInBlock runningAccumulate runningConcurrency runningDifference runningDifferenceStartingWithFirstValue seriesDecomposeSTL seriesOutliersDetectTukey seriesPeriodDetectFFT serverTimezone serverUUID showCertificate sleep sleepEachRow structureToCapnProtoSchema structureToProtobufSchema subDate subtractTupleOfIntervals svg synonyms tcpPort tgamma throwIf tid tokenizeQuery toValidUTF8 transactionID transactionLatestSnapshot transactionOldestSnapshot transform tryDecrypt tryIdnaEncode tryPunycodeDecode uniqThetaIntersect uniqThetaNot uniqThetaUnion uptime UUIDNumToString UUIDStringToNum UUIDToNum UUIDv7ToDateTime validateNestedArraySizes version windowID wkb wkt zookeeperSessionUptime",
|
||||
};
|
||||
|
||||
const CLICKHOUSE_ALIASES_BY_CANONICAL: Record<string, string[]> = {
|
||||
dense_rank: ["denseRank"],
|
||||
alphaTokens: ["splitByAlpha"],
|
||||
arrayAUCPR: ["arrayPRAUC"],
|
||||
arrayFlatten: ["flatten"],
|
||||
arrayJoin: ["unnest"],
|
||||
arrayRemove: ["array_remove"],
|
||||
arrayROCAUC: ["arrayAUC"],
|
||||
arrayStringConcat: ["array_to_string"],
|
||||
authenticatedUser: ["authUser"],
|
||||
base64Decode: ["FROM_BASE64"],
|
||||
base64Encode: ["TO_BASE64"],
|
||||
byteHammingDistance: ["mismatches"],
|
||||
caseWithExpression: ["caseWithExpr"],
|
||||
ceil: ["ceiling"],
|
||||
concatWithSeparator: ["concat_ws"],
|
||||
connectionId: ["connection_id"],
|
||||
cosineDistance: ["distanceCosine"],
|
||||
cosineDistanceTransposed: ["distanceCosineTransposed"],
|
||||
currentDatabase: ["DATABASE", "SCHEMA", "current_database"],
|
||||
currentQueryID: ["current_query_id"],
|
||||
currentSchemas: ["current_schemas"],
|
||||
currentUser: ["current_user", "session_user", "user"],
|
||||
dateDiff: ["DATE_DIFF", "TIMESTAMP_DIFF", "timestampDiff"],
|
||||
dateTrunc: ["DATE_TRUNC"],
|
||||
dotProduct: ["scalarProduct"],
|
||||
dotProductTransposed: ["scalarProductTransposed"],
|
||||
editDistance: ["levenshteinDistance"],
|
||||
editDistanceUTF8: ["levenshteinDistanceUTF8"],
|
||||
extractAllGroupsVertical: ["extractAllGroups"],
|
||||
extractKeyValuePairs: ["mapFromString", "str_to_map"],
|
||||
formatDateTime: ["DATE_FORMAT"],
|
||||
formatReadableSize: ["FORMAT_BYTES"],
|
||||
FQDN: ["fullHostName"],
|
||||
fromDaysSinceYearZero: ["FROM_DAYS"],
|
||||
fromUnixTimestamp: ["FROM_UNIXTIME"],
|
||||
fromUTCTimestamp: ["from_utc_timestamp"],
|
||||
hasAllTokens: ["hasAllToken"],
|
||||
hasAnyTokens: ["hasAnyToken"],
|
||||
hasPhrase: ["matchPhrase"],
|
||||
initialQueryID: ["initial_query_id"],
|
||||
initialQueryStartTime: ["initial_query_start_time"],
|
||||
IPv4NumToString: ["INET_NTOA"],
|
||||
IPv4StringToNum: ["INET_ATON"],
|
||||
IPv6NumToString: ["INET6_NTOA"],
|
||||
IPv6StringToNum: ["INET6_ATON"],
|
||||
isValidASCII: ["isASCII"],
|
||||
JSONArrayLength: ["JSON_ARRAY_LENGTH"],
|
||||
kostikConsistentHash: ["yandexConsistentHash"],
|
||||
L1Distance: ["distanceL1"],
|
||||
L1Norm: ["normL1"],
|
||||
L1Normalize: ["normalizeL1"],
|
||||
L2Distance: ["distanceL2"],
|
||||
L2DistanceTransposed: ["distanceL2Transposed"],
|
||||
L2Norm: ["normL2"],
|
||||
L2Normalize: ["normalizeL2"],
|
||||
L2SquaredDistance: ["distanceL2Squared"],
|
||||
L2SquaredNorm: ["normL2Squared"],
|
||||
leftPad: ["lpad"],
|
||||
length: ["CARDINALITY", "OCTET_LENGTH"],
|
||||
lengthUTF8: ["CHARACTER_LENGTH", "CHAR_LENGTH"],
|
||||
LinfDistance: ["distanceLinf"],
|
||||
LinfNorm: ["normLinf"],
|
||||
LinfNormalize: ["normalizeLinf"],
|
||||
log: ["ln"],
|
||||
lower: ["lcase"],
|
||||
LpDistance: ["distanceLp"],
|
||||
LpNorm: ["normLp"],
|
||||
LpNormalize: ["normalizeLp"],
|
||||
mapContainsKey: ["mapContains"],
|
||||
mapFromArrays: ["MAP_FROM_ARRAYS"],
|
||||
match: ["REGEXP_MATCHES"],
|
||||
minSampleSizeContinuous: ["minSampleSizeContinous"],
|
||||
modulo: ["mod"],
|
||||
moduloOrNull: ["modOrNull"],
|
||||
multiIf: ["caseWithoutExpr", "caseWithoutExpression"],
|
||||
MVTEncodeGeom: ["ST_AsMVTGeom"],
|
||||
naturalSortKey: ["NATURAL_SORT_KEY"],
|
||||
now: ["current_timestamp", "localtimestamp"],
|
||||
parseDateTime: ["TO_UNIXTIME"],
|
||||
parseDateTimeOrNull: ["str_to_date"],
|
||||
percent_rank: ["percentRank"],
|
||||
positionCaseInsensitive: ["instr"],
|
||||
positiveModulo: ["pmod", "positive_modulo"],
|
||||
positiveModuloOrNull: ["pmodOrNull", "positive_modulo_or_null"],
|
||||
pow: ["power"],
|
||||
queryID: ["query_id"],
|
||||
rand: ["rand32"],
|
||||
readWKBLineString: ["ST_LineFromWKB"],
|
||||
readWKBMultiLineString: ["ST_MLineFromWKB"],
|
||||
readWKBMultiPolygon: ["ST_MPolyFromWKB"],
|
||||
readWKBPoint: ["ST_PointFromWKB"],
|
||||
readWKBPolygon: ["ST_PolyFromWKB"],
|
||||
regexpExtract: ["REGEXP_EXTRACT", "REGEXP_SUBSTR"],
|
||||
regexpPosition: ["regexpInstr", "regexp_instr"],
|
||||
removeDiacriticsUTF8: ["removeAccentsUTF8"],
|
||||
replaceAll: ["replace"],
|
||||
replaceRegexpAll: ["REGEXP_REPLACE"],
|
||||
rightPad: ["rpad"],
|
||||
simpleJSONExtractBool: ["visitParamExtractBool"],
|
||||
simpleJSONExtractFloat: ["visitParamExtractFloat"],
|
||||
simpleJSONExtractInt: ["visitParamExtractInt"],
|
||||
simpleJSONExtractRaw: ["visitParamExtractRaw"],
|
||||
simpleJSONExtractString: ["visitParamExtractString"],
|
||||
simpleJSONExtractUInt: ["visitParamExtractUInt"],
|
||||
simpleJSONHas: ["visitParamHas"],
|
||||
sqidEncode: ["sqid"],
|
||||
substring: ["byteSlice", "mid", "substr"],
|
||||
substringIndex: ["SUBSTRING_INDEX"],
|
||||
timeSeriesGroupToTags: ["timeSeriesTagsGroupToTags"],
|
||||
timeSeriesIdToGroup: ["timeSeriesIdToTagsGroup"],
|
||||
today: ["curdate", "current_date"],
|
||||
toDayOfMonth: ["DAY", "DAYOFMONTH"],
|
||||
toDayOfWeek: ["DAYOFWEEK"],
|
||||
toDayOfYear: ["DAYOFYEAR"],
|
||||
toDaysSinceYearZero: ["TO_DAYS"],
|
||||
toHour: ["HOUR"],
|
||||
toLastDayOfMonth: ["LAST_DAY"],
|
||||
toMicrosecond: ["MICROSECOND"],
|
||||
toMillisecond: ["MILLISECOND"],
|
||||
toMinute: ["MINUTE"],
|
||||
toMonth: ["MONTH"],
|
||||
toNanosecond: ["NANOSECOND"],
|
||||
toQuarter: ["QUARTER"],
|
||||
toSecond: ["SECOND"],
|
||||
toStartOfFiveMinutes: ["toStartOfFiveMinute"],
|
||||
toStartOfInterval: ["date_bin", "time_bucket"],
|
||||
toUTCTimestamp: ["to_utc_timestamp"],
|
||||
toWeek: ["week"],
|
||||
toYear: ["YEAR"],
|
||||
toYearWeek: ["yearweek"],
|
||||
trimBoth: ["trim"],
|
||||
trimLeft: ["ltrim"],
|
||||
trimRight: ["rtrim"],
|
||||
trunc: ["truncate"],
|
||||
tupleMinus: ["vectorDifference"],
|
||||
tuplePlus: ["vectorSum"],
|
||||
upper: ["ucase"],
|
||||
UTCTimestamp: ["UTC_timestamp"],
|
||||
widthBucket: ["width_bucket"],
|
||||
};
|
||||
|
||||
const sig = (...parameterGroups: string[][]): ClickHouseFunctionSignature => ({ parameterGroups });
|
||||
|
||||
const SIGNATURE_OVERRIDES: Record<string, ClickHouseFunctionSignature[]> = {
|
||||
arrayElement: [sig(["array", "index"])],
|
||||
arrayFilter: [sig(["lambda", "array", "...arrays"])],
|
||||
arrayJoin: [sig(["array"])],
|
||||
arrayMap: [sig(["lambda", "array", "...arrays"])],
|
||||
cityHash64: [sig(["argument", "...arguments"])],
|
||||
concat: [sig(["value", "...values"])],
|
||||
cume_dist: [sig([])],
|
||||
dense_rank: [sig([])],
|
||||
dictGet: [sig(["dictionary", "attribute", "key"])],
|
||||
formatDateTime: [sig(["value", "format"]), sig(["value", "format", "time_zone"])],
|
||||
geoDistance: [sig(["longitude1", "latitude1", "longitude2", "latitude2"])],
|
||||
JSONExtract: [sig(["json", "path", "...paths", "return_type"])],
|
||||
JSONExtractString: [sig(["json", "path", "...paths"])],
|
||||
lag: [sig(["value"]), sig(["value", "offset"]), sig(["value", "offset", "default"])],
|
||||
lagInFrame: [sig(["value"]), sig(["value", "offset"]), sig(["value", "offset", "default"])],
|
||||
lead: [sig(["value"]), sig(["value", "offset"]), sig(["value", "offset", "default"])],
|
||||
leadInFrame: [sig(["value"]), sig(["value", "offset"]), sig(["value", "offset", "default"])],
|
||||
length: [sig(["value"])],
|
||||
lower: [sig(["string"])],
|
||||
map: [sig(["key", "value", "...pairs"])],
|
||||
now: [sig([]), sig(["time_zone"])],
|
||||
ntile: [sig(["buckets"])],
|
||||
percent_rank: [sig([])],
|
||||
rank: [sig([])],
|
||||
row_number: [sig([])],
|
||||
substring: [sig(["string", "offset"]), sig(["string", "offset", "length"])],
|
||||
toDate: [sig(["value"]), sig(["value", "time_zone"])],
|
||||
toDateTime: [sig(["value"]), sig(["value", "time_zone"])],
|
||||
toStartOfDay: [sig(["value"]), sig(["value", "time_zone"])],
|
||||
toStartOfInterval: [sig(["value", "INTERVAL x unit"]), sig(["value", "INTERVAL x unit", "time_zone"]), sig(["value", "INTERVAL x unit", "origin", "time_zone?"])],
|
||||
tuple: [sig(["value", "...values"])],
|
||||
upper: [sig(["string"])],
|
||||
URLHierarchy: [sig(["url"])],
|
||||
};
|
||||
|
||||
const ZERO_ARGUMENT_FUNCTIONS = new Set([
|
||||
"buildId",
|
||||
"currentDatabase",
|
||||
"currentQueryID",
|
||||
"currentUser",
|
||||
"e",
|
||||
"generateUUIDv4",
|
||||
"generateUUIDv7",
|
||||
"hostName",
|
||||
"now",
|
||||
"pi",
|
||||
"rand",
|
||||
"rand64",
|
||||
"revision",
|
||||
"row_number",
|
||||
"serverTimezone",
|
||||
"serverUUID",
|
||||
"today",
|
||||
"timezone",
|
||||
"uptime",
|
||||
"version",
|
||||
"yesterday",
|
||||
]);
|
||||
|
||||
export const CLICKHOUSE_WINDOW_FUNCTION_NAMES = new Set(["cume_dist", "dense_rank", "denseRank", "first_value", "lag", "lagInFrame", "last_value", "lead", "leadInFrame", "nth_value", "ntile", "percent_rank", "percentRank", "rank", "row_number"]);
|
||||
|
||||
function definition(name: string, category: ClickHouseFunctionCategory): ClickHouseFunctionDefinition {
|
||||
const kind = category === "window" ? "window" : "regular";
|
||||
const signatures = Object.prototype.hasOwnProperty.call(SIGNATURE_OVERRIDES, name) ? SIGNATURE_OVERRIDES[name] : [sig(ZERO_ARGUMENT_FUNCTIONS.has(name) ? [] : ["argument", "...arguments?"])];
|
||||
const aliases = Object.prototype.hasOwnProperty.call(CLICKHOUSE_ALIASES_BY_CANONICAL, name) ? CLICKHOUSE_ALIASES_BY_CANONICAL[name] : undefined;
|
||||
return {
|
||||
name,
|
||||
kind,
|
||||
category,
|
||||
signatures,
|
||||
aliases,
|
||||
};
|
||||
}
|
||||
|
||||
export const CLICKHOUSE_REGULAR_FUNCTIONS: ClickHouseFunctionDefinition[] = Object.entries(CLICKHOUSE_REGULAR_NAMES_BY_CATEGORY).flatMap(([category, names]) =>
|
||||
(names ?? "")
|
||||
.split(" ")
|
||||
.filter(Boolean)
|
||||
.map((name) => definition(name, category as ClickHouseFunctionCategory)),
|
||||
);
|
||||
|
||||
export const CLICKHOUSE_FUNCTION_CATEGORY_MANIFEST = [
|
||||
{ category: "array", minimumCount: 80 },
|
||||
{ category: "bitmap", minimumCount: 22 },
|
||||
{ category: "comparison", minimumCount: 46 },
|
||||
{ category: "conversion", minimumCount: 139 },
|
||||
{ category: "date-time", minimumCount: 212 },
|
||||
{ category: "dictionary", minimumCount: 42 },
|
||||
{ category: "encoding", minimumCount: 35 },
|
||||
{ category: "geo", minimumCount: 100 },
|
||||
{ category: "hash", minimumCount: 77 },
|
||||
{ category: "ip", minimumCount: 19 },
|
||||
{ category: "json", minimumCount: 48 },
|
||||
{ category: "map", minimumCount: 23 },
|
||||
{ category: "math", minimumCount: 89 },
|
||||
{ category: "nullable", minimumCount: 9 },
|
||||
{ category: "random", minimumCount: 24 },
|
||||
{ category: "string", minimumCount: 156 },
|
||||
{ category: "tuple", minimumCount: 21 },
|
||||
{ category: "url", minimumCount: 37 },
|
||||
{ category: "window", minimumCount: 13 },
|
||||
{ category: "other", minimumCount: 236 },
|
||||
] as const;
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { ClickHouseFunctionDefinition } from "./functionTypes";
|
||||
|
||||
/** Static name snapshot from ClickHouse Playground system.table_functions on 2026-07-31. */
|
||||
export const CLICKHOUSE_TABLE_FUNCTIONS: ClickHouseFunctionDefinition[] = [
|
||||
{ name: "SQLStandardValues", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "arrowFlight", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "azureBlobStorage", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "azureBlobStorageCluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "cluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "clusterAllReplicas", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "cosn", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "deltaLake", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "deltaLakeAzure", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "deltaLakeAzureCluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "deltaLakeCluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "deltaLakeLocal", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "deltaLakeS3", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "deltaLakeS3Cluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "dictionary", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "executable", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "file", kind: "table", category: "table", signatures: [{ parameterGroups: [["path", "format?", "structure?", "compression?"]] }] },
|
||||
{ name: "fileCluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "filesystem", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "format", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "fuzzJSON", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "fuzzQuery", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "gcs", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "generateRandom", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "generateSeries", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "generate_series", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "hdfs", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "hdfsCluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "hive", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "hudi", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "hudiCluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "iceberg", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "icebergAzure", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "icebergAzureCluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "icebergCluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "icebergHDFS", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "icebergHDFSCluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "icebergLocal", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "icebergLocalCluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "icebergS3", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "icebergS3Cluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "input", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "jdbc", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "loop", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "merge", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "mergeTreeAnalyzeIndexes", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "mergeTreeAnalyzeIndexesUUID", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "mergeTreeIndex", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "mergeTreeProjection", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "mergeTreeTextIndex", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "mongodb", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "mysql", kind: "table", category: "table", signatures: [{ parameterGroups: [["address", "database", "table", "user", "password"]] }] },
|
||||
{ name: "null", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "numbers", kind: "table", category: "table", signatures: [{ parameterGroups: [["count"]] }, { parameterGroups: [["offset", "count"]] }, { parameterGroups: [["offset", "count", "step"]] }] },
|
||||
{ name: "numbers_mt", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "odbc", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "oss", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "paimon", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "paimonAzure", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "paimonAzureCluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "paimonCluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "paimonHDFS", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "paimonHDFSCluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "paimonLocal", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "paimonS3", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "paimonS3Cluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "postgresql", kind: "table", category: "table", signatures: [{ parameterGroups: [["address", "database", "table", "user", "password", "schema?"]] }] },
|
||||
{ name: "primes", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "prometheusQuery", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "prometheusQueryRange", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "redis", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "remote", kind: "table", category: "table", signatures: [{ parameterGroups: [["addresses", "database", "table", "user?", "password?"]] }] },
|
||||
{ name: "remoteSecure", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "s3", kind: "table", category: "table", signatures: [{ parameterGroups: [["url", "format?", "structure?", "compression?"]] }] },
|
||||
{ name: "s3Cluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "sqlite", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "timeSeriesData", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "timeSeriesMetrics", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "timeSeriesSamples", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "timeSeriesSelector", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "timeSeriesTags", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "url", kind: "table", category: "table", signatures: [{ parameterGroups: [["url", "format", "structure?", "headers?"]] }] },
|
||||
{ name: "urlCluster", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "values", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "view", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "viewExplain", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "viewIfPermitted", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "ytsaurus", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "zeros", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
{ name: "zeros_mt", kind: "table", category: "table", signatures: [{ parameterGroups: [["argument", "...arguments?"]] }] },
|
||||
];
|
||||
@@ -2,6 +2,8 @@ import { Cassandra, MariaSQL, MSSQL, MySQL, PLSQL, PostgreSQL, SQLite, StandardS
|
||||
import type { DatabaseType, SqlSnippet } from "@/types/database";
|
||||
import { buildMongoCompletionItemsFromContext, type MongoCompletionItem } from "@/lib/mongo/mongoCompletion";
|
||||
import { CLOUDFLARE_D1_COMMON_FUNCTION_NAMES } from "@/lib/sql/cloudflareD1";
|
||||
import { searchClickHouseFunctions } from "@/lib/sql/clickhouse/functionRegistry";
|
||||
import type { ClickHouseFunctionDefinition, ClickHouseFunctionKind } from "@/lib/sql/clickhouse/functionTypes";
|
||||
import type { SqlObjectNavigationType } from "@/lib/sql/sqlNavigation";
|
||||
import { sqlSemanticDialectFor } from "@/lib/sql/semantic/dialect";
|
||||
import { findActiveSqlStatementSpan, tokenizeSqlSemantic } from "@/lib/sql/semantic/tokens";
|
||||
@@ -1253,15 +1255,26 @@ export interface SqlCompletionContext {
|
||||
oracleTableFunctionContext?: boolean;
|
||||
autoAliasTableCompletions: boolean;
|
||||
tableAliasAfterCursor?: boolean;
|
||||
openingParenAfterCursor: boolean;
|
||||
contextKind: SqlCompletionContextKind;
|
||||
dataTypeContext: boolean;
|
||||
}
|
||||
|
||||
export interface SqlFunctionSignatureHelpOverload {
|
||||
signature: string;
|
||||
parameterGroups: string[][];
|
||||
activeGroup: number;
|
||||
activeParameter: number;
|
||||
}
|
||||
|
||||
export interface SqlFunctionSignatureHelp {
|
||||
name: string;
|
||||
signature: string;
|
||||
activeParameter: number;
|
||||
parameters: string[];
|
||||
overloads: SqlFunctionSignatureHelpOverload[];
|
||||
activeOverload: number;
|
||||
/** Legacy single-overload fields retained for non-ClickHouse callers. */
|
||||
signature?: string;
|
||||
activeParameter?: number;
|
||||
parameters?: string[];
|
||||
}
|
||||
|
||||
export interface SqlCompletionTranslations {
|
||||
@@ -1346,7 +1359,7 @@ class SqlCompletionProvider {
|
||||
this.items.push(...buildSnippetItems(context.prefix, snippets, this.input.keywordCase, this.databaseType));
|
||||
}
|
||||
if (!preferReferencedColumns || context.suggestRoutines) {
|
||||
const functionItems = context.dataTypeContext ? [] : buildFunctionSnippetItems(context.prefix, getFunctionDescriptions(this.t), this.databaseType);
|
||||
const functionItems = context.dataTypeContext ? [] : buildFunctionSnippetItems(context.prefix, getFunctionDescriptions(this.t), this.databaseType, context.openingParenAfterCursor);
|
||||
this.items.push(...(preferReferencedColumns ? functionItems.filter((item) => item.label.toLowerCase().startsWith(context.prefix.toLowerCase())) : functionItems));
|
||||
if (isOracleLikeDatabase(this.databaseType)) {
|
||||
this.items.push(...buildOracleSystemValueItems(context.prefix, this.input.keywordCase));
|
||||
@@ -1402,6 +1415,9 @@ class SqlCompletionProvider {
|
||||
if (!context.exclusiveColumnSuggestions && context.suggestTables) {
|
||||
this.items.push(...buildForeignKeyRelatedTableItems(context, this.input.tables, this.input.foreignKeysByTable, this.dialect));
|
||||
this.items.push(...buildTableItems(context, this.input.tables, this.dialect, !!this.input.autoAliasTables && context.autoAliasTableCompletions, context.referencedTables, this.databaseType, this.input.currentSchema));
|
||||
if (this.databaseType === "clickhouse") {
|
||||
this.items.push(...buildClickHouseFunctionItems(context.prefix, context.openingParenAfterCursor, "table"));
|
||||
}
|
||||
if (isOracleLikeDatabase(this.databaseType)) {
|
||||
this.items.push(...buildOracleTableFunctionItems(context.prefix));
|
||||
}
|
||||
@@ -1630,25 +1646,63 @@ export function getSqlCompletionResultValidFor(sql: string, cursor: number): Reg
|
||||
|
||||
export function getSqlFunctionSignatureHelp(sql: string, cursor: number, databaseType?: DatabaseType): SqlFunctionSignatureHelp | null {
|
||||
const beforeCursor = sql.slice(0, cursor);
|
||||
const openParenIndex = findActiveFunctionOpenParen(beforeCursor);
|
||||
if (openParenIndex == null) return null;
|
||||
const call = findActiveFunctionCall(beforeCursor);
|
||||
if (!call) return null;
|
||||
|
||||
const beforeParen = beforeCursor.slice(0, openParenIndex).trimEnd();
|
||||
const name = /([A-Za-z_][\w$]*)$/.exec(beforeParen)?.[1]?.toUpperCase();
|
||||
if (!name) return null;
|
||||
const observedParameter = countTopLevelCommas(call.groupText);
|
||||
if (databaseType !== "clickhouse") {
|
||||
const lookupName = call.name.toUpperCase();
|
||||
const parameters = (databaseType ? DATABASE_FUNCTION_SIGNATURES[databaseType]?.get(lookupName) : undefined) ?? SQL_FUNCTION_SIGNATURES.get(lookupName);
|
||||
if (!parameters) return null;
|
||||
const activeParameter = Math.min(observedParameter, Math.max(0, parameters.length - 1));
|
||||
const signature = `${lookupName}(${parameters.join(", ")})`;
|
||||
const legacyHelp = { name: lookupName, signature, activeParameter, parameters };
|
||||
Object.defineProperties(legacyHelp, {
|
||||
overloads: {
|
||||
value: [{ signature, parameterGroups: [parameters], activeGroup: 0, activeParameter }],
|
||||
enumerable: false,
|
||||
},
|
||||
activeOverload: { value: 0, enumerable: false },
|
||||
});
|
||||
return legacyHelp as SqlFunctionSignatureHelp;
|
||||
}
|
||||
|
||||
const parameters = (databaseType ? DATABASE_FUNCTION_SIGNATURES[databaseType]?.get(name) : undefined) ?? SQL_FUNCTION_SIGNATURES.get(name);
|
||||
if (!parameters) return null;
|
||||
const parameterGroups = searchClickHouseFunctions(call.name, 50)
|
||||
.find((definition) => [definition.name, ...(definition.aliases ?? [])].some((name) => name.toLowerCase() === call.name.toLowerCase()))
|
||||
?.signatures.map((signature) => signature.parameterGroups);
|
||||
if (!parameterGroups) return null;
|
||||
|
||||
const overloads = parameterGroups
|
||||
.map((groups, sourceIndex) => ({ groups, sourceIndex }))
|
||||
.filter(({ groups }) => groups[call.activeGroup] != null)
|
||||
.sort((left, right) => {
|
||||
const leftAccepts = functionParameterGroupAccepts(left.groups[call.activeGroup], observedParameter);
|
||||
const rightAccepts = functionParameterGroupAccepts(right.groups[call.activeGroup], observedParameter);
|
||||
return Number(rightAccepts) - Number(leftAccepts) || left.sourceIndex - right.sourceIndex;
|
||||
})
|
||||
.map(({ groups }) => {
|
||||
const parameters = groups[call.activeGroup];
|
||||
return {
|
||||
signature: call.name + groups.map((group) => `(${group.join(", ")})`).join(""),
|
||||
parameterGroups: groups,
|
||||
activeGroup: call.activeGroup,
|
||||
activeParameter: Math.min(observedParameter, Math.max(0, parameters.length - 1)),
|
||||
};
|
||||
});
|
||||
if (overloads.length === 0) return null;
|
||||
|
||||
const activeParameter = countTopLevelCommas(beforeCursor.slice(openParenIndex + 1));
|
||||
return {
|
||||
name,
|
||||
signature: `${name}(${parameters.join(", ")})`,
|
||||
activeParameter: Math.min(activeParameter, Math.max(0, parameters.length - 1)),
|
||||
parameters,
|
||||
name: call.name,
|
||||
overloads,
|
||||
activeOverload: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function functionParameterGroupAccepts(parameters: string[], observedParameter: number): boolean {
|
||||
if (observedParameter < parameters.length) return true;
|
||||
return parameters.some((parameter) => parameter.startsWith("..."));
|
||||
}
|
||||
|
||||
function sqlCompletionStatementSpan(sql: string, cursor: number, options: SqlSemanticBuildOptions): SqlSemanticSpan {
|
||||
const activeStatementSpan = activeSqlCompletionStatementSpan(sql, cursor, options);
|
||||
return currentSqlLikeLineBlockSpan(sql, cursor, activeStatementSpan) ?? activeStatementSpan;
|
||||
@@ -1836,6 +1890,7 @@ export function getSqlCompletionContext(sql: string, cursor: number, options: Sq
|
||||
oracleTableFunctionContext,
|
||||
autoAliasTableCompletions,
|
||||
tableAliasAfterCursor,
|
||||
openingParenAfterCursor: /^\s*\(/.test(sql.slice(cursor)),
|
||||
contextKind,
|
||||
dataTypeContext,
|
||||
};
|
||||
@@ -3991,7 +4046,46 @@ function activeFunctionSignatures(databaseType?: DatabaseType): Map<string, stri
|
||||
return signatures;
|
||||
}
|
||||
|
||||
function buildFunctionSnippetItems(prefix: string, functionDescriptions: Map<string, string>, databaseType?: DatabaseType): SqlCompletionItem[] {
|
||||
function formatFunctionSignatureApply(definition: ClickHouseFunctionDefinition, omitOpeningParen: boolean): string {
|
||||
if (omitOpeningParen) return definition.name;
|
||||
const signature = definition.signatures[definition.preferredSignature ?? 0];
|
||||
return (
|
||||
definition.name +
|
||||
signature.parameterGroups
|
||||
.map(
|
||||
(group) =>
|
||||
`(${group
|
||||
.filter((parameter) => !parameter.endsWith("?"))
|
||||
.map((parameter) => `\${${parameter}}`)
|
||||
.join(", ")})`,
|
||||
)
|
||||
.join("")
|
||||
);
|
||||
}
|
||||
|
||||
function clickHouseFunctionDetail(definition: ClickHouseFunctionDefinition): string {
|
||||
const status = definition.status && definition.status !== "stable" ? ` · ${definition.status}` : "";
|
||||
const overloads = definition.signatures.length > 1 ? ` · ${definition.signatures.length} overloads` : "";
|
||||
return `ClickHouse · ${definition.category}${overloads}${status}`;
|
||||
}
|
||||
|
||||
function buildClickHouseFunctionItems(prefix: string, omitOpeningParen: boolean, kind?: ClickHouseFunctionKind): SqlCompletionItem[] {
|
||||
return searchClickHouseFunctions(prefix, 200, kind).map((definition) => {
|
||||
const statusPenalty = definition.status === "deprecated" ? -600 : definition.status === "experimental" ? -300 : 0;
|
||||
const generatedPenalty = definition.generated ? -75 : 0;
|
||||
return {
|
||||
label: definition.name,
|
||||
type: "function" as const,
|
||||
detail: clickHouseFunctionDetail(definition),
|
||||
info: definition.description,
|
||||
apply: formatFunctionSignatureApply(definition, omitOpeningParen),
|
||||
boost: computeBoost(definition.name, prefix) + 300 + statusPenalty + generatedPenalty,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function buildFunctionSnippetItems(prefix: string, functionDescriptions: Map<string, string>, databaseType?: DatabaseType, omitOpeningParen = false): SqlCompletionItem[] {
|
||||
if (databaseType === "clickhouse") return buildClickHouseFunctionItems(prefix, omitOpeningParen);
|
||||
const items: SqlCompletionItem[] = [];
|
||||
|
||||
for (const [name, parameters] of activeFunctionSignatures(databaseType).entries()) {
|
||||
@@ -4288,6 +4382,62 @@ function getTypePriorityBoost(type: SqlCompletionItem["type"]): number {
|
||||
}
|
||||
}
|
||||
|
||||
interface ActiveFunctionCall {
|
||||
name: string;
|
||||
activeGroup: number;
|
||||
groupText: string;
|
||||
}
|
||||
|
||||
function findActiveFunctionCall(sqlBeforeCursor: string): ActiveFunctionCall | null {
|
||||
const activeOpenParen = findActiveFunctionOpenParen(sqlBeforeCursor);
|
||||
if (activeOpenParen == null) return null;
|
||||
|
||||
const beforeActiveGroup = sqlBeforeCursor.slice(0, activeOpenParen).trimEnd();
|
||||
const ordinaryName = /([A-Za-z_][\w$]*)$/.exec(beforeActiveGroup)?.[1];
|
||||
if (ordinaryName) {
|
||||
return {
|
||||
name: ordinaryName,
|
||||
activeGroup: 0,
|
||||
groupText: sqlBeforeCursor.slice(activeOpenParen + 1),
|
||||
};
|
||||
}
|
||||
|
||||
if (!beforeActiveGroup.endsWith(")")) return null;
|
||||
const firstGroupOpenParen = findMatchingOpenParen(beforeActiveGroup, beforeActiveGroup.length - 1);
|
||||
if (firstGroupOpenParen == null) return null;
|
||||
const parametricName = /([A-Za-z_][\w$]*)$/.exec(beforeActiveGroup.slice(0, firstGroupOpenParen).trimEnd())?.[1];
|
||||
if (!parametricName) return null;
|
||||
return {
|
||||
name: parametricName,
|
||||
activeGroup: 1,
|
||||
groupText: sqlBeforeCursor.slice(activeOpenParen + 1),
|
||||
};
|
||||
}
|
||||
|
||||
function findMatchingOpenParen(text: string, closeParenIndex: number): number | null {
|
||||
let depth = 0;
|
||||
let inSingleQuote = false;
|
||||
let inDoubleQuote = false;
|
||||
for (let index = closeParenIndex; index >= 0; index -= 1) {
|
||||
const character = text[index];
|
||||
if (character === "'" && !inDoubleQuote) {
|
||||
inSingleQuote = !inSingleQuote;
|
||||
continue;
|
||||
}
|
||||
if (character === '"' && !inSingleQuote) {
|
||||
inDoubleQuote = !inDoubleQuote;
|
||||
continue;
|
||||
}
|
||||
if (inSingleQuote || inDoubleQuote) continue;
|
||||
if (character === ")") depth += 1;
|
||||
else if (character === "(") {
|
||||
depth -= 1;
|
||||
if (depth === 0) return index;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function findActiveFunctionOpenParen(sqlBeforeCursor: string): number | null {
|
||||
let depth = 0;
|
||||
let inSingleQuote = false;
|
||||
|
||||
Reference in new issue
Block a user