Skip to content

Commit 6572bf4

Browse files
authored
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.
1 parent da7be35 commit 6572bf4

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

Diff for: packages/drizzle/src/transform/write/traverseFields.ts

+4
Original file line numberDiff line numberDiff line change
@@ -496,6 +496,10 @@ export const traverseFields = ({
496496
formattedValue = sql`ST_GeomFromGeoJSON(${JSON.stringify(value)})`
497497
}
498498

499+
if (field.type === 'text' && value && typeof value !== 'string') {
500+
formattedValue = JSON.stringify(value)
501+
}
502+
499503
if (field.type === 'date') {
500504
if (typeof value === 'number' && !Number.isNaN(value)) {
501505
formattedValue = new Date(value).toISOString()

Diff for: test/database/config.ts

+4
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ export default buildConfigWithDefaults({
4444
type: 'text',
4545
required: true,
4646
},
47+
{
48+
name: 'text',
49+
type: 'text',
50+
},
4751
{
4852
name: 'number',
4953
type: 'number',

Diff for: test/database/int.spec.ts

+13
Original file line numberDiff line numberDiff line change
@@ -1979,6 +1979,19 @@ describe('database', () => {
19791979
})
19801980
})
19811981

1982+
it('should convert numbers to text', async () => {
1983+
const result = await payload.create({
1984+
collection: postsSlug,
1985+
data: {
1986+
title: 'testing',
1987+
// @ts-expect-error hardcoding a number and expecting that it will convert to string
1988+
text: 1,
1989+
},
1990+
})
1991+
1992+
expect(result.text).toStrictEqual('1')
1993+
})
1994+
19821995
it('should not allow to query by a field with `virtual: true`', async () => {
19831996
await expect(
19841997
payload.find({

0 commit comments

Comments
 (0)