mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 21:33:19 +00:00
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:
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
* (src/db/engine/postgres/postgres-driver.ts). Nothing here connects.
|
||||
*/
|
||||
import { parseInt8, parseNumeric, TrekPostgreSqlDriver } from '../../../../../src/db/engine/postgres/postgres-driver';
|
||||
import { Configuration } from '@mikro-orm/core';
|
||||
import type { PostgreSqlConnection } from '@mikro-orm/postgresql';
|
||||
import { Configuration, defineEntity, p } from '@mikro-orm/core';
|
||||
import { MikroORM, type PostgreSqlConnection } from '@mikro-orm/postgresql';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
type Parsers = { getTypeParser(oid: number): (text: string) => unknown };
|
||||
|
||||
@@ -44,4 +44,28 @@ describe('postgres driver', () => {
|
||||
expect(types.getTypeParser(1700)('12.5')).toBe(12.5);
|
||||
expect(types.getTypeParser(1114)('2026-01-01 00:00:00')).toBe('2026-01-01 00:00:00');
|
||||
});
|
||||
|
||||
it("PGDRIVER-004: find orders the entity's own key the way its index holds it, every other column as SQLite does", async () => {
|
||||
const Probe = defineEntity({
|
||||
name: 'Probe',
|
||||
tableName: 'probe',
|
||||
properties: { id: p.integer().primary(), plugin_id: p.text(), ts: p.text().nullable() },
|
||||
});
|
||||
const orm = new MikroORM({
|
||||
driver: TrekPostgreSqlDriver,
|
||||
clientUrl: 'postgresql://u@localhost/trek',
|
||||
entities: [Probe],
|
||||
});
|
||||
const execute = vi.spyOn(orm.em.getConnection(), 'execute').mockResolvedValue([]);
|
||||
const em = orm.em.fork();
|
||||
await em.findOne(Probe, { plugin_id: 'x' }, { orderBy: { id: 'desc' } });
|
||||
await em.find(Probe, {}, { orderBy: [{ ts: 'desc' }, { id: 1 }], limit: 5 });
|
||||
await em.find(Probe, {}, { orderBy: { id: 'desc nulls last' } });
|
||||
const orders = execute.mock.calls.map(([query]) => String(query).replace(/^.* order by /, ''));
|
||||
expect(orders).toEqual([
|
||||
'"p0"."id" desc nulls first limit ?',
|
||||
'"p0"."ts" desc nulls last, "p0"."id" asc nulls last limit ?',
|
||||
'"p0"."id" desc nulls last',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user