fix(db-postgres): build near sort query properly for point fields (#12240)

Continuation of https://github.com/payloadcms/payload/pull/12185 and fix
https://github.com/payloadcms/payload/issues/12221

The mentioned PR introduced auto sorting by the point field when a
`near` query is used, but it didn't build actual needed query to order
results by their distance to a _given_ (from the `near` query) point.

Now, we build:
```sql
order by pont_field <-> ST_SetSRID(ST_MakePoint(lng, lat), 4326)
```

Which does what we want
This commit is contained in:
Sasha
2025-05-15 20:45:33 +03:00
committed by GitHub
parent 5fce501589
commit 58fc2f9a74
3 changed files with 14 additions and 4 deletions

View File

@@ -1,7 +1,7 @@
import type { Table } from 'drizzle-orm'
import type { SQL, Table } from 'drizzle-orm'
import type { FlattenedField, Sort } from 'payload'
import { asc, desc } from 'drizzle-orm'
import { asc, desc, or } from 'drizzle-orm'
import type { DrizzleAdapter, GenericColumn } from '../types.js'
import type { BuildQueryJoinAliases, BuildQueryResult } from './buildQuery.js'
@@ -16,6 +16,7 @@ type Args = {
joins: BuildQueryJoinAliases
locale?: string
parentIsLocalized: boolean
rawSort?: SQL
selectFields: Record<string, GenericColumn>
sort?: Sort
tableName: string
@@ -31,6 +32,7 @@ export const buildOrderBy = ({
joins,
locale,
parentIsLocalized,
rawSort,
selectFields,
sort,
tableName,
@@ -74,12 +76,18 @@ export const buildOrderBy = ({
value: sortProperty,
})
if (sortTable?.[sortTableColumnName]) {
let order = sortDirection === 'asc' ? asc : desc
if (rawSort) {
order = () => rawSort
}
orderBy.push({
column:
aliasTable && tableName === getNameFromDrizzleTable(sortTable)
? aliasTable[sortTableColumnName]
: sortTable[sortTableColumnName],
order: sortDirection === 'asc' ? asc : desc,
order,
})
selectFields[sortTableColumnName] = sortTable[sortTableColumnName]

View File

@@ -79,6 +79,7 @@ const buildQuery = function buildQuery({
joins,
locale,
parentIsLocalized,
rawSort: context.rawSort,
selectFields,
sort: context.sort,
tableName,

View File

@@ -14,7 +14,7 @@ import { buildAndOrConditions } from './buildAndOrConditions.js'
import { getTableColumnFromPath } from './getTableColumnFromPath.js'
import { sanitizeQueryValue } from './sanitizeQueryValue.js'
export type QueryContext = { sort: Sort }
export type QueryContext = { rawSort?: SQL; sort: Sort }
type Args = {
adapter: DrizzleAdapter
@@ -348,6 +348,7 @@ export function parseParams({
}
if (geoConstraints.length) {
context.sort = relationOrPath
context.rawSort = sql`${table[columnName]} <-> ST_SetSRID(ST_MakePoint(${lng}, ${lat}), 4326)`
constraints.push(and(...geoConstraints))
}
break