Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions src/__tests__/long-alias.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Column, Entity, JoinColumn, ManyToOne, OneToMany, PrimaryGeneratedColumn, Relation } from 'typeorm'

// Relation names long enough that the path-derived join aliases (`__root_<relation>_rel...`)
// exceed the 63 character identifier limit of Postgres. The two relations share a long common
// prefix, so plain truncation would give both joins the same alias. The join columns get short
// names so the tables can be created on MariaDB, whose column names are limited to 64 characters.

@Entity()
export class LongAliasLeafEntity {
@PrimaryGeneratedColumn()
id: number

@Column()
label: string
}

@Entity()
export class LongAliasTargetEntity {
@PrimaryGeneratedColumn()
id: number

@Column()
name: string

@ManyToOne(() => LongAliasLeafEntity, { nullable: true })
@JoinColumn()
leafReachedThroughAnotherVeryLongRelationName?: LongAliasLeafEntity

@ManyToOne(() => LongAliasOwnerEntity, (owner) => owner.targetsReachedThroughAVeryLongRelationName)
@JoinColumn()
owner: Relation<LongAliasOwnerEntity>
}

@Entity()
export class LongAliasOwnerEntity {
@PrimaryGeneratedColumn()
id: number

@Column()
name: string

@ManyToOne(() => LongAliasTargetEntity, { nullable: true })
@JoinColumn({ name: 'firstTargetId' })
relationWithAnExceptionallyLongNameThatOverflowsTheAliasLimitFirst?: LongAliasTargetEntity

@ManyToOne(() => LongAliasTargetEntity, { nullable: true })
@JoinColumn({ name: 'secondTargetId' })
relationWithAnExceptionallyLongNameThatOverflowsTheAliasLimitSecond?: LongAliasTargetEntity

@OneToMany(() => LongAliasTargetEntity, (target) => target.owner)
targetsReachedThroughAVeryLongRelationName: LongAliasTargetEntity[]
}
21 changes: 21 additions & 0 deletions src/alias-length.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { getJoinAlias } from './helper'

