Skip to content

Commit 0892666

Browse files
authored
Update readme (#167)
1 parent 1a6a057 commit 0892666

File tree

4 files changed

+59
-704
lines changed

4 files changed

+59
-704
lines changed

README.md

+2-255
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333

3434
![PGlite](https://raw.githubusercontent.com/electric-sql/pglite/main/screenshot.png)
3535

36-
PGlite is a WASM Postgres build packaged into a TypeScript client library that enables you to run Postgres in the browser, Node.js and Bun, with no need to install any other dependencies. It is only 2.6mb gzipped.
36+
PGlite is a WASM Postgres build packaged into a TypeScript client library that enables you to run Postgres in the browser, Node.js and Bun, with no need to install any other dependencies. It is only 3mb gzipped and has support for many Postgres extensions, including [pgvector](https://github.com/pgvector/pgvector).
3737

3838
```javascript
3939
import { PGlite } from "@electric-sql/pglite";
@@ -47,23 +47,7 @@ It can be used as an ephemeral in-memory database, or with persistence either to
4747

4848
Unlike previous "Postgres in the browser" projects, PGlite does not use a Linux virtual machine - it is simply Postgres in WASM.
4949

50-
It is being developed at [ElectricSQL](http://electric-sql.com) in collaboration with [Neon](http://neon.tech). We will continue to build on this experiment with the aim of creating a fully capable lightweight WASM Postgres with support for extensions such as pgvector.
51-
52-
## Whats new in V0.1
53-
54-
Version 0.1 (up from 0.0.2) includes significant changes to the Postgres build - it's about 1/3 smaller at 2.6mb gzipped, and up to 2-3 times faster. We have also found a way to statically compile Postgres extensions into the build - the first of these is pl/pgsql with more coming soon.
55-
56-
Key changes in this release are:
57-
58-
- Support for [parameterised queries](#querytquery-string-params-any-options-queryoptions-promiseresultst) #39
59-
- An interactive [transaction API](#transactiontcallback-tx-transaction--promiset) #39
60-
- pl/pgsql support #48
61-
- Additional [query options](#queryoptions) #51
62-
- Run PGlite in a [Web Workers](#web-workers) #49
63-
- Fix for running on Windows #54
64-
- Fix for missing `pg_catalog` and `information_schema` tables and view #41
65-
66-
We have also [published some benchmarks](https://github.com/electric-sql/pglite/blob/main/packages/benchmark/README.md) in comparison to a WASM SQLite build, and both native Postgres and SQLite. While PGlite is currently a little slower than WASM SQLite we have plans for further optimisations, including OPFS support and removing some the the Emscripten options that can add overhead.
50+
For full documentation and user guides see [pglite.dev](https://pglite.dev).
6751

6852
## Browser
6953

@@ -116,201 +100,6 @@ or to persist to the filesystem:
116100
const db = new PGlite("./path/to/pgdata");
117101
```
118102

119-
## Deno
120-
121-
To use the in-memory Postgres, create a file `server.ts`:
122-
123-
```typescript
124-
import { PGlite } from "npm:@electric-sql/pglite";
125-
126-
Deno.serve(async (_request: Request) => {
127-
const db = new PGlite();
128-
const query = await db.query("select 'Hello world' as message;");
129-
130-
return new Response(JSON.stringify(query));
131-
});
132-
```
133-
134-
Then run the file with `deno run --allow-net --allow-read server.ts`.
135-
136-
## API Reference
137-
138-
### Main Constructor:
139-
140-
#### `new PGlite(dataDir: string, options: PGliteOptions)`
141-
142-
A new pglite instance is created using the `new PGlite()` constructor.
143-
144-
##### `dataDir`
145-
146-
Path to the directory to store the Postgres database. You can provide a url scheme for various storage backends:
147-
148-
- `file://` or unprefixed: File system storage, available in Node and Bun.
149-
- `idb://`: IndexedDB storage, available in the browser.
150-
- `memory://`: In-memory ephemeral storage, available in all platforms.
151-
152-
##### `options`:
153-
154-
- `debug`: 1-5 - the Postgres debug level. Logs are sent to the console.
155-
- `relaxedDurability`: boolean - under relaxed durability mode PGlite will not wait for flushes to storage to complete when using the indexedDB file system.
156-
157-
### Methods:
158-
159-
#### `.query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>`
160-
161-
Execute a single statement, optionally with parameters.
162-
163-
Uses the *extended query* Postgres wire protocol.
164-
165-
Returns single [result object](#results-objects).
166-
167-
##### Example:
168-
169-
```ts
170-
await pg.query(
171-
'INSERT INTO test (name) VALUES ($1);',
172-
[ 'test' ]
173-
);
174-
// { affectedRows: 1 },
175-
```
176-
177-
##### QueryOptions:
178-
179-
The `query` and `exec` methods take an optional `options` objects with the following parameters:
180-
181-
- `rowMode: "object" | "array"`
182-
The returned row object type, either an object of `fieldName: value` mappings or an array of positional values. Defaults to `"object"`.
183-
- `parsers: ParserOptions`
184-
An object of type `{[[pgType: number]: (value: string) => any;]}` mapping Postgres data type id to parser function.
185-
For convenance the `pglite` package exports a const for most common Postgres types:
186-
187-
```ts
188-
import { types } from "@electric-sql/pglite";
189-
await pg.query(`
190-
SELECT * FROM test WHERE name = $1;
191-
`, ["test"], {
192-
rowMode: "array",
193-
parsers: {
194-
[types.TEXT]: (value) => value.toUpperCase(),
195-
}
196-
});
197-
```
198-
199-
#### `.exec(query: string, options?: QueryOptions): Promise<Array<Results>>`
200-
201-
Execute one or more statements. *(note that parameters are not supported)*
202-
203-
This is useful for applying database migrations, or running multi-statement sql that doesn't use parameters.
204-
205-
Uses the *simple query* Postgres wire protocol.
206-
207-
Returns array of [result objects](#results-objects), one for each statement.
208-
209-
##### Example:
210-
211-
```ts
212-
await pg.exec(`
213-
CREATE TABLE IF NOT EXISTS test (
214-
id SERIAL PRIMARY KEY,
215-
name TEXT
216-
);
217-
INSERT INTO test (name) VALUES ('test');
218-
SELECT * FROM test;
219-
`);
220-
// [
221-
// { affectedRows: 0 },
222-
// { affectedRows: 1 },
223-
// {
224-
// rows: [
225-
// { id: 1, name: 'test' }
226-
// ]
227-
// affectedRows: 0,
228-
// fields: [
229-
// { name: 'id', dataTypeID: '23' },
230-
// { name: 'name', dataTypeID: '25' },
231-
// ]
232-
// }
233-
// ]
234-
```
235-
236-
#### `.transaction<T>(callback: (tx: Transaction) => Promise<T>)`
237-
238-
To start an interactive transaction pass a callback to the transaction method. It is passed a `Transaction` object which can be used to perform operations within the transaction.
239-
240-
##### `Transaction` objects:
241-
242-
- `tx.query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>`
243-
The same as the main [`.query` method](#querytquery-string-params-any-promiseresultst).
244-
- `tx.exec(query: string, options?: QueryOptions): Promise<Array<Results>>`
245-
The same as the main [`.exec` method](#execquery-string-promisearrayresults).
246-
- `tx.rollback()`
247-
Rollback and close the current transaction.
248-
249-
##### Example:
250-
251-
```ts
252-
await pg.transaction(async (tx) => {
253-
await tx.query(
254-
'INSERT INTO test (name) VALUES ('$1');',
255-
[ 'test' ]
256-
);
257-
return await ts.query('SELECT * FROM test;');
258-
});
259-
```
260-
261-
#### `.close(): Promise<void>`
262-
263-
Close the database, ensuring it is shut down cleanly.
264-
265-
### Properties:
266-
267-
- `.ready` *boolean (read only)*: Whether the database is ready to accept queries.
268-
- `.closed` *boolean (read only)*: Whether the database is closed and no longer accepting queries.
269-
- `.waitReady` *Promise<void>*: Promise that resolves when the database is ready to use. Note that queries will wait for this if called before the database has fully initialised, and so it's not necessary to wait for it explicitly.
270-
271-
### Results<T> Objects:
272-
273-
Result objects have the following properties:
274-
275-
- `rows: Row<T>[]` - The rows retuned by the query
276-
- `affectedRows?: number` - Count of the rows affected by the query. Note this is *not* the count of rows returned, it is the number or rows in the database changed by the query.
277-
- `fields: { name: string; dataTypeID: number }[]` - Field name and Postgres data type ID for each field returned.
278-
279-
280-
### Row<T> Objects:
281-
282-
Rows objects are a key / value mapping for each row returned by the query.
283-
284-
The `.query<T>()` method can take a TypeScript type describing the expected shape of the returned rows. *(Note: this is not validated at run time, the result only cast to the provided type)*
285-
286-
### Web Workers:
287-
288-
It's likely that you will want to run PGlite in a Web Worker so that it doesn't block the main thread. To aid in this we provide a `PGliteWorker` with the same API as the core `PGlite` but it runs Postgres in a dedicated Web Worker. To use, import from the `/worker` export:
289-
290-
```js
291-
import { PGliteWorker } from "@electric-sql/pglite/worker";
292-
293-
const pg = new PGliteWorker('idb://my-database');
294-
await pg.exec(`
295-
CREATE TABLE IF NOT EXISTS test (
296-
id SERIAL PRIMARY KEY,
297-
name TEXT
298-
);
299-
`);
300-
```
301-
302-
*Work in progress: We plan to expand this API to allow sharing of the worker PGlite across browser tabs.*
303-
304-
## Extensions
305-
306-
PGlite supports the pl/pgsql procedural language extension, this is included and enabled by default.
307-
308-
In future we plan to support additional extensions, see the [roadmap](#roadmap).
309-
310-
## ORM support.
311-
312-
- Drizzle ORM supports PGlite, see [their docs here](https://orm.drizzle.team/docs/get-started-postgresql#pglite).
313-
314103
## How it works
315104

316105
PostgreSQL typically operates using a process forking model; whenever a client initiates a connection, a new process is forked to manage that connection. However, programs compiled with Emscripten - a C to WebAssembly (WASM) compiler - cannot fork new processes, and operates strictly in a single-process mode. As a result, PostgreSQL cannot be directly compiled to WASM for conventional operation.
@@ -321,48 +110,6 @@ Fortunately, PostgreSQL includes a "single user mode" primarily intended for com
321110

322111
- PGlite is single user/connection.
323112

324-
## Roadmap
325-
326-
PGlite is *Alpha* and under active development, the current roadmap is:
327-
328-
- CI builds [#19](https://github.com/electric-sql/pglite/issues/19)
329-
- Support Postgres extensions, starting with:
330-
- pgvector [#18](https://github.com/electric-sql/pglite/issues/18)
331-
- PostGIS [#11](https://github.com/electric-sql/pglite/issues/11)
332-
- OPFS support in browser [#9](https://github.com/electric-sql/pglite/issues/9)
333-
- Muti-tab support in browser [#32](https://github.com/electric-sql/pglite/issues/32)
334-
- Syncing via [ElectricSQL](https://electric-sql.com) with a Postgres server [electric/#1058](https://github.com/electric-sql/electric/pull/1058)
335-
336-
## Repository Structure
337-
338-
The PGlite project is split into two parts:
339-
340-
- `/packages/pglite`
341-
The TypeScript package for PGlite
342-
- `/postgres` _(git submodule)_
343-
A fork of Postgres with changes to enable compiling to WASM:
344-
[/electric-sql/postgres-wasm](https://github.com/electric-sql/postgres-wasm)
345-
346-
Please use the [issues](https://github.com/electric-sql/pglite/issues/) in this main repository for filing issues related to either part of PGlite. Changes that affect both the TypeScript package and the Postgres source should be filed as two pull requests - one for each repository, and they should reference each other.
347-
348-
## Building
349-
350-
There are a couple of prerequisites:
351-
352-
- the Postgres build toolchain - https://www.postgresql.org/download/
353-
- emscripten version 3.1.56 - https://emscripten.org/docs/getting_started/downloads.html
354-
355-
To build, checkout the repo, then:
356-
357-
```
358-
git submodule update --init
359-
cd ./pglite/packages/pglite
360-
emsdk install 3.1.56
361-
emsdk activate 3.1.56
362-
pnpm install
363-
pnpm build
364-
```
365-
366113
## Acknowledgments
367114

368115
PGlite builds on the work of [Stas Kelvich](https://github.com/kelvich) of [Neon](https://neon.tech) in this [Postgres fork](https://github.com/electric-sql/postgres-wasm).

packages/pglite-react/README.md

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# PGlite React.js Hooks
2+
3+
This package implements React hooks for [PGLite](https://pglite.dev/) on top of the [live query plugin](https://pglite.dev/docs/live-queries). Full documentation is available at [pglite.dev/docs/framework-hooks](https://pglite.dev/docs/framework-hooks#react).
4+
5+
To install:
6+
7+
```sh
8+
npm install @electric-sql/pglite-react
9+
```
10+
11+
The hooks this package provides are:
12+
13+
- [PGliteProvider](https://pglite.dev/docs/framework-hooks#pgliteprovider): A Provider component to pass a PGlite instance to all child components for use with the other hooks.
14+
- [usePGlite](https://pglite.dev/docs/framework-hooks#usepglite): Retrieve the provided PGlite instance.
15+
- [useLiveQuery](https://pglite.dev/docs/framework-hooks#uselivequery): Reactively re-render your component whenever the results of a live query change
16+
- [useLiveIncrementalQuery](https://pglite.dev/docs/framework-hooks#useliveincrementalquery): Reactively re-render your component whenever the results of a live query change by offloading the diff to PGlite

packages/pglite-sync/README.md

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# PGlite ElectricSQL Sync Plugin
2+
3+
A [sync plugin](https://pglite.dev/docs/sync) for [PGlite](https://pglite.dev/) using [ElectricSQL](https://electric-sql.com/). Full documentation is available at [pglite.dev/docs/sync](https://pglite.dev/docs/sync).
4+
5+
To install:
6+
7+
```sh
8+
npm install @electric-sql/pglite-sync
9+
```
10+
11+
Then add it to you PGlite instance and create any local tables needed:
12+
13+
```ts
14+
import { electricSync } from '@electric-sql/pglite-sync'
15+
16+
const pg = await PGlite.create({
17+
extensions: {
18+
electric: electricSync(),
19+
},
20+
})
21+
22+
await pg.exec(`
23+
CREATE TABLE IF NOT EXISTS todo (
24+
id SERIAL PRIMARY KEY,
25+
task TEXT,
26+
done BOOLEAN
27+
);
28+
`)
29+
```
30+
31+
You can then use the syncShapeToTable method to sync a table from Electric:
32+
33+
```ts
34+
const shape = await pg.electric.syncShapeToTable({
35+
url: 'http://localhost:3000/v1/shape/todo',
36+
table: 'todo',
37+
primaryKey: ['id'],
38+
})
39+
```

0 commit comments

Comments
 (0)