Skip to content

Commit

Permalink
Transform all values to SQLite in input structures.
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin-dp committed Nov 7, 2023
1 parent babd73a commit bd1b8cc
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 19 deletions.
36 changes: 17 additions & 19 deletions clients/typescript/src/client/conversions/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { FieldName, Fields } from '../model/schema'
import { fromSqlite, toSqlite } from './sqlite'
import { InvalidArgumentError } from '../validation/errors/invalidArgumentError'
import { mapObject } from '../util/functions'
import { PgDateType, PgType } from './types'
import { PgType } from './types'

export enum Transformation {
Js2Sqlite,
Expand Down Expand Up @@ -318,25 +318,22 @@ function transformFieldsAllowingFilters(

if (!pgType) throw new InvalidArgumentError(`Unknown field ${field}`)

switch (pgType) {
// Types that require transformations
case PgDateType.PG_DATE:
case PgDateType.PG_TIME:
case PgDateType.PG_TIMESTAMP:
case PgDateType.PG_TIMESTAMPTZ:
case PgDateType.PG_TIMETZ:
if (value instanceof Date) {
// transform it
return toSqlite(value, pgType)
} else {
// it must be an object containing filters
// transform the values that are nested in those filters
return transformFilterObject(field, value, pgType, fields)
}
// other types that don't require transformations
default:
return value
if (isFilterObject(value)) {
// transform the values that are nested in those filters
return transformFilterObject(field, value, pgType, fields)
}

return toSqlite(value, pgType)
}

function isObject(v: any): boolean {
return typeof v === 'object' && !Array.isArray(v) && v !== null
}

function isFilterObject(value: any): boolean {
// if it is an object it can only be a timestamp or a filter object
// because those are the only objects we support in where clauses
return isObject(value) && !(value instanceof Date)
}

/**
Expand Down Expand Up @@ -388,6 +385,7 @@ function transformFilterObject(
})

return {
...o,
...transformedSimpleFilterObj,
...transformedArrayFilterObj,
...transformedNotFilterObj,
Expand Down
15 changes: 15 additions & 0 deletions clients/typescript/test/client/conversions/input.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,21 @@ test.serial('findFirst transforms JS objects to SQLite', async (t) => {
t.deepEqual(res?.timestamp, new Date(date))
})

test.serial('findFirst transforms booleans to integer in SQLite', async (t) => {
await electric.adapter.run({
sql: `INSERT INTO DataTypes('id', 'bool') VALUES (1, 0), (2, 1)`,
})

const res = await tbl.findFirst({
where: {
bool: true,
},
})

t.is(res?.id, 2)
t.is(res?.bool, true)
})

test.serial(
'findFirst transforms JS objects in equals filter to SQLite',
async (t) => {
Expand Down

0 comments on commit bd1b8cc

Please sign in to comment.