diff --git a/src/types.js b/src/types.js index 7c7c2b93..78932ccc 100644 --- a/src/types.js +++ b/src/types.js @@ -1,6 +1,17 @@ import { Query } from './query.js' import { Errors } from './errors.js' +const defaultArrayTypes = { + "boolean": 1000, + "number": 1021, + "string": 1009, + "bigint": 1016, +}; + +export const inferArrayType = function inferArrayType(x) { + return defaultArrayTypes[typeof x[0]] || inferType(x[0]); +} + export const types = { string: { to: 25, @@ -224,7 +235,7 @@ export const inferType = function inferType(x) { x instanceof Uint8Array ? 17 : (x === true || x === false) ? 16 : typeof x === 'bigint' ? 20 : - Array.isArray(x) ? inferType(x[0]) : + Array.isArray(x) ? inferArrayType(x) : 0 ) } diff --git a/tests/index.js b/tests/index.js index bf81b036..f3f9f842 100644 --- a/tests/index.js +++ b/tests/index.js @@ -92,6 +92,22 @@ t('Boolean false', async() => [false, (await sql`select ${ false } as x`)[0].x] ) +t('Boolean[] [true, false]', async() => + ["[true,false]", JSON.stringify((await sql`select ${ [true, false] }::bool[] as x`)[0].x)] +) + +t('Number[] [1, 2]', async() => + ["[1,2]", JSON.stringify((await sql`select ${ [1, 2] }::int4[] as x`)[0].x)] +) + +t('String[] ["a", "b"]', async() => + ['["a","b"]', JSON.stringify((await sql`select ${ ["a", "b"] }::text[] as x`)[0].x)] +) + +t('BigInt[] [BigInt(1), BigInt(2)]', async() => + ['[1,2]', JSON.stringify((await sql`select ${ [BigInt(1), BigInt(2)] }::float4[] as x`)[0].x)] +) + t('Boolean true', async() => [true, (await sql`select ${ true } as x`)[0].x] ) @@ -125,7 +141,7 @@ t('String array', async() => ) t('Array of Integer', async() => - ['3', (await sql`select ${ sql.array([1, 2, 3]) } as x`)[0].x[2]] + [3, (await sql`select ${ sql.array([1, 2, 3]) } as x`)[0].x[2]] ) t('Array of String', async() => @@ -143,11 +159,11 @@ t('Array of Box', async() => [ ]) t('Nested array n2', async() => - ['4', (await sql`select ${ sql.array([[1, 2], [3, 4]]) } as x`)[0].x[1][1]] + [4, (await sql`select ${ sql.array([[1, 2], [3, 4]]) } as x`)[0].x[1][1]] ) t('Nested array n3', async() => - ['6', (await sql`select ${ sql.array([[[1, 2]], [[3, 4]], [[5, 6]]]) } as x`)[0].x[2][0][1]] + [6, (await sql`select ${ sql.array([[[1, 2]], [[3, 4]], [[5, 6]]]) } as x`)[0].x[2][0][1]] ) t('Escape in arrays', async() =>