Skip to content

fix array type inference #533

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/types.js
Original file line number Diff line number Diff line change
@@ -213,14 +213,25 @@ export const escapeIdentifier = function escape(str) {
return '"' + str.replace(/"/g, '""').replace(/\./g, '"."') + '"'
}

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 inferType = function inferType(x) {
return (
x instanceof Parameter ? x.type :
x instanceof Date ? 1184 :
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
)
}
22 changes: 19 additions & 3 deletions tests/index.js
Original file line number Diff line number Diff line change
@@ -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() =>
@@ -138,11 +154,11 @@ t('Array of Date', 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() =>