| 362 | } |
| 363 | |
| 364 | export function createMaterializedView({ |
| 365 | name: tableName, |
| 366 | query, |
| 367 | engine = 'AggregatingMergeTree()', |
| 368 | orderBy, |
| 369 | partitionBy, |
| 370 | settings = {}, |
| 371 | populate = false, |
| 372 | distributionHash = 'rand()', |
| 373 | replicatedVersion, |
| 374 | isClustered, |
| 375 | }: CreateMaterializedViewOptions): string[] { |
| 376 | const settingsClause = Object.entries(settings).length |
| 377 | ? `SETTINGS ${Object.entries(settings) |
| 378 | .map(([key, value]) => `${key} = ${value}`) |
| 379 | .join(', ')}` |
| 380 | : ''; |
| 381 | |
| 382 | const partitionByClause = partitionBy ? `PARTITION BY ${partitionBy}` : ''; |
| 383 | |
| 384 | // Transform query to use replicated table names in clustered mode |
| 385 | const transformedQuery = query.replace(/\{(\w+)\}/g, (_, tableName) => |
| 386 | isClustered ? replicated(tableName) : tableName, |
| 387 | ); |
| 388 | |
| 389 | if (!isClustered) { |
| 390 | return [ |
| 391 | `CREATE MATERIALIZED VIEW IF NOT EXISTS ${tableName} |
| 392 | ENGINE = ${engine} |
| 393 | ${partitionByClause} |
| 394 | ORDER BY (${orderBy.join(', ')}) |
| 395 | ${settingsClause} |
| 396 | ${populate ? 'POPULATE' : ''} |
| 397 | AS ${transformedQuery}`.trim(), |
| 398 | ]; |
| 399 | } |
| 400 | |
| 401 | return [ |
| 402 | // Replicated materialized view |
| 403 | `CREATE MATERIALIZED VIEW IF NOT EXISTS ${replicated(tableName)} ON CLUSTER '{cluster}' |
| 404 | ENGINE = Replicated${engine.replace(/^(.+?)\((.+?)?\)/, `$1('${CLUSTER_REPLICA_PATH.replace('{replicatedVersion}', replicatedVersion)}', '{replica}', $2)`).replace(/, \)$/, ')')} |
| 405 | ${partitionByClause} |
| 406 | ORDER BY (${orderBy.join(', ')}) |
| 407 | ${settingsClause} |
| 408 | ${populate ? 'POPULATE' : ''} |
| 409 | AS ${transformedQuery}`.trim(), |
| 410 | // Distributed materialized view |
| 411 | `CREATE TABLE IF NOT EXISTS ${tableName} ON CLUSTER '{cluster}' AS ${replicated(tableName)} |
| 412 | ENGINE = Distributed('{cluster}', currentDatabase(), ${replicated(tableName)}, ${distributionHash})`, |
| 413 | ]; |
| 414 | } |
| 415 | |
| 416 | export function countRows(tableName: string) { |
| 417 | return `SELECT count() FROM ${tableName}`; |