### Install kysely-pglite-dialect Source: https://github.com/czeidler/kysely-pglite-dialect/blob/main/README.md Install the necessary packages for using the PGlite dialect with Kysely. This includes the dialect itself, Kysely, and @electric-sql/pglite. ```bash npm i kysely-pglite-dialect kysely @electric-sql/pglite ``` -------------------------------- ### Initialize Kysely with PGliteDialect Source: https://context7.com/czeidler/kysely-pglite-dialect/llms.txt Set up Kysely with the PGliteDialect, providing either a PGlite instance or a PGliteWorker. Define your database schema using TypeScript interfaces for type safety. This example shows both raw SQL and schema builder methods for table creation. ```typescript import { Kysely, Generated, sql } from "kysely" import { PGlite } from "@electric-sql/pglite" import { PGliteDialect } from "kysely-pglite-dialect" // Define your database schema with TypeScript types interface Database { users: { id: Generated name: string email: string created_at: Generated } } // Initialize Kysely with PGliteDialect const db = new Kysely({ dialect: new PGliteDialect(new PGlite()), }) // Create tables using raw SQL await sql` CREATE TABLE users ( id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT NOW() ) `.execute(db) // Or use the schema builder await db.schema .createTable("users") .addColumn("id", "serial", (col) => col.primaryKey()) .addColumn("name", "varchar(255)", (col) => col.notNull()) .addColumn("email", "varchar(255)", (col) => col.unique().notNull()) .addColumn("created_at", "timestamp", (col) => col.defaultTo(sql`NOW()`)) .execute() ``` -------------------------------- ### Initialize Kysely with PGliteDialect Source: https://github.com/czeidler/kysely-pglite-dialect/blob/main/README.md Initialize Kysely by providing an instance of PGliteDialect, which wraps a PGlite database instance. This setup is required before performing any database operations. ```typescript import { Kysely } from "kysely" import { PGlite } from "@electric-sql/pglite" import { PGliteDialect } from "kysely-pglite-dialect" const db = new Kysely<{ pglite_test_table: { id: Generated; data: string } }>({ dialect: new PGliteDialect(new PGlite()), }) ``` -------------------------------- ### Initialize PGliteDialect with PGliteWorker Source: https://context7.com/czeidler/kysely-pglite-dialect/llms.txt Set up Kysely to use PGlite in a Web Worker for improved browser performance by offloading database operations from the main thread. Imports for Kysely, PGliteWorker, and PGliteDialect are required. ```typescript import { Kysely } from "kysely" import { PGliteWorker } from "@electric-sql/pglite/worker" import { PGliteDialect } from "kysely-pglite-dialect" // Initialize with a PGliteWorker instance const worker = new PGliteWorker( new Worker(new URL("./pglite-worker.js", import.meta.url)) ) const db = new Kysely({ dialect: new PGliteDialect(worker), }) // Use exactly like regular PGlite await db.selectFrom("users").selectAll().execute() ``` -------------------------------- ### Execute Basic Transaction Source: https://context7.com/czeidler/kysely-pglite-dialect/llms.txt Perform multiple database operations atomically. If any operation within the transaction fails, all changes are rolled back. ```typescript await db.transaction().execute(async (trx) => { // Insert a user const user = await trx .insertInto("users") .values({ name: "Frank", email: "frank@example.com" }) .returning("id") .executeTakeFirstOrThrow() // Insert related data in the same transaction await trx .insertInto("users") .values({ name: "Grace", email: "grace@example.com" }) .execute() // If any operation fails, all changes are rolled back }) ``` -------------------------------- ### Insert Data into Users Table Source: https://context7.com/czeidler/kysely-pglite-dialect/llms.txt Perform type-safe insert operations using Kysely. Supports inserting single rows, multiple rows in bulk, and returning generated columns like 'id' and 'created_at'. ```typescript // Single insert await db .insertInto("users") .values({ name: "Alice", email: "alice@example.com" }) .execute() ``` ```typescript // Bulk insert multiple rows await db .insertInto("users") .values([ { name: "Bob", email: "bob@example.com" }, { name: "Charlie", email: "charlie@example.com" }, { name: "Diana", email: "diana@example.com" }, ]) .execute() ``` ```typescript // Insert and return the generated id const result = await db .insertInto("users") .values({ name: "Eve", email: "eve@example.com" }) .returning(["id", "created_at"]) .executeTakeFirst() console.log(result) // { id: 5, created_at: 2024-01-15T10:30:00.000Z } ``` -------------------------------- ### Select Data from Users Table Source: https://context7.com/czeidler/kysely-pglite-dialect/llms.txt Execute type-safe select queries to retrieve data. Supports selecting all columns, specific columns with filtering, and complex queries involving ordering and limits. ```typescript // Select all columns from a table const allUsers = await db.selectFrom("users").selectAll().execute() // Returns: [{ id: 1, name: "Alice", email: "alice@example.com", created_at: ... }, ...] ``` ```typescript // Select specific columns with filtering const user = await db .selectFrom("users") .select(["id", "name", "email"]) .where("email", "=", "alice@example.com") .executeTakeFirst() ``` ```typescript // Complex queries with ordering and limits const recentUsers = await db .selectFrom("users") .selectAll() .where("name", "like", "%a%") .orderBy("created_at", "desc") .limit(10) .execute() ``` -------------------------------- ### Execute Transaction with Isolation Level Source: https://context7.com/czeidler/kysely-pglite-dialect/llms.txt Run a transaction with a specified isolation level, such as 'serializable', for advanced concurrency control. ```typescript await db .transaction() .setIsolationLevel("serializable") .execute(async (trx) => { const users = await trx.selectFrom("users").selectAll().execute() // Operations run with serializable isolation }) ``` -------------------------------- ### Update and Delete Records in Users Table Source: https://context7.com/czeidler/kysely-pglite-dialect/llms.txt Perform type-safe update and delete operations. These builders return the number of affected rows. ```typescript // Update records const updateResult = await db .updateTable("users") .set({ name: "Alice Smith" }) .where("id", "=", 1) .executeTakeFirst() console.log(updateResult.numAffectedRows) // 1n (BigInt) ``` ```typescript // Delete records const deleteResult = await db .deleteFrom("users") .where("email", "=", "old@example.com") .executeTakeFirst() console.log(deleteResult.numAffectedRows) // 1n (BigInt) ``` -------------------------------- ### Stream Query Results in Chunks Source: https://context7.com/czeidler/kysely-pglite-dialect/llms.txt Process large result sets efficiently by streaming rows in configurable chunks to avoid memory issues. Useful for handling large datasets without loading everything into memory. ```typescript // Stream results in chunks of 2 rows at a time const results: { id: number; name: string; email: string }[] = [] for await (const row of db .selectFrom("users") .selectAll() .stream(2)) { results.push(row) console.log(`Processing user: ${row.name}`) } ``` ```typescript // Useful for processing large datasets without loading all into memory for await (const user of db .selectFrom("users") .select(["id", "email"]) .stream(100)) { await sendEmail(user.email) } ``` -------------------------------- ### Destroy Database Connection Source: https://context7.com/czeidler/kysely-pglite-dialect/llms.txt Properly close the PGlite database connection when finished to release resources. The dialect automatically calls PGlite's close() method upon destruction. ```typescript // Always destroy when finished to release resources const db = new Kysely({ dialect: new PGliteDialect(new PGlite()), }) try { // Perform database operations await db.selectFrom("users").selectAll().execute() } finally { // Cleanup: closes the PGlite connection await db.destroy() } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.