fix(db-sqlite): text field converts to floating point number (#12107)

### What?

Converts numbers passed to a text field to avoid the database/drizzle
from converting it incorrectly.

### Why?

If you have a hook that passes a value to another field you can
experience this problem where drizzle converts a number value for a text
field to a floating point number in sqlite for example.

### How?

Adds logic to `transform/write/traverseFields.ts` to cast text field
values to string.
This commit is contained in:
Dan Ribbens
2025-04-14 17:05:08 -04:00
committed by GitHub
parent da7be35a15
commit 6572bf4ae1
3 changed files with 21 additions and 0 deletions

View File

@@ -496,6 +496,10 @@ export const traverseFields = ({
formattedValue = sql`ST_GeomFromGeoJSON(${JSON.stringify(value)})` formattedValue = sql`ST_GeomFromGeoJSON(${JSON.stringify(value)})`
} }
if (field.type === 'text' && value && typeof value !== 'string') {
formattedValue = JSON.stringify(value)
}
if (field.type === 'date') { if (field.type === 'date') {
if (typeof value === 'number' && !Number.isNaN(value)) { if (typeof value === 'number' && !Number.isNaN(value)) {
formattedValue = new Date(value).toISOString() formattedValue = new Date(value).toISOString()

View File

@@ -44,6 +44,10 @@ export default buildConfigWithDefaults({
type: 'text', type: 'text',
required: true, required: true,
}, },
{
name: 'text',
type: 'text',
},
{ {
name: 'number', name: 'number',
type: 'number', type: 'number',

View File

@@ -1979,6 +1979,19 @@ describe('database', () => {
}) })
}) })
it('should convert numbers to text', async () => {
const result = await payload.create({
collection: postsSlug,
data: {
title: 'testing',
// @ts-expect-error hardcoding a number and expecting that it will convert to string
text: 1,
},
})
expect(result.text).toStrictEqual('1')
})
it('should not allow to query by a field with `virtual: true`', async () => { it('should not allow to query by a field with `virtual: true`', async () => {
await expect( await expect(
payload.find({ payload.find({