describe('getJoinAlias', () => {
const driver = (maxAliasLength?: number) => ({ connection: { driver: { maxAliasLength } } }) as any

it('keeps aliases that fit within the driver limit unchanged', () => {
expect(getJoinAlias(driver(63), '__root_toys_rel')).toBe('__root_toys_rel')
expect(getJoinAlias(driver(undefined), 'x'.repeat(200))).toBe('x'.repeat(200))
})

it('shortens long aliases deterministically and keeps them distinct', () => {
const prefix = '__root_' + 'a'.repeat(60)
const first = getJoinAlias(driver(63), `${prefix}_first_rel`)
const second = getJoinAlias(driver(63), `${prefix}_second_rel`)

expect(first.length).toBeLessThanOrEqual(63)
expect(second.length).toBeLessThanOrEqual(63)
expect(first).not.toBe(second)
expect(getJoinAlias(driver(63), `${prefix}_first_rel`)).toBe(first)
})
})
12 changes: 7 additions & 5 deletions src/filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
createRelationSchema,
extractVirtualProperty,
fixColumnAlias,
getJoinAlias,
getPropertiesByColumnName,
isDateColumnType,
isISODate,
Expand Down Expand Up @@ -244,11 +245,12 @@ export function preparePolymorphicColumn(qb: SelectQueryBuilder<any>, column: st
`Polymorphic filter groups (using "~") support only to-one relations, not "${part}".`
)
}
const joinAlias = `${parentAlias}_${relationName}_rel`
const pathAlias = `${parentAlias}_${relationName}_rel`
const joinAlias = getJoinAlias(qb, pathAlias)
if (!qb.expressionMap.joinAttributes.some((attr) => attr.alias?.name === joinAlias)) {
qb.leftJoin(`${parentAlias}.${relationName}`, joinAlias)
qb.leftJoin(`${getJoinAlias(qb, parentAlias)}.${relationName}`, joinAlias)
}
parentAlias = joinAlias
parentAlias = pathAlias
metadata = relation.inverseEntityMetadata
}
}
Expand Down Expand Up @@ -962,8 +964,8 @@ export function addToManySubFilters<T>(
// Build and correlate the single EXISTS subquery for this path. `pathSlug` keeps its
// aliases and parameters from colliding with other relation paths in the same query.
const buildExistsQb = () => {
const relAlias = (name: string, depth: number) => `_rel_${name}_${depth}_${pathSlug}`
const juncAlias = (name: string, depth: number) => `_junc_${name}_${depth}_${pathSlug}`
const relAlias = (name: string, depth: number) => getJoinAlias(qb, `_rel_${name}_${depth}_${pathSlug}`)
const juncAlias = (name: string, depth: number) => getJoinAlias(qb, `_junc_${name}_${depth}_${pathSlug}`)
const leafAlias = relAlias(relationPath[relationPath.length - 1][0], relationPath.length - 1)
const existsQb = qb.connection.createQueryBuilder(existsMetadata.target as any, leafAlias)

Expand Down
46 changes: 40 additions & 6 deletions src/helper.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createHash } from 'crypto'
import { mergeWith } from 'lodash'
import { FindOperator, FindOptionsRelations, ObjectLiteral, Repository, SelectQueryBuilder } from 'typeorm'
import { ColumnMetadata } from 'typeorm/metadata/ColumnMetadata'
Expand Down Expand Up @@ -325,6 +326,23 @@ export function resolveJsonbPath(qb: SelectQueryBuilder<unknown>, column: string
return notJsonb
}

/**
* Returns the alias to use for a join whose path-derived alias (e.g. `__root_toys_rel_shop_rel`) may
* exceed the identifier length limit of the database (63 characters on Postgres). The database would
* silently truncate such an alias, so two joins sharing a long prefix would end up with the same
* name. Aliases over the driver's `maxAliasLength` are cut and suffixed with a hash of the full
* alias, which keeps them deterministic (every reference to the same path resolves to the same
* alias) and distinct. Aliases within the limit are returned unchanged.
*/
export function getJoinAlias(qb: { connection: { driver: { maxAliasLength?: number } } }, alias: string): string {
const maxAliasLength = qb.connection.driver.maxAliasLength
if (!maxAliasLength || alias.length <= maxAliasLength) {
return alias
}
const hash = createHash('sha1').update(alias).digest('hex').slice(0, 8)
return `${alias.slice(0, maxAliasLength - hash.length - 1)}_${hash}`
}

// This function is used to fix the column alias when using relation, embedded or virtual properties
export function fixColumnAlias(
properties: ColumnProperties,
Expand All @@ -344,13 +362,14 @@ export function fixColumnAlias(
const baseColumnProperties = getPropertiesByColumnName(
[...jsonbResolution.relationPath, jsonbResolution.jsonbColumn].join('.')
)
const baseAlias = fixColumnAlias(
const baseAlias = buildColumnAlias(
baseColumnProperties,
alias,
jsonbResolution.relationPath.length > 0,
isVirtualProperty,
isEmbedded,
query
query,
qb
)

if (jsonbResolution.jsonPath.length === 0) {
Expand All @@ -370,9 +389,24 @@ export function fixColumnAlias(
}
}

return buildColumnAlias(properties, alias, isRelation, isVirtualProperty, isEmbedded, query, qb)
}

function buildColumnAlias(
properties: ColumnProperties,
alias: string,
isRelation: boolean,
isVirtualProperty: boolean,
isEmbedded: boolean,
query?: ColumnMetadata['query'],
qb?: SelectQueryBuilder<unknown>
): string {
const joinAlias = (path: string) => (qb ? getJoinAlias(qb, path) : path)

if (isRelation) {
const relationAlias = joinAlias(`${alias}_${properties.propertyPath}_rel`)
if (isVirtualProperty && query) {
return `(${query(`${alias}_${properties.propertyPath}_rel`)})` // () is needed to avoid parameter conflict
return `(${query(relationAlias)})` // () is needed to avoid parameter conflict
} else if ((isVirtualProperty && !query) || properties.isNested) {
if (properties.propertyName.includes('.')) {
const propertyPath = properties.propertyName.split('.')
Expand All @@ -382,12 +416,12 @@ export function fixColumnAlias(
.join('_')
const nestedCol = propertyPath[propertyPath.length - 1]

return `${alias}_${properties.propertyPath}_rel_${nestedRelations}.${nestedCol}`
return `${joinAlias(`${alias}_${properties.propertyPath}_rel_${nestedRelations}`)}.${nestedCol}`
} else {
return `${alias}_${properties.propertyPath}_rel_${properties.propertyName}`
return `${relationAlias}_${properties.propertyName}`
}
} else {
return `${alias}_${properties.propertyPath}_rel.${properties.propertyName}`
return `${relationAlias}.${properties.propertyName}`
}
} else if (isVirtualProperty) {
return query ? `(${query(`${alias}`)})` : `${alias}_${properties.propertyName}`
Expand Down
111 changes: 111 additions & 0 deletions src/paginate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { CatHomePillowEntity } from './__tests__/cat-home-pillow.entity'
import { CatHomeEntity } from './__tests__/cat-home.entity'
import { CatToyEntity } from './__tests__/cat-toy.entity'
import { CatEntity, CutenessLevel } from './__tests__/cat.entity'
import { LongAliasLeafEntity, LongAliasOwnerEntity, LongAliasTargetEntity } from './__tests__/long-alias.entity'
import { ToyShopAddressEntity } from './__tests__/toy-shop-address.entity'
import { ToyShopEntity } from './__tests__/toy-shop.entity'
import { PaginateQuery } from './decorator'
Expand Down Expand Up @@ -76,6 +77,9 @@ describe('paginate', () => {
CatHomePillowEntity,
CatHomePillowBrandEntity,
ToyShopEntity,
LongAliasOwnerEntity,
LongAliasTargetEntity,
LongAliasLeafEntity,
process.env.DB === 'postgres' ? CatHairEntity : undefined,
],
}
Expand Down Expand Up @@ -6132,4 +6136,111 @@ describe('paginate', () => {
})
})
}

describe('join aliases longer than the database identifier limit', () => {
let ownerRepo: Repository<LongAliasOwnerEntity>

const first = 'relationWithAnExceptionallyLongNameThatOverflowsTheAliasLimitFirst'
const second = 'relationWithAnExceptionallyLongNameThatOverflowsTheAliasLimitSecond'
const nested = 'leafReachedThroughAnotherVeryLongRelationName'
const toMany = 'targetsReachedThroughAVeryLongRelationName'

beforeAll(async () => {
ownerRepo = dataSource.getRepository(LongAliasOwnerEntity)
const targetRepo = dataSource.getRepository(LongAliasTargetEntity)
const leafRepo = dataSource.getRepository(LongAliasLeafEntity)

const [leafA, leafB] = await leafRepo.save([
leafRepo.create({ label: 'A' }),
leafRepo.create({ label: 'B' }),
])
const [one, two] = await targetRepo.save([
targetRepo.create({ name: 'one', [nested]: leafA }),
targetRepo.create({ name: 'two', [nested]: leafB }),
])
const [alpha, beta] = await ownerRepo.save([
ownerRepo.create({ name: 'alpha', [first]: one, [second]: two }),
ownerRepo.create({ name: 'beta', [first]: two, [second]: one }),
])
await targetRepo.save([
targetRepo.create({ name: 'child of alpha', owner: alpha }),
targetRepo.create({ name: 'child of beta', owner: beta }),
])
})

it('loads, sorts and filters two relations whose aliases share a long prefix', async () => {
const config: PaginateConfig<LongAliasOwnerEntity> = {
relations: { [first]: { [nested]: true }, [second]: { [nested]: true } },
sortableColumns: ['id', `${first}.name`, `${second}.${nested}.label`],
filterableColumns: {
[`${first}.name`]: [FilterOperator.EQ],
[`${second}.${nested}.label`]: [FilterOperator.EQ],
},
searchableColumns: [`${first}.name`, `${second}.name`],
}

const result = await paginate<LongAliasOwnerEntity>(
{
path: '',
sortBy: [[`${second}.${nested}.label`, 'DESC']],
filter: { [`${first}.name`]: '$eq:one', [`${second}.${nested}.label`]: '$eq:B' },
search: 'o',
},
ownerRepo,
config
)

expect(result.data.map((owner) => owner.name)).toStrictEqual(['alpha'])
const [alpha] = result.data
expect(alpha[first].name).toBe('one')
expect(alpha[first][nested].label).toBe('A')
expect(alpha[second].name).toBe('two')
expect(alpha[second][nested].label).toBe('B')
})

it('filters through to-many and nested relations without loading them', async () => {
const result = await paginate<LongAliasOwnerEntity>(
{
path: '',
filter: {
[`${toMany}.name`]: '$eq:child of beta',
[`${first}.${nested}.label`]: '$eq:B',
},
},
ownerRepo,
{
sortableColumns: ['id'],
filterableColumns: {
[`${toMany}.name`]: [FilterOperator.EQ],
[`${first}.${nested}.label`]: [FilterOperator.EQ],
},
}
)

expect(result.data.map((owner) => owner.name)).toStrictEqual(['beta'])
})

it('applies a config where on nested relations that are not loaded', async () => {
const result = await paginate<LongAliasOwnerEntity>({ path: '' }, ownerRepo, {
sortableColumns: ['id'],
where: {
[first]: { [nested]: { label: 'A' } },
[second]: { [nested]: { label: 'B' } },
},
})

expect(result.data.map((owner) => owner.name)).toStrictEqual(['alpha'])
})

it('joins the relation parts of a polymorphic (~) filter', async () => {
const column = `${first}.${nested}.label~${second}.${nested}.label`
const result = await paginate<LongAliasOwnerEntity>(
{ path: '', filterExpression: `${column}=$eq:B` } as PaginateQuery,
ownerRepo,
{ sortableColumns: ['id'], filterableColumns: { [column]: true } }
)

expect(result.data.map((owner) => owner.name)).toStrictEqual(['beta'])
})
})
})
20 changes: 15 additions & 5 deletions src/paginate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
createRelationSchema,
extractVirtualProperty,
fixColumnAlias,
getJoinAlias,
getMissingPrimaryKeyColumns,
getPaddedExpr,
getPropertiesByColumnName,
Expand Down Expand Up @@ -193,8 +194,14 @@ function flattenWhereAndTransform<T>(
.map((p) => p + '_rel')
.join('_')}`
const tableName = pathSplit[pathSplit.length - 1]
const tableAliasWithProperty = `${queryBuilder.alias}${fullPath}.${tableName}`
const joinTableAlias = `${queryBuilder.alias}${fullPath}_${tableName}_rel`
const tableAliasWithProperty = `${getJoinAlias(
queryBuilder,
`${queryBuilder.alias}${fullPath}`
)}.${tableName}`
const joinTableAlias = getJoinAlias(
queryBuilder,
`${queryBuilder.alias}${fullPath}_${tableName}_rel`
)

const baseTableAlias = allJoinedTables[joinTableAlias]

Expand Down Expand Up @@ -1173,7 +1180,10 @@ export function addRelationsFromSchema<T>(
Object.keys(relations).forEach((relationName) => {
const joinMethod =
joinMethods[parentRelation ? `${parentRelation}.${relationName}` : relationName] ?? defaultJoinMethod
const joinAlias = `${alias ?? prefix}_${relationName}_rel`
// The path-derived alias is kept for building the aliases of nested relations; the join
// itself uses the (possibly shortened) alias that fixColumnAlias resolves to.
const pathAlias = `${alias ?? prefix}_${relationName}_rel`
const joinAlias = getJoinAlias(queryBuilder, pathAlias)

// A prior step (e.g. a polymorphic `~` filter, which left-joins its relation parts on
// the main query builder before relations are loaded) may have already joined this
Expand All @@ -1188,7 +1198,7 @@ export function addRelationsFromSchema<T>(
queryBuilder.addSelect(joinAlias)
}
} else {
queryBuilder[joinMethod](`${alias ?? prefix}.${relationName}`, joinAlias)
queryBuilder[joinMethod](`${getJoinAlias(queryBuilder, alias ?? prefix)}.${relationName}`, joinAlias)
}

// Check whether this is a non-terminal node with a relation schema to load
Expand All @@ -1201,7 +1211,7 @@ export function addRelationsFromSchema<T>(
createQueryBuilderRelations(
relationName,
relationSchema,
`${alias ?? prefix}_${relationName}_rel`,
pathAlias,
parentRelation ? `${parentRelation}.${relationName}` : relationName
)
}
Expand Down
Loading