MCPcopy Create free account
hub / github.com/Openpanel-dev/openpanel / createMaterializedView

Function createMaterializedView

packages/db/src/clickhouse/migration.ts:364–414  ·  view source on GitHub ↗
({
  name: tableName,
  query,
  engine = 'AggregatingMergeTree()',
  orderBy,
  partitionBy,
  settings = {},
  populate = false,
  distributionHash = 'rand()',
  replicatedVersion,
  isClustered,
}: CreateMaterializedViewOptions)

Source from the content-addressed store, hash-verified

362}
363
364export 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}
392ENGINE = ${engine}
393${partitionByClause}
394ORDER BY (${orderBy.join(', ')})
395${settingsClause}
396${populate ? 'POPULATE' : ''}
397AS ${transformedQuery}`.trim(),
398 ];
399 }
400
401 return [
402 // Replicated materialized view
403 `CREATE MATERIALIZED VIEW IF NOT EXISTS ${replicated(tableName)} ON CLUSTER '{cluster}'
404ENGINE = Replicated${engine.replace(/^(.+?)\((.+?)?\)/, `$1('${CLUSTER_REPLICA_PATH.replace('{replicatedVersion}', replicatedVersion)}', '{replica}', $2)`).replace(/, \)$/, ')')}
405${partitionByClause}
406ORDER BY (${orderBy.join(', ')})
407${settingsClause}
408${populate ? 'POPULATE' : ''}
409AS ${transformedQuery}`.trim(),
410 // Distributed materialized view
411 `CREATE TABLE IF NOT EXISTS ${tableName} ON CLUSTER '{cluster}' AS ${replicated(tableName)}
412ENGINE = Distributed('{cluster}', currentDatabase(), ${replicated(tableName)}, ${distributionHash})`,
413 ];
414}
415
416export function countRows(tableName: string) {
417 return `SELECT count() FROM ${tableName}`;

Callers 3

upFunction · 0.90
upFunction · 0.90
upFunction · 0.90

Calls 4

joinMethod · 0.80
replaceMethod · 0.80
replicatedFunction · 0.70
mapMethod · 0.45

Tested by

no test coverage detected