### Install Schema from String for PostgreSQL (JavaScript) Source: https://context7.com/voxpelli/umzeption/llms.txt A PostgreSQL-specific variant, `pgInstallSchemaFromString`, that directly works with the pg context type. Use this when you know the context is PostgreSQL for optimized schema installation. It also executes SQL within a transaction. ```javascript import { readFile } from 'node:fs/promises'; import { pgInstallSchemaFromString } from 'umzeption'; /** @satisfies {import('umzeption').UmzeptionDependency} */ export const umzeptionConfig = { glob: ['migrations/*.js'], installSchema: async ({ context }) => { if (context.type !== 'pg') { throw new Error(`Expected pg context, got: ${context.type}`); } const createTables = ` CREATE TABLE categories ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, slug VARCHAR(100) UNIQUE ); CREATE TABLE products ( id SERIAL PRIMARY KEY, category_id INTEGER REFERENCES categories(id), name VARCHAR(255) NOT NULL, price DECIMAL(10,2), created_at TIMESTAMP DEFAULT NOW() ); CREATE INDEX idx_products_category ON products(category_id); `; // Executes within a transaction - all or nothing await pgInstallSchemaFromString(context, createTables); }, }; ``` -------------------------------- ### Use installSchemaFromString Helper Source: https://github.com/voxpelli/umzeption/blob/main/README.md This example demonstrates using the `installSchemaFromString` helper function within an Umzeption dependency. It reads SQL schema definitions from a file and applies them using the provided context. ```javascript import { readFile } from 'node:fs/promises'; import { installSchemaFromString } from 'umzeption'; /** @satisfies {import('umzeption').UmzeptionDependency} */ export const umzeptionConfig = { dependencies: ['@yikesable/abc'], glob: ['migrations/*.js'], installSchema: async ({ context }) => { const tables = await readFile(new URL('create-tables.sql', import.meta.url), 'utf8'); return installSchemaFromString(context, tables); }, }; ``` -------------------------------- ### Initialize Umzeption with PostgreSQL Context Source: https://github.com/voxpelli/umzeption/blob/main/README.md This snippet demonstrates how to initialize Umzeption with a PostgreSQL context using the `pg` library. It configures migrations, dependencies, schema installation, and storage, then runs the migrations. ```javascript import pg from 'pg'; import { UmzeptionPgStorage, createUmzeptionPgContext, umzeption, } from 'umzeption'; import { Umzug } from 'umzug'; const umzug = new Umzug({ migrations: umzeption({ dependencies: [ '@yikesable/foo', '@yikesable/bar', ], glob: ['migrations/*.js'], async installSchema ({ context: queryInterface }) {}, install: true, meta: import.meta, }), context: createUmzeptionPgContext(new pg.Pool({ allowExitOnIdle: true, connectionString: '...', })), storage: new UmzeptionPgStorage(), logger: console, }); umzug.up(); ``` -------------------------------- ### Install Schema from String (JavaScript) Source: https://context7.com/voxpelli/umzeption/llms.txt Installs database schemas from SQL strings using `installSchemaFromString`. It parses CREATE statements and executes them within a transaction. Supports multiple CREATE statements separated by semicolons. This function is generic and works with any Umzeption context. ```javascript import { readFile } from 'node:fs/promises'; import { installSchemaFromString } from 'umzeption'; /** @satisfies {import('umzeption').UmzeptionDependency} */ export const umzeptionConfig = { dependencies: [], glob: ['migrations/*.js'], installSchema: async ({ context }) => { // Load SQL from a file const sql = await readFile( new URL('./schema.sql', import.meta.url), 'utf8' ); // Execute all CREATE statements in a transaction await installSchemaFromString(context, sql); }, }; // Example schema.sql content: // CREATE TABLE users ( // id SERIAL PRIMARY KEY, // email VARCHAR(255) NOT NULL // ); // // CREATE TABLE posts ( // id SERIAL PRIMARY KEY, // user_id INTEGER REFERENCES users(id), // title VARCHAR(255), // content TEXT // ); // // CREATE INDEX idx_posts_user ON posts(user_id); ``` -------------------------------- ### Define Umzeption Dependency via umzeptionConfig Source: https://github.com/voxpelli/umzeption/blob/main/README.md This example shows how to define an Umzeption dependency using the `umzeptionConfig` property. It specifies dependencies, migration glob patterns, and an asynchronous `installSchema` function for setting up the database schema. ```javascript /** @satisfies {import('umzeption').UmzeptionDependency} */ export const umzeptionConfig = { dependencies: ['@yikesable/abc'], glob: ['migrations/*.js'], async installSchema ({ context }) { if (context.type !== 'pg') { throw new Error(`Unsupported context type: ${context.type}`); } const tables = await getTables(); await context.value.transact(async client => { for (const table of tables) { await client.query(table); } }); }, }; ``` -------------------------------- ### Define Umzeption Dependency via Top-Level Exports Source: https://github.com/voxpelli/umzeption/blob/main/README.md This snippet illustrates defining an Umzeption dependency through top-level exports. It includes `dependencies`, `glob` for migration patterns, and an exported `installSchema` function to handle schema installation logic. ```javascript export const dependencies = ['@yikesable/abc']; export const glob = ['migrations/*.js']; /** @type {import('umzeption').UmzeptionDependency["installSchema"]} */ export async function installSchema ({ context }) { if (context.type !== 'pg') { throw new Error(`Unsupported context type: ${context.type}`); } const tables = await getTables(); await context.value.transact(async client => { for (const table of tables) { await client.query(table); } }); }, ``` -------------------------------- ### Implement Custom MySQL Umzeption Storage (JavaScript) Source: https://context7.com/voxpelli/umzeption/llms.txt Provides an example of creating a custom storage adapter for MySQL by extending `BaseUmzeptionStorage`. This involves overriding the `query` method to adapt SQL placeholders for the MySQL driver. It demonstrates integrating this custom storage with Umzug. ```javascript import { BaseUmzeptionStorage } from 'umzeption'; // Custom MySQL storage implementation class UmzeptionMysqlStorage extends BaseUmzeptionStorage { constructor(pool) { super(); this.pool = pool; } // Override the query method to use your database driver async query(context, query, ...values) { // Convert $1, $2 placeholders to ? for MySQL const mysqlQuery = query.replace(/\$(\d+)/g, '?'); const [rows] = await this.pool.execute(mysqlQuery, values); return { rows }; } } // Usage with custom storage import mysql from 'mysql2/promise'; import { Umzug } from 'umzug'; import { umzeption, createUmzeptionContext } from 'umzeption'; const pool = mysql.createPool({ host: 'localhost', database: 'mydb', user: 'root', }); const context = createUmzeptionContext('unknown', pool); const storage = new UmzeptionMysqlStorage(pool); const umzug = new Umzug({ migrations: umzeption({ glob: ['migrations/*.js'], meta: import.meta, }), context, storage, logger: console, }); await umzug.up(); ``` -------------------------------- ### Create Umzug Migration Resolver with Umzeption Source: https://context7.com/voxpelli/umzeption/llms.txt This snippet demonstrates how to create an Umzug instance configured with the `umzeption` factory function. It handles recursive dependency loading, specifies migration files using glob patterns, defines an `installSchema` function for fresh installations, and configures the context and storage for PostgreSQL. ```javascript import pg from 'pg'; import { Umzug } from 'umzug'; import { umzeption, createUmzeptionPgContext, UmzeptionPgStorage } from 'umzeption'; // Create the Umzug instance with umzeption for recursive migrations const umzug = new Umzug({ migrations: umzeption({ // Specify npm packages or relative paths to load as dependencies dependencies: [ '@myorg/user-schema', '@myorg/product-schema', './local-module' ], // Glob pattern for your own migration files glob: ['migrations/*.js'], // Schema installation function for fresh installs async installSchema({ context }) { if (context.type !== 'pg') { throw new Error(`Unsupported context type: ${context.type}`); } await context.value.query(` CREATE TABLE users ( id SERIAL PRIMARY KEY, email VARCHAR(255) NOT NULL UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) `); }, // Set to true for fresh database installations install: false, // Use import.meta to resolve relative paths meta: import.meta, // Alternative: use cwd instead of meta // cwd: process.cwd(), // Set noop: true to register migrations without executing them // noop: false, }), context: createUmzeptionPgContext(new pg.Pool({ connectionString: 'postgresql://localhost:5432/mydb', allowExitOnIdle: true, })), storage: new UmzeptionPgStorage(), logger: console, }); // Run all pending migrations await umzug.up(); // Or run specific migrations await umzug.up({ to: 'migration-name.js' }); // Rollback migrations await umzug.down(); ``` -------------------------------- ### UmzeptionDependency Interface Definition (JavaScript) Source: https://context7.com/voxpelli/umzeption/llms.txt Defines the `UmzeptionDependency` interface for npm packages or local modules to be loadable by Umzeption. Dependencies can export configuration via `umzeptionConfig` or individual top-level exports. This example shows how to define dependencies, glob patterns, and the `installSchema` function. ```javascript // Option 1: Using umzeptionConfig export (recommended) // file: @myorg/user-schema/index.js /** @satisfies {import('umzeption').UmzeptionDependency} */ export const umzeptionConfig = { // Other umzeption packages this depends on (loaded first) dependencies: ['@myorg/base-schema'], // Glob patterns for migration files relative to this package glob: ['migrations/*.js'], // Function to install the complete schema (used in install mode) async installSchema({ context, name }) { if (context.type !== 'pg') { throw new Error(`Unsupported context: ${context.type}`); } await context.value.transact(async (client) => { await client.query(` CREATE TABLE users ( id SERIAL PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, password_hash VARCHAR(255), created_at TIMESTAMP DEFAULT NOW() ) `); await client.query(` CREATE TABLE user_sessions ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id INTEGER REFERENCES users(id) ON DELETE CASCADE, expires_at TIMESTAMP NOT NULL ) `); }); }, }; // Option 2: Top-level exports // file: @myorg/product-schema/index.js export const dependencies = ['@myorg/user-schema']; export const glob = ['migrations/*.js']; /** @type {import('umzeption').UmzeptionDependency["installSchema"]} */ export async function installSchema({ context }) { if (context.type !== 'pg') { throw new Error(`Unsupported context: ${context.type}`); } await context.value.query(` CREATE TABLE products ( id SERIAL PRIMARY KEY, owner_id INTEGER REFERENCES users(id), name VARCHAR(255) NOT NULL, description TEXT ) `); } ``` -------------------------------- ### Create Generic and PostgreSQL Umzeption Contexts (JavaScript) Source: https://context7.com/voxpelli/umzeption/llms.txt Demonstrates creating generic and PostgreSQL-specific Umzeption contexts. The generic context is useful for testing, while the PostgreSQL context integrates with a pg.Pool for database operations. It also shows how to handle context type checking within migrations. ```javascript import { createUmzeptionContext } from 'umzeption'; // Create a generic unknown context (useful for testing) const testContext = createUmzeptionContext('unknown', { customData: 'test-value', query: async (sql) => console.log('Would execute:', sql), }); // Create a PostgreSQL context manually import pg from 'pg'; const pool = new pg.Pool({ connectionString: 'postgresql://localhost/db' }); const pgContext = createUmzeptionContext('pg', { pool, query: pool.query.bind(pool), connect: pool.connect.bind(pool), transact: async (fn) => { const client = await pool.connect(); try { await client.query('BEGIN'); await fn(client); await client.query('COMMIT'); } catch (err) { await client.query('ROLLBACK'); throw err; } finally { client.release(); } }, }); // Context type checking in migrations async function installSchema({ context }) { switch (context.type) { case 'pg': await context.value.query('CREATE TABLE ...'); break; case 'unknown': console.log('Unknown context - skipping schema install'); break; default: throw new Error(`Unsupported context type: ${context.type}`); } } ``` -------------------------------- ### Implement PostgreSQL Umzeption Storage and Migration Execution (JavaScript) Source: https://context7.com/voxpelli/umzeption/llms.txt Shows how to use `UmzeptionPgStorage` to manage migrations in a PostgreSQL database. It includes setting up Umzug with the PostgreSQL context and storage, and demonstrates checking for executed and pending migrations. The `umzeption_migrations` table is automatically managed. ```javascript import pg from 'pg'; import { Umzug } from 'umzug'; import { umzeption, createUmzeptionPgContext, UmzeptionPgStorage } from 'umzeption'; const pool = new pg.Pool({ connectionString: 'postgresql://localhost:5432/mydb', }); const storage = new UmzeptionPgStorage(); const umzug = new Umzug({ migrations: umzeption({ dependencies: ['@myorg/base-schema'], glob: ['migrations/*.js'], meta: import.meta, }), context: createUmzeptionPgContext(pool), storage, // Uses the umzeption_migrations table logger: console, }); // The storage automatically creates this table if it doesn't exist: // CREATE TABLE IF NOT EXISTS umzeption_migrations ( // name VARCHAR(255) PRIMARY KEY, // created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP // ) // Check executed migrations const executed = await umzug.executed(); console.log('Executed migrations:', executed.map(m => m.name)); // Output: ['dep:install', ':install', 'dep|001-create-table.js', '001-init.js'] // Check pending migrations const pending = await umzug.pending(); console.log('Pending migrations:', pending.map(m => m.name)); ``` -------------------------------- ### Create PostgreSQL Context for Umzeption Source: https://context7.com/voxpelli/umzeption/llms.txt This function creates a PostgreSQL context wrapper compatible with Umzeption, abstracting a `pg.Pool` instance. It provides a standardized interface for database operations, including direct query execution and transaction management, adhering to a Fastify-postgres style. ```javascript import pg from 'pg'; import { createUmzeptionPgContext } from 'umzeption'; // Create a PostgreSQL connection pool const pool = new pg.Pool({ host: 'localhost', port: 5432, database: 'myapp', user: 'postgres', password: 'secret', max: 20, allowExitOnIdle: true, }); // Wrap the pool in an Umzeption context const context = createUmzeptionPgContext(pool); // The context provides: // - context.type: 'pg' - identifies the context type // - context.value.pool: the original pg.Pool // - context.value.query: bound query method // - context.value.connect: bound connect method // - context.value.transact: transaction wrapper function // Using the context in a migration async function up({ context }) { if (context.type === 'pg') { // Direct query await context.value.query('CREATE INDEX idx_users_email ON users(email)'); // Transaction with automatic commit/rollback await context.value.transact(async (client) => { await client.query('INSERT INTO users (email) VALUES ($1)', ['user@example.com']); await client.query('INSERT INTO audit_log (action) VALUES ($1)', ['user_created']); }); } } ``` -------------------------------- ### JavaScript Umzug Migration with Umzeption Context Source: https://context7.com/voxpelli/umzeption/llms.txt This JavaScript code defines the 'up' and 'down' functions for an Umzug migration using the Umzeption context. It includes type checking for the context and performs database operations within a transaction. This migration is specific to PostgreSQL databases. ```javascript // file: migrations/001-add-user-roles.js /** * @param {object} params * @param {import('umzeption').AnyUmzeptionContext} params.context * @param {string} params.name * @param {string} params.path */ export async function up({ context, name }) { if (context.type !== 'pg') { throw new Error(`Migration ${name} requires pg context`); } await context.value.transact(async (client) => { // Add role column await client.query(` ALTER TABLE users ADD COLUMN role VARCHAR(50) DEFAULT 'user' `); // Create roles lookup table await client.query(` CREATE TABLE roles ( name VARCHAR(50) PRIMARY KEY, permissions JSONB DEFAULT '{}' ) `); // Insert default roles await client.query(` INSERT INTO roles (name, permissions) VALUES ('user', '{"read": true}'), ('admin', '{"read": true, "write": true, "delete": true}') `); }); } export async function down({ context, name }) { if (context.type !== 'pg') { throw new Error(`Migration ${name} requires pg context`); } await context.value.transact(async (client) => { await client.query('ALTER TABLE users DROP COLUMN role'); await client.query('DROP TABLE roles'); }); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.