Skip to content
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

feat: Add refreshArrayTypes() call to re-sync newly created complex array columns, like enums #500

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions .changeset/spicy-grapes-walk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@electric-sql/pglite': minor
---

Add `refreshArrayTypes()` call to re-sync newly created complex array columns, like enums
6 changes: 6 additions & 0 deletions docs/docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,12 @@ Returns an object with:
- `resultFields: Array<{ name: string, dataTypeID: number, parser: Function }>` <br/>
Information about each result field including its name, Postgres type ID, and the parser function used to convert Postgres values to JavaScript format.

### refreshArrayTypes

`.refreshArrayTypes(): Promise<void>`

Refresh the array types in the database. This is useful when you have added columns that contain array types (ie. array of enums) and need to update the internal array type cache. This is done automatically when the database is started, but can be called manually if needed.

##### Example

```ts
Expand Down
12 changes: 10 additions & 2 deletions packages/pglite/src/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ export abstract class BasePGlite
* each type.
* This should be called at the end of #init() in the implementing class.
*/
async _initArrayTypes() {
if (this.#arrayTypesInitialized) return
async _initArrayTypes({ force = false } = {}) {
if (this.#arrayTypesInitialized && !force) return
this.#arrayTypesInitialized = true

const types = await this.query<{ oid: number; typarray: number }>(`
Expand All @@ -130,6 +130,14 @@ export abstract class BasePGlite
return await this.execProtocol(message, { ...options, syncToFs: false })
}

/**
* Re-syncs the array types from the database
* This is useful if you add a new type to the database and want to use it, otherwise pglite won't recognize it.
*/
async refreshArrayTypes() {
await this._initArrayTypes({ force: true })
}

/**
* Execute a single SQL statement
* This uses the "Extended Query" postgres wire protocol message.
Expand Down
107 changes: 107 additions & 0 deletions packages/pglite/tests/array-types.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { describe, it, expect } from 'vitest'
import { PGlite } from '../dist/index.js'
import { expectToThrowAsync } from './test-utils.js'

describe('array types', () => {
it('throws for array params enum when not calling refreshArrayTypes', async () => {
const db = new PGlite()
await db.query(`
CREATE TYPE mood AS ENUM ('sad', 'happy');
`)

await db.query(`
CREATE TABLE IF NOT EXISTS test (
id SERIAL PRIMARY KEY,
name TEXT,
moods mood[]
);
`)

await expectToThrowAsync(async () => {
await db.query(
`
INSERT INTO test (name, moods) VALUES ($1, $2);
`,
['test2', ['sad', 'happy']],
)
}, 'malformed array literal: "sad,happy"')
})

it('works with new array types after calling refreshArrayTypes', async () => {
const db = new PGlite()
await db.query(`
CREATE TYPE mood AS ENUM ('sad', 'happy');
`)

await db.query(`
CREATE TABLE IF NOT EXISTS test (
id SERIAL PRIMARY KEY,
name TEXT,
moods mood[]
);
`)

await db.refreshArrayTypes()

await db.query(
`
INSERT INTO test (name, moods) VALUES ($1, $2);
`,
['test2', ['sad', 'happy']],
)

const res = await db.query(`
SELECT * FROM test;
`)

expect(res).toEqual({
rows: [
{
id: 1,
name: 'test2',
moods: ['sad', 'happy'],
},
],
fields: [
{
name: 'id',
dataTypeID: 23,
},
{
name: 'name',
dataTypeID: 25,
},
{
name: 'moods',
dataTypeID: 16384,
},
],
affectedRows: 0,
})
})

it('refreshArrayTypes is indempotent', async () => {
function getSize(obj) {
return Object.keys(obj).length
}

const db = new PGlite()
await db.waitReady

const initialSerializersSize = getSize(db.serializers)
const initialParsersSize = getSize(db.parsers)

expect(initialSerializersSize).toBeGreaterThan(0)
expect(initialParsersSize).toBeGreaterThan(0)

await db.refreshArrayTypes()

expect(getSize(db.serializers)).toBe(initialSerializersSize)
expect(getSize(db.parsers)).toBe(initialParsersSize)

await db.refreshArrayTypes()

expect(getSize(db.serializers)).toBe(initialSerializersSize)
expect(getSize(db.parsers)).toBe(initialParsersSize)
})
})