fix(db): let the primary key index serve MikroORM find orders on Postgres

A find ordered by its entity's own primary key now renders the NULL position the btree holds, so ORDER BY id DESC LIMIT n reads the index instead of sorting every matching row. A key is never NULL, so the rows come back in the same order.
This commit is contained in:
Maurice
2026-11-23 17:15:45 +01:00
parent 97da0c5ba6
commit b03597957c
3 changed files with 73 additions and 6 deletions
@@ -1,3 +1,4 @@
import { QueryOrderNumeric } from '@mikro-orm/core';
import { PostgreSqlPlatform } from '@mikro-orm/postgresql';
import {
@@ -35,6 +36,8 @@ import {
* gets no position: every `id` of TREK's schema is a primary key, so no NULL
* sorts there, and a NULL position Postgres's btree does not hold in that
* direction would keep the primary key from serving `ORDER BY id DESC LIMIT n`.
* MikroORM's `find` orders its entity's own primary key the way the btree holds
* it (`asc nulls last`, `desc nulls first`) for the same reason.
*/
/** The NULL position SQLite gives an ORDER BY item of this direction. */
@@ -127,3 +130,26 @@ export class SqliteNullOrderPlatform extends PostgreSqlPlatform {
return super.getOrderByExpression(column, direction, collation).map(withSqliteNullPosition);
}
}
/** Whether a MikroORM order direction is a bare `asc` or `desc`, with no NULL position of its own. */
function plainDirection(direction: unknown): 'asc' | 'desc' | null {
if (direction === QueryOrderNumeric.ASC) return 'asc';
if (direction === QueryOrderNumeric.DESC) return 'desc';
const spelled = typeof direction === 'string' ? direction.trim().toLowerCase() : '';
return spelled === 'asc' || spelled === 'desc' ? spelled : null;
}
/**
* A `find` order with each bare direction on the entity's own primary key in
* the NULL position Postgres's btree holds: a key is never NULL, so the rows
* keep their order and the key's index can serve `ORDER BY id DESC LIMIT n`.
*/
export function withIndexedKeyOrder<O extends object>(primaryKeys: readonly string[], orderBy: O[]): O[] {
if (primaryKeys.length !== 1) return orderBy;
const [key] = primaryKeys;
return orderBy.map((item) => {
const direction = Object.hasOwn(item, key) ? plainDirection((item as Record<string, unknown>)[key]) : null;
if (!direction) return item;
return { ...item, [key]: direction === 'desc' ? 'desc nulls first' : 'asc nulls last' } as O;
});
}
@@ -1,7 +1,14 @@
import { nulFreeJson, stripNul, withNulFreeParameters } from '../../nul-free';
import { SqliteNullOrderPlatform, withSqliteNullOrder } from './null-order';
import { type Configuration, type TransformContext } from '@mikro-orm/core';
import { PostgreSqlConnection, PostgreSqlDriver } from '@mikro-orm/postgresql';
import { SqliteNullOrderPlatform, withIndexedKeyOrder, withSqliteNullOrder } from './null-order';
import {
type Configuration,
type EntityMetadata,
type FindOptions,
type PopulateOptions,
type QueryOrderMap,
type TransformContext,
} from '@mikro-orm/core';
import { type AnyQueryBuilder, PostgreSqlConnection, PostgreSqlDriver } from '@mikro-orm/postgresql';
/** `int8` (bigint), a `pg_type.oid`: every integer column and every `count(*)` on Postgres. */
const INT8_OID = 20;
@@ -95,4 +102,14 @@ export class TrekPostgreSqlDriver extends PostgreSqlDriver {
(this as unknown as { connection: PostgreSqlConnection }).connection = new NumberTypesConnection(config);
(this as unknown as { platform: TrekPostgreSqlPlatform }).platform = new TrekPostgreSqlPlatform();
}
/** `find`'s order, with its entity's primary key in the order its index holds (`null-order.ts`). */
protected override buildOrderBy<T extends object>(
qb: AnyQueryBuilder<T>,
meta: EntityMetadata<T>,
populate: PopulateOptions<T>[],
options: Pick<FindOptions<T>, 'strategy' | 'orderBy' | 'populateOrderBy'>,
): QueryOrderMap<T>[] {
return withIndexedKeyOrder(meta.primaryKeys, super.buildOrderBy(qb, meta, populate, options));
}
}