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

Method prepareFields

packages/sql/src/query/QueryBuilder.ts:3143–3256  ·  view source on GitHub ↗
(
    fields: InternalField<T>[],
    type: 'where' | 'groupBy' | 'sub-query' = 'where',
    schema?: string,
  )

Source from the content-addressed store, hash-verified

3141 }
3142
3143 protected prepareFields<T>(
3144 fields: InternalField<T>[],
3145 type: 'where' | 'groupBy' | 'sub-query' = 'where',
3146 schema?: string,
3147 ): (string | RawQueryFragment)[] {
3148 const ret: InternalField<T>[] = [];
3149 const getFieldName = (name: string, customAlias?: string) => {
3150 const alias = customAlias ?? (type === 'groupBy' ? null : undefined);
3151 return this.helper.mapper(name, this.type, undefined, alias, schema);
3152 };
3153
3154 fields.forEach(originalField => {
3155 if (typeof originalField !== 'string') {
3156 ret.push(originalField);
3157 return;
3158 }
3159
3160 // Strip 'as alias' suffix if present — the alias is passed to mapper at the end
3161 let field = originalField;
3162 let customAlias: string | undefined;
3163 const asMatch = FIELD_ALIAS_RE.exec(originalField);
3164
3165 if (asMatch) {
3166 field = asMatch[1].trim();
3167 customAlias = asMatch[2];
3168 }
3169
3170 const join = Object.keys(this.#state.joins).find(k => field === k.substring(0, k.indexOf('#')))!;
3171
3172 if (join && type === 'where') {
3173 ret.push(...(this.helper.mapJoinColumns(this.type, this.#state.joins[join]) as string[]));
3174 return;
3175 }
3176
3177 const [a, f] = this.helper.splitField(field as EntityKey<T>);
3178 const prop = this.helper.getProperty(f, a);
3179
3180 /* v8 ignore next */
3181 if (prop && [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
3182 return;
3183 }
3184
3185 if (prop?.persist === false && !prop.embedded && !prop.formula && type === 'where') {
3186 return;
3187 }
3188
3189 if (prop?.embedded || (prop?.kind === ReferenceKind.EMBEDDED && prop.object)) {
3190 const name = prop.embeddedPath?.join('.') ?? prop.fieldNames[0];
3191 const aliased = this.#state.aliases[a] ? `${a}.${name}` : name;
3192 ret.push(getFieldName(aliased, customAlias));
3193 return;
3194 }
3195
3196 if (prop?.kind === ReferenceKind.EMBEDDED) {
3197 if (customAlias) {
3198 throw new Error(
3199 `Cannot use 'as ${customAlias}' alias on embedded property '${field}' because it expands to multiple columns. Alias individual fields instead (e.g. '${field}.propertyName as ${customAlias}').`,
3200 );

Callers 5

getNativeQueryMethod · 0.95
getQueryBaseMethod · 0.95
wrapPaginateSubQueryMethod · 0.95
wrapModifySubQueryMethod · 0.95
wrapPaginateSubQueryMethod · 0.80

Calls 12

pushMethod · 0.80
mapJoinColumnsMethod · 0.80
splitFieldMethod · 0.80
filterMethod · 0.80
mapperMethod · 0.80
findMethod · 0.65
joinMethod · 0.65
hasMethod · 0.65
uniqueMethod · 0.65
keysMethod · 0.45
getPropertyMethod · 0.45
mapMethod · 0.45

Tested by

no test coverage detected