Skip to content

Commit

Permalink
fix(db-postgres): query using blockType (#5044)
Browse files Browse the repository at this point in the history
* fix(db-postgres): query using blockType

* chore: cleanup commented lines
  • Loading branch information
DanRibbens committed Feb 16, 2024
1 parent 1ac943e commit 35c2a08
Show file tree
Hide file tree
Showing 5 changed files with 114 additions and 14 deletions.
1 change: 1 addition & 0 deletions packages/db-postgres/src/queries/buildQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ const buildQuery = async function buildQuery({
pathSegments: sortPath.replace(/__/g, '.').split('.'),
selectFields,
tableName,
value: sortPath,
})
orderBy.column = sortTable?.[sortTableColumnName]
} catch (err) {
Expand Down
41 changes: 38 additions & 3 deletions packages/db-postgres/src/queries/getTableColumnFromPath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ type Args = {
* If creating a new table name for arrays and blocks, this suffix should be appended to the table name
*/
tableNameSuffix?: string
/**
* The raw value of the query before sanitization
*/
value: unknown
}
/**
* Transforms path to table and column name
Expand All @@ -70,6 +74,7 @@ export const getTableColumnFromPath = ({
selectFields,
tableName,
tableNameSuffix = '',
value,
}: Args): TableColumn => {
const fieldPath = incomingSegments[0]
let locale = incomingLocale
Expand Down Expand Up @@ -131,6 +136,7 @@ export const getTableColumnFromPath = ({
selectFields,
tableName: newTableName,
tableNameSuffix,
value,
})
}
case 'tab': {
Expand All @@ -151,6 +157,7 @@ export const getTableColumnFromPath = ({
selectFields,
tableName: newTableName,
tableNameSuffix: `${tableNameSuffix}${toSnakeCase(field.name)}_`,
value,
})
}
return getTableColumnFromPath({
Expand All @@ -169,6 +176,7 @@ export const getTableColumnFromPath = ({
selectFields,
tableName: newTableName,
tableNameSuffix,
value,
})
}

Expand Down Expand Up @@ -204,6 +212,7 @@ export const getTableColumnFromPath = ({
selectFields,
tableName: newTableName,
tableNameSuffix: `${tableNameSuffix}${toSnakeCase(field.name)}_`,
value,
})
}

Expand Down Expand Up @@ -241,12 +250,39 @@ export const getTableColumnFromPath = ({
rootTableName,
selectFields,
tableName: newTableName,
value,
})
}

case 'blocks': {
let blockTableColumn: TableColumn
let newTableName: string

// handle blockType queries
if (pathSegments[1] === 'blockType') {
// find the block config using the value
const blockTypes = Array.isArray(value) ? value : [value]
blockTypes.forEach((blockType) => {
const block = field.blocks.find((block) => block.slug === blockType)
newTableName = `${tableName}_blocks_${toSnakeCase(block.slug)}`
joins[newTableName] = eq(
adapter.tables[tableName].id,
adapter.tables[newTableName]._parentID,
)
constraints.push({
columnName: '_path',
table: adapter.tables[newTableName],
value: pathSegments[0],
})
})
return {
constraints,
field,
getNotNullColumnByValue: () => 'id',
table: adapter.tables[tableName],
}
}

const hasBlockField = field.blocks.some((block) => {
newTableName = `${tableName}_blocks_${toSnakeCase(block.slug)}`
constraintPath = `${constraintPath}${field.name}.%.`
Expand All @@ -267,6 +303,7 @@ export const getTableColumnFromPath = ({
rootTableName,
selectFields: blockSelectFields,
tableName: newTableName,
value,
})
} catch (error) {
// this is fine, not every block will have the field
Expand Down Expand Up @@ -307,9 +344,6 @@ export const getTableColumnFromPath = ({
table: blockTableColumn.table,
}
}
if (pathSegments[1] === 'blockType') {
throw new APIError('Querying on blockType is not supported')
}
break
}

Expand Down Expand Up @@ -397,6 +431,7 @@ export const getTableColumnFromPath = ({
rootTableName: newTableName,
selectFields,
tableName: newTableName,
value,
})
}

Expand Down
10 changes: 3 additions & 7 deletions packages/db-postgres/src/queries/parseParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,7 @@ export async function parseParams({
where: condition,
})
if (builtConditions.length > 0) {
if (result) {
result = operatorMap[conditionOperator](result, ...builtConditions)
} else {
result = operatorMap[conditionOperator](...builtConditions)
}
result = operatorMap[conditionOperator](...builtConditions)
}
} else {
// It's a path - and there can be multiple comparisons on a single path.
Expand All @@ -77,6 +73,7 @@ export async function parseParams({
if (typeof pathOperators === 'object') {
for (const operator of Object.keys(pathOperators)) {
if (validOperators.includes(operator as Operator)) {
const val = where[relationOrPath][operator]
const {
columnName,
constraints: queryConstraints,
Expand All @@ -95,10 +92,9 @@ export async function parseParams({
pathSegments: relationOrPath.replace(/__/g, '.').split('.'),
selectFields,
tableName,
value: val,
})

const val = where[relationOrPath][operator]

queryConstraints.forEach(({ columnName: col, table: constraintTable, value }) => {
if (typeof value === 'string' && value.indexOf('%') > -1) {
constraints.push(operatorMap.like(constraintTable[col], value))
Expand Down
4 changes: 4 additions & 0 deletions test/fields/collections/Blocks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ const BlockFields: CollectionConfig = {
slug: blockFieldsSlug,
fields: [
getBlocksField(),
{
...getBlocksField(),
name: 'duplicate',
},
{
...getBlocksField('localized'),
name: 'collapsedByDefaultBlocks',
Expand Down
72 changes: 68 additions & 4 deletions test/fields/int.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ describe('Fields', () => {
const { id } = await payload.create({
collection: 'text-fields',
data: {
text,
localizedHasMany,
text,
},
locale: 'en',
})
Expand Down Expand Up @@ -977,6 +977,70 @@ describe('Fields', () => {
expect(result.docs).toHaveLength(1)
expect(result.docs[0]).toMatchObject(blockDoc)
})

it('should query by blockType', async () => {
const text = 'blockType query test'

const hit = await payload.create({
collection: blockFieldsSlug,
data: {
blocks: [
{
blockType: 'content',
text,
},
],
},
})
const miss = await payload.create({
collection: blockFieldsSlug,
data: {
blocks: [
{
blockType: 'number',
number: 5,
},
],
duplicate: [
{
blockType: 'content',
text,
},
],
},
})

const { docs: equalsDocs } = await payload.find({
collection: blockFieldsSlug,
where: {
and: [
{
'blocks.blockType': { equals: 'content' },
},
{
'blocks.text': { equals: text },
},
],
},
})

const { docs: inDocs } = await payload.find({
collection: blockFieldsSlug,
where: {
'blocks.blockType': { in: ['content'] },
},
})

const equalsHitResult = equalsDocs.find(({ id }) => id === hit.id)
const inHitResult = inDocs.find(({ id }) => id === hit.id)
const equalsMissResult = equalsDocs.find(({ id }) => id === miss.id)
const inMissResult = inDocs.find(({ id }) => id === miss.id)

expect(equalsHitResult.id).toStrictEqual(hit.id)
expect(inHitResult.id).toStrictEqual(hit.id)
expect(equalsMissResult).toBeUndefined()
expect(inMissResult).toBeUndefined()
})
})

describe('json', () => {
Expand Down Expand Up @@ -1175,8 +1239,8 @@ describe('Fields', () => {
expect(existsFalseResult.docs).toHaveLength(0)

await payload.update({
collection: 'select-fields',
id,
collection: 'select-fields',
data: {
select: null,
},
Expand Down Expand Up @@ -1257,8 +1321,8 @@ describe('Fields', () => {
expect(nodes).toBeDefined()
const child = nodes.flatMap((n) => n.children).find((c) => c.doc)
expect(child).toMatchObject({
linkType: 'internal',
type: 'link',
linkType: 'internal',
})
expect(child.doc.relationTo).toEqual('array-fields')

Expand Down Expand Up @@ -1337,8 +1401,8 @@ describe('Fields', () => {
expect(existsFalseResult.docs).toHaveLength(0)

await payload.update({
collection: 'select-fields',
id,
collection: 'select-fields',
data: {
select: null,
},
Expand Down

0 comments on commit 35c2a08

Please sign in to comment.