MCPcopy Create free account
hub / github.com/mikro-orm/mikro-orm / toEntityPartitionBy

Function toEntityPartitionBy

packages/sql/src/schema/partitioning.ts:419–474  ·  view source on GitHub ↗
(
  partitioning: TablePartitioning | undefined,
  parentTableName?: string,
  parentSchema?: string,
)

Source from the content-addressed store, hash-verified

417
418/** @internal */
419export const toEntityPartitionBy = (
420 partitioning: TablePartitioning | undefined,
421 parentTableName?: string,
422 parentSchema?: string,
423): EntityPartitionBy | undefined => {
424 if (!partitioning) {
425 return undefined;
426 }
427
428 const normalizedDefinition = normalizePartitionDefinition(partitioning.definition);
429 const normalizedPartitions = partitioning.partitions.map(partition => ({
430 ...partition,
431 bound: normalizePartitionBound(partition.bound),
432 }));
433 // Split the leading type keyword off of the definition without using `split(' ')`, which would
434 // shatter quoted literals containing spaces. Match a bareword prefix followed by whitespace.
435 const [, rawType = normalizedDefinition, rawExpression = ''] =
436 /^(\S+)(?:\s+([\s\S]*))?$/.exec(normalizeWhitespace(normalizedDefinition)) ?? [];
437 const type = rawType.toLowerCase();
438
439 if (!isSupportedPartitionType(type)) {
440 throw new Error(`Unsupported partition type '${rawType}' in definition '${partitioning.definition}'`);
441 }
442
443 const expression = unwrapOuterParentheses(rawExpression);
444 const qualify = (partition: TablePartition) =>
445 partition.schema && partition.schema !== parentSchema ? `${partition.schema}.${partition.name}` : partition.name;
446
447 if (type === 'hash') {
448 // Collapse to a bare count when catalog names follow the default
449 // `${parentTableName}_${remainder}` pattern and live in the parent's schema, or when we have
450 // no parent context to compare against (backwards-compatible behavior for callers that pass
451 // just the `TablePartitioning`). Otherwise preserve the explicit name array so the next DDL
452 // generation reproduces the same children.
453 const usesDefaultShape =
454 parentTableName == null ||
455 normalizedPartitions.every(
456 (p, i) => p.name === `${parentTableName}_${i}` && (!p.schema || p.schema === parentSchema),
457 );
458
459 return {
460 type,
461 expression,
462 partitions: usesDefaultShape ? normalizedPartitions.length : normalizedPartitions.map(qualify),
463 };
464 }
465
466 return {
467 type,
468 expression,
469 partitions: normalizedPartitions.map(partition => ({
470 name: qualify(partition),
471 values: partition.bound === 'default' ? 'default' : partition.bound.replace(/^for values\s+/i, ''),
472 })),
473 };
474};

Callers 2

getEntityDeclarationMethod · 0.85

Calls 7

normalizePartitionBoundFunction · 0.85
normalizeWhitespaceFunction · 0.85
isSupportedPartitionTypeFunction · 0.85
unwrapOuterParenthesesFunction · 0.85
qualifyFunction · 0.85
mapMethod · 0.45

Tested by

no test coverage detected