### Starting MongoDB with Docker for Testing Source: https://github.com/u007/drismify/blob/main/tests/009-mongodb-adapter/setup-mongodb.md This command initiates a MongoDB container using Docker, mapping port 27017 and configuring a root user with a specified password for authentication. It includes a delay to ensure the database starts and a verification step to ping the admin database. ```bash docker run -d \ --name drismify-mongodb-test \ -p 27017:27017 \ -e MONGO_INITDB_ROOT_USERNAME=root \ -e MONGO_INITDB_ROOT_PASSWORD=000000 \ mongo:latest # Wait for MongoDB to start (about 10-15 seconds) sleep 15 # Verify connection docker exec drismify-mongodb-test mongosh --username root --password 000000 --authenticationDatabase admin --eval "db.adminCommand('ping')" ``` -------------------------------- ### Installing MongoDB Community on Ubuntu/Debian Source: https://github.com/u007/drismify/blob/main/tests/009-mongodb-adapter/setup-mongodb.md These commands install the MongoDB Community Edition on Ubuntu/Debian systems. The process includes adding the MongoDB GPG key, configuring the APT repository for MongoDB 7.0, updating the package list, and finally installing the `mongodb-org` package. ```bash wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add - echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list sudo apt-get update sudo apt-get install -y mongodb-org ``` -------------------------------- ### Installing MongoDB Community on macOS with Homebrew Source: https://github.com/u007/drismify/blob/main/tests/009-mongodb-adapter/setup-mongodb.md These commands facilitate the installation of MongoDB Community Edition on macOS using Homebrew. The process involves tapping the official MongoDB Homebrew repository and then installing the `mongodb-community` package. ```bash brew tap mongodb/brew brew install mongodb-community ``` -------------------------------- ### Starting MongoDB Without Authentication and Connecting Shell Source: https://github.com/u007/drismify/blob/main/tests/009-mongodb-adapter/setup-mongodb.md This snippet demonstrates how to start a MongoDB instance without authentication, specifying a custom data directory. In a separate terminal, `mongosh` is used to connect to this running instance, typically for initial setup tasks such as user creation. ```bash mongod --dbpath /path/to/your/data/directory # In another terminal, connect and create user mongosh ``` -------------------------------- ### Building Drismify from Source - Bash Source: https://github.com/u007/drismify/blob/main/README.md This snippet provides the necessary bash commands to clone the Drismify repository, install its dependencies using pnpm, build the project, and test the command-line interface. It outlines the standard development setup process for contributors. ```bash # Clone the repository git clone https://github.com/u007/drismify.git cd drismify # Install dependencies pnpm install # Build the project pnpm run build # Test the CLI node dist/cli.js --help ``` -------------------------------- ### Quick Start: Drismify 30-Second Demo Source: https://github.com/u007/drismify/blob/main/README.md This comprehensive snippet provides a quick demonstration of Drismify's core functionality. It covers global installation, creating a sample Prisma schema, validating it, converting it to a Drizzle schema, and viewing the generated output. ```bash npm install -g drismify # Create a sample schema file echo 'generator client { provider = "drismify" } datasource db { provider = "sqlite" url = "file:./dev.db" } model User { id Int @id @default(autoincrement()) email String @unique name String? }' > sample-schema.prisma # Validate the schema drismify validate sample-schema.prisma # Convert to Drizzle schema drismify generate-schema sample-schema.prisma drizzle-output.ts # View the generated Drizzle schema cat drizzle-output.ts ``` -------------------------------- ### Installing JSR CLI (Bash) Source: https://github.com/u007/drismify/blob/main/PUBLISHING.md This command globally installs the JSR (JavaScript Registry) command-line interface, which is required to interact with the JSR registry. ```bash npm install -g @jsr/cli ``` -------------------------------- ### Starting MongoDB with Authentication Enabled Source: https://github.com/u007/drismify/blob/main/tests/009-mongodb-adapter/setup-mongodb.md This command restarts the MongoDB instance, enabling authentication. It requires a previously created user (such as the root user) to connect and perform operations, significantly enhancing database security. ```bash # Stop the previous instance and restart with auth mongod --dbpath /path/to/your/data/directory --auth ``` -------------------------------- ### Running Drismify MongoDB Adapter Tests with Bun Source: https://github.com/u007/drismify/blob/main/tests/009-mongodb-adapter/setup-mongodb.md This command executes the Drismify MongoDB adapter tests using the Bun runtime. It targets a specific test file located within the `tests/009-mongodb-adapter/` directory from the project's root. ```bash bun test tests/009-mongodb-adapter/mongodb-adapter.test.ts ``` -------------------------------- ### Example Prisma Schema for Drismify Source: https://github.com/u007/drismify/blob/main/README.md This snippet provides a sample `schema.prisma` file demonstrating a typical setup for Drismify. It defines `generator` and `datasource` blocks, including an example for SQLite and a commented-out one for MongoDB, along with `User` and `Post` models with relations. ```prisma // This is your Prisma schema file, // learn more about it in the docs: https://pris.ly/d/prisma-schema generator client { provider = "drismify" } datasource db { provider = "sqlite" url = "file:./dev.db" } // For MongoDB: // datasource db { // provider = "mongodb" // url = "mongodb://localhost:27017/mydb" // } model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[] } model Post { id Int @id @default(autoincrement()) title String content String? published Boolean @default(false) author User @relation(fields: [authorId], references: [id]) authorId Int } ``` -------------------------------- ### Executing Drismify Commands with npx Source: https://github.com/u007/drismify/blob/main/README.md This snippet demonstrates how to use Drismify commands without a global installation by leveraging `npx`. It shows examples for validating a Prisma schema, generating a TypeScript schema, and accessing the help documentation. ```bash npx drismify validate schema.prisma npx drismify generate-schema schema.prisma output.ts npx drismify --help ``` -------------------------------- ### Installing Drismify CLI Globally Source: https://github.com/u007/drismify/blob/main/README.md This snippet demonstrates how to install the Drismify CLI globally using npm, pnpm, or bun. A global installation is recommended for project management and allows access to Drismify commands from any directory. ```bash npm install -g drismify # or pnpm add -g drismify # or bun add -g drismify ``` -------------------------------- ### Logging In to NPM (Bash) Source: https://github.com/u007/drismify/blob/main/PUBLISHING.md This command logs the user into the NPM registry, prompting for credentials. It is a prerequisite for publishing packages to NPM. ```bash npm login ``` -------------------------------- ### Automated Publishing Workflow (YAML) Source: https://github.com/u007/drismify/blob/main/PUBLISHING.md This GitHub Actions workflow automates the publishing process to both NPM and JSR upon a new GitHub release. It checks out the code, sets up Node.js, installs dependencies, builds, tests, and then publishes using respective tokens. ```yaml name: Publish Package on: release: types: [published] jobs: publish-npm: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '18' registry-url: 'https://registry.npmjs.org' - run: npm ci - run: npm run build - run: npm test - run: npm publish env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} publish-jsr: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '18' - run: npm ci - run: npm run build - run: npx jsr publish env: JSR_TOKEN: ${{ secrets.JSR_TOKEN }} ``` -------------------------------- ### Installing Drismify via JSR (Deno/Modern Runtimes) Source: https://github.com/u007/drismify/blob/main/README.md This snippet provides commands to install Drismify from the JSR registry, suitable for Deno and other modern JavaScript runtimes. It uses `deno add` or `npx jsr add` to fetch the `@drismify/core` package. ```bash deno add @drismify/core # or npx jsr add @drismify/core ``` -------------------------------- ### Stopping and Removing Docker MongoDB Container Source: https://github.com/u007/drismify/blob/main/tests/009-mongodb-adapter/setup-mongodb.md These commands are used to stop and then remove the `drismify-mongodb-test` Docker container. This is crucial for cleaning up resources after testing or when reconfiguring the environment. ```bash docker stop drismify-mongodb-test docker rm drismify-mongodb-test ``` -------------------------------- ### Installing Drismify as a Project Library Source: https://github.com/u007/drismify/blob/main/README.md This snippet shows how to install Drismify as a local project dependency using npm, pnpm, or bun. This method integrates Drismify into your project's `node_modules` for direct use within your application code. ```bash npm install drismify # or pnpm add drismify # or bun add drismify ``` -------------------------------- ### Launching Drismify Studio with CLI Source: https://github.com/u007/drismify/blob/main/docs/advanced-features.md This snippet shows how to launch Drismify Studio, a web-based database management interface, using `npx drismify studio`. Examples include launching with default settings, specifying a schema path, and customizing the port. Options for `no-browser` and `read-only` modes are also available. ```bash npx drismify studio [schema-path] # Examples: npx drismify studio npx drismify studio ./schema.prisma npx drismify studio ./schema.prisma --port 3000 ``` -------------------------------- ### Logging In to JSR (Bash) Source: https://github.com/u007/drismify/blob/main/PUBLISHING.md This command logs the user into the JSR registry, typically opening a browser for authentication. It is a prerequisite for publishing packages to JSR. ```bash jsr login ``` -------------------------------- ### Creating Root User in MongoDB Shell Source: https://github.com/u007/drismify/blob/main/tests/009-mongodb-adapter/setup-mongodb.md This MongoDB shell script creates a root user with a specified username, password, and roles within the `admin` database. This user is essential for enabling authentication and securing the MongoDB instance. ```javascript use admin db.createUser({ user: "root", pwd: "000000", roles: ["root"] }) exit ``` -------------------------------- ### Verifying NPM Publication (Bash) Source: https://github.com/u007/drismify/blob/main/PUBLISHING.md This command retrieves and displays information about the 'drismify' package from the NPM registry, allowing verification of a successful publication. ```bash npm view drismify ``` -------------------------------- ### Default MongoDB Configuration in TypeScript Source: https://github.com/u007/drismify/blob/main/tests/009-mongodb-adapter/setup-mongodb.md This TypeScript snippet defines the default configuration for connecting to MongoDB within the Drismify project. It specifies the connection URL, database name, user credentials, authentication source, port, and host for the test environment. ```typescript // src/config/mongodb.config.ts export const DEFAULT_MONGODB_CONFIG: MongoDBConfig = { url: 'mongodb://root:000000@localhost:37017', database: 'drismify_test', user: 'root', password: '000000', authSource: 'admin', port: 37017, host: 'localhost' }; ``` -------------------------------- ### Drismify CLI: Schema Validation and Conversion Examples (Bash) Source: https://github.com/u007/drismify/blob/main/README.md This snippet provides practical examples of using Drismify CLI commands for schema validation and conversion. It shows how to validate a Prisma schema file, perform a detailed validation with verbose output, suggestions, and linting, and convert a Prisma schema to a Drizzle schema, specifying input and output paths. ```bash # Validate a Prisma schema file drismify validate ./prisma/schema.prisma # Validate with detailed output and suggestions drismify validate ./prisma/schema.prisma --verbose --suggestions --lint # Convert Prisma schema to Drizzle drismify generate-schema ./prisma/schema.prisma ./src/db/schema.ts ``` -------------------------------- ### Publishing to NPM (Bash) Source: https://github.com/u007/drismify/blob/main/PUBLISHING.md These commands publish the current package to the NPM registry. Different tags (--tag beta, --tag alpha) can be used to publish pre-release versions, while npm publish publishes a stable release. ```bash # For stable releases npm publish # For beta releases npm publish --tag beta # For alpha releases npm publish --tag alpha ``` -------------------------------- ### Verifying JSR Publication (Bash) Source: https://github.com/u007/drismify/blob/main/PUBLISHING.md This command retrieves and displays information about the '@drismify/core' package from the JSR registry, allowing verification of a successful publication. ```bash jsr info @drismify/core ``` -------------------------------- ### Troubleshooting NPM Publish (Bash) Source: https://github.com/u007/drismify/blob/main/PUBLISHING.md These commands help diagnose NPM publishing issues. npm pack --dry-run shows which files would be included in the package, and tar -tzf inspects the contents of a generated .tgz archive. ```bash # Check what files will be published npm pack --dry-run # Check package contents tar -tzf drismify-*.tgz ``` -------------------------------- ### Publishing to JSR (Bash) Source: https://github.com/u007/drismify/blob/main/PUBLISHING.md This command publishes the current package to the JSR registry. It automatically handles versioning and package integrity checks. ```bash jsr publish ``` -------------------------------- ### Seeding Database with Drismify CLI Source: https://github.com/u007/drismify/blob/main/docs/advanced-features.md This command demonstrates how to seed a database with test data using `npx drismify seed`. It provides examples for basic seeding, specifying a schema and seed script, and using the `--reset` option to clear the database before seeding. Options for factory mode and record count are also mentioned. ```bash npx drismify seed [schema-path] [seed-script] # Examples: npx drismify seed npx drismify seed ./schema.prisma ./seed.ts npx drismify seed ./schema.prisma --reset ``` -------------------------------- ### Troubleshooting JSR Publish (Bash) Source: https://github.com/u007/drismify/blob/main/PUBLISHING.md These commands assist in debugging JSR publishing problems. jsr validate checks the JSR configuration, and jsr pack --dry-run shows which files would be included in the JSR package. ```bash # Validate JSR configuration jsr validate # Check JSR package contents jsr pack --dry-run ``` -------------------------------- ### Introspecting Database Schema with Drismify CLI Source: https://github.com/u007/drismify/blob/main/docs/advanced-features.md This snippet shows how to use the `npx drismify introspect` command to generate a Prisma schema from an existing database. It includes examples for SQLite and Turso databases, demonstrating how to specify the database URL, provider, and output path for the generated schema file. ```bash npx drismify introspect [provider] [output-path] # Examples: npx drismify introspect ./dev.db sqlite ./schema.prisma npx drismify introspect https://my-db.turso.io turso ./schema.prisma ``` -------------------------------- ### Implementing Advanced Drismify Extensions (TypeScript) Source: https://github.com/u007/drismify/blob/main/README.md This example showcases the use of advanced Drismify extensions for transactions and soft deletion. It demonstrates how to apply `createTransactionExtension` and `createSoftDeleteExtension` to the Prisma client, enabling atomic operations and logical deletion of records, along with methods to find and restore soft-deleted entries. ```typescript import { createTransactionExtension, createMiddlewareExtension, createSoftDeleteExtension } from 'drismify'; // Add transaction support const prisma = new PrismaClient().$extends(createTransactionExtension()); // Use transactions const result = await prisma.$transaction(async (tx) => { const user = await tx.user.create({ data: { name: 'Alice' } }); return user; }); // Add soft delete functionality const softDeleteClient = prisma.$extends(createSoftDeleteExtension()); // Soft delete a record (won't appear in normal queries) await softDeleteClient.user.softDelete({ where: { id: 1 } }); // Find only soft-deleted records const deletedUsers = await softDeleteClient.user.findDeleted(); // Restore a soft-deleted record await softDeleteClient.user.restore({ where: { id: 1 } }); ``` -------------------------------- ### Updating Package Version (Bash) Source: https://github.com/u007/drismify/blob/main/PUBLISHING.md This command updates the version number in package.json according to semantic versioning rules (patch, minor, or major). It also creates a new Git tag. ```bash # Update package.json npm version patch|minor|major # Manually update jsr.json to match # Update src/index.ts VERSION constant ``` -------------------------------- ### Implementing Hooks with Drismify's Hook Extension (TypeScript) Source: https://github.com/u007/drismify/blob/main/docs/advanced-features.md This snippet demonstrates how to use createHookExtension to define functions that run before or after specific database operations. It shows examples of a before create hook to log parameters and an after findMany hook to log results, as well as dynamically adding before and after hooks for update operations. ```typescript import { PrismaClient } from './generated/client'; import { createHookExtension } from 'drismify'; const prisma = new PrismaClient().$extends(createHookExtension( { // Before hooks create: async (params) => { console.log('Before create:', params); // Modify params if needed return params; } }, { // After hooks findMany: async (result) => { console.log(`Found ${result.length} records`); return result; } } )); // Add hooks dynamically const prismaWithMoreHooks = prisma .$before('update', (params) => { console.log('Before update:', params); return params; }) .$after('update', (result) => { console.log('After update:', result); return result; }); ``` -------------------------------- ### Implementing Caching for Drismify Queries Source: https://github.com/u007/drismify/blob/main/docs/advanced-features.md This example demonstrates how to enable and manage caching for frequently accessed data in Drismify. It shows how to configure caching during client initialization, enable it dynamically, use `cache: true` or `cache: false` for specific queries, and clear or disable the cache. ```typescript const prisma = new PrismaClient({ cache: { enabled: true, ttl: 60, // Time-to-live in seconds size: 100 // Maximum number of cached queries } }); // Or enable caching dynamically prisma.$enableCache({ ttl: 30, size: 50 }); // Cached queries will be served from cache when possible const cachedUsers = await prisma.user.findMany({ cache: true }); // Bypass cache for specific queries const freshUsers = await prisma.user.findMany({ cache: false }); // Clear the cache prisma.$clearCache(); // Disable caching prisma.$disableCache(); ``` -------------------------------- ### Validating an Existing Prisma Schema Source: https://github.com/u007/drismify/blob/main/README.md This snippet shows how to validate a Prisma schema file using the Drismify CLI. It includes basic validation and an example with verbose output and suggestions for detailed feedback on schema issues. ```bash drismify validate schema.prisma # Validate with verbose output and suggestions drismify validate schema.prisma --verbose --suggestions ``` -------------------------------- ### Programmatic Schema Parsing and Client Generation with Drismify (TypeScript) Source: https://github.com/u007/drismify/blob/main/README.md This example illustrates how to programmatically parse a Prisma schema file and generate client code using Drismify's internal utilities. It demonstrates the use of SchemaParser to obtain an Abstract Syntax Tree (AST) and ClientGenerator to output client code and types to a specified directory. ```typescript import { SchemaParser, SchemaTranslator, MigrationGenerator, ClientGenerator } from 'drismify'; // Parse Prisma schema programmatically const parser = new SchemaParser(); const ast = parser.parseFromFile('./schema.prisma'); // Generate client code programmatically const generator = new ClientGenerator({ outputDir: './generated/client', generateTypes: true }); await generator.generateFromAST(ast); ``` -------------------------------- ### Generated SQL for Check Constraints and Foreign Keys Source: https://github.com/u007/drismify/blob/main/README.md This SQL snippet shows the automatically generated `CREATE TABLE` statements by Drismify. It includes examples of `CHECK` constraints for `age`, `salary`, `status`, and `email` on the `user` table, and a named `FOREIGN KEY` constraint (`post_author_fk`) on the `post` table, along with named indexes. ```sql -- Table with check constraints CREATE TABLE "user" ( id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT UNIQUE NOT NULL, age INTEGER NOT NULL, salary REAL NOT NULL, status TEXT NOT NULL, CONSTRAINT minimum_age CHECK (age >= 18), CONSTRAINT positive_salary CHECK (salary > 0), CHECK (status IN ('active', 'inactive', 'suspended')), CHECK (LENGTH(email) > 5) ); -- Named foreign key constraint CREATE TABLE "post" ( id INTEGER PRIMARY KEY AUTOINCREMENT, author_id INTEGER NOT NULL, CONSTRAINT post_author_fk FOREIGN KEY ("author_id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE RESTRICT ); -- Named indexes CREATE INDEX user_credentials_idx ON user (email, username); CREATE INDEX user_status_created_idx ON user (status, created_at); ``` -------------------------------- ### Adding Middleware with Drismify's Middleware Extension (TypeScript) Source: https://github.com/u007/drismify/blob/main/docs/advanced-features.md This snippet illustrates how to use createMiddlewareExtension to intercept and modify database operations. It provides an example of a findMany middleware that logs execution time and results, and also shows how to dynamically add more middleware for specific operations like create. ```typescript import { PrismaClient } from './generated/client'; import { createMiddlewareExtension } from 'drismify'; const prisma = new PrismaClient().$extends(createMiddlewareExtension({ findMany: async (params, next) => { console.log('Before findMany:', params); const startTime = Date.now(); const result = await next(params); const duration = Date.now() - startTime; console.log(`findMany took ${duration}ms and returned ${result.length} results`); return result; } })); // Dynamically add more middleware const prismaWithMoreMiddleware = prisma.$use('create', async (params, next) => { console.log('Creating a record:', params); return next(params); }); ``` -------------------------------- ### Defining Referential Actions in Prisma Schema Source: https://github.com/u007/drismify/blob/main/README.md This snippet demonstrates how to define different referential actions (onDelete, onUpdate) for foreign key relationships in a Prisma schema. It shows examples of Cascade, Restrict, SetNull, and SetDefault for onDelete, and Restrict and NoAction for onUpdate, applied to Profile, Post, and Comment models. ```Prisma model User { id Int @id @default(autoincrement()) email String @unique posts Post[] comments Comment[] profile Profile? } // One-to-one with cascade delete model Profile { id Int @id @default(autoincrement()) bio String user User @relation(fields: [userId], references: [id], onDelete: Cascade) userId Int @unique } // Many-to-one with cascade delete and restrict update model Post { id Int @id @default(autoincrement()) title String content String? author User @relation(fields: [authorId], references: [id], onDelete: Cascade, onUpdate: Restrict) authorId Int comments Comment[] } // Set null on delete, set default on update model Comment { id Int @id @default(autoincrement()) content String post Post @relation(fields: [postId], references: [id], onDelete: SetNull) postId Int? author User @relation(fields: [authorId], references: [id], onDelete: SetDefault, onUpdate: NoAction) authorId Int @default(1) // Default to system user } ``` -------------------------------- ### Defining Index Constraints in Prisma Schema Source: https://github.com/u007/drismify/blob/main/README.md This snippet demonstrates how to define @@index constraints in a Prisma schema to create database indexes for improved query performance. It includes examples of both named and unnamed indexes, covering single-field and multi-field indexing for email, username, status, and createdAt fields. ```Prisma model User { id Int @id @default(autoincrement()) email String username String status String createdAt DateTime @default(now()) // Named indexes @@index([email, username], name: "user_credentials_idx") @@index([status, createdAt], name: "user_status_created_idx") // Unnamed indexes @@index([email]) @@index([createdAt]) } ``` -------------------------------- ### Enabling and Disabling Query Optimization in Drismify Source: https://github.com/u007/drismify/blob/main/docs/advanced-features.md This code demonstrates how to enable and disable Drismify's automatic query optimization feature. Once enabled using `$enableQueryOptimization()`, all subsequent queries are optimized. The example shows a complex query benefiting from optimization, and how to disable it with `$disableQueryOptimization()`. ```typescript // Enable query optimization prisma.$enableQueryOptimization(); // All queries will now be optimized const users = await prisma.user.findMany({ where: { posts: { some: { published: true } } }, include: { posts: true } }); // Disable query optimization prisma.$disableQueryOptimization(); ``` -------------------------------- ### Combining Multiple Drismify Extensions in TypeScript Source: https://github.com/u007/drismify/blob/main/docs/advanced-features.md This example illustrates how to combine various Drismify extensions like transaction, middleware, and soft delete into a single extension using `combineExtensions`. The combined extension is then applied to the Prisma client, allowing for modular and layered functionality, such as logging queries via a middleware. ```typescript import { PrismaClient } from './generated/client'; import { combineExtensions, createTransactionExtension, createMiddlewareExtension, createSoftDeleteExtension } from 'drismify'; const combinedExtension = combineExtensions( createTransactionExtension(), createMiddlewareExtension({ findMany: async (params, next) => { console.log('Query:', params); return next(params); } }), createSoftDeleteExtension() ); const prisma = new PrismaClient().$extends(combinedExtension); ``` -------------------------------- ### Defining Composite Types in Prisma Schema Source: https://github.com/u007/drismify/blob/main/README.md This Prisma schema snippet illustrates how to define reusable structured data types, known as composite types, using the `type` keyword. It shows examples of `Address` and `ContactInfo` types and their subsequent usage within `User` and `Business` models, allowing for complex, nested data structures. ```prisma // Define composite types in your schema type Address { street String city String state String zip String country String } type ContactInfo { email String phone String? website String? } // Use composite types in models model User { id Int @id @default(autoincrement()) name String address Address contact ContactInfo } model Business { id Int @id @default(autoincrement()) name String address Address coordinates Coordinates? } ``` -------------------------------- ### Defining Check Constraints in Prisma Schema Source: https://github.com/u007/drismify/blob/main/README.md This snippet illustrates how to define @@check constraints in a Prisma schema to enforce custom validation rules at the database level. It shows examples of both named and unnamed check constraints, including conditions for age, salary, status, email length, product price range, and discount validity. ```Prisma model User { id Int @id @default(autoincrement()) email String @unique age Int salary Float status String // Named check constraints @@check(age >= 18, name: "minimum_age") @@check(salary > 0, name: "positive_salary") // Unnamed check constraints @@check(status IN ('active', 'inactive', 'suspended')) @@check(LENGTH(email) > 5) } model Product { id Int @id @default(autoincrement()) name String price Float discount Float @default(0) // Complex check constraints @@check(price > 0 AND price < 1000000, name: "valid_price_range") @@check(discount >= 0 AND discount <= 1, name: "valid_discount") @@check(LENGTH(name) > 0 AND LENGTH(name) <= 255) } ``` -------------------------------- ### Adding Computed Fields with Drismify's Computed Fields Extension (TypeScript) Source: https://github.com/u007/drismify/blob/main/docs/advanced-features.md This snippet illustrates how to use createComputedFieldsExtension to define virtual fields whose values are derived from other fields in a model. It provides an example of a fullName computed field for the user model and shows how to dynamically add more computed fields like displayName. ```typescript import { PrismaClient } from './generated/client'; import { createComputedFieldsExtension } from 'drismify'; const prisma = new PrismaClient().$extends( createComputedFieldsExtension({ user: { fullName: { // Fields needed to compute this field needs: { firstName: true, lastName: true }, // Function to compute the field value compute: (user) => `${user.firstName} ${user.lastName}` } } }) ); // Add computed fields dynamically const prismaWithMoreFields = prisma.$addComputedField('user', 'displayName', { needs: { firstName: true, lastName: true, title: true }, compute: (user) => `${user.title || ''} ${user.firstName} ${user.lastName}`.trim() }); ``` -------------------------------- ### Combining Multiple JSON Conditions with Drismify (TypeScript) Source: https://github.com/u007/drismify/blob/main/README.md This snippet demonstrates how to combine multiple JSON conditions using logical operators (`AND`, `OR`) within Drismify queries. It shows examples of filtering users based on multiple nested JSON properties simultaneously and finding users matching any of several array elements. This enables highly specific and complex JSON data retrieval. ```typescript // Using AND with JSON fields const darkThemeWithNotifications = await prisma.user.findMany({ where: { AND: [ { 'metadata.preferences.theme': 'dark' }, { 'metadata.preferences.notifications': true } ] } }); // Using OR with JSON fields const adminOrModerators = await prisma.user.findMany({ where: { OR: [ { metadata: { array_contains: 'admin' } }, { metadata: { array_contains: 'moderator' } } ] } }); ``` -------------------------------- ### Using Drismify JSON Operators for Filtering (TypeScript) Source: https://github.com/u007/drismify/blob/main/README.md This snippet illustrates the use of various JSON operators provided by Drismify for advanced filtering. It includes examples of the `path` operator for specific JSON paths, `array_contains` for checking array elements, and `string_contains` for substring matching within JSON string values. These operators enhance the flexibility of JSON field queries. ```typescript // Using path operator const usersWithNotifications = await prisma.user.findMany({ where: { metadata: { path: ['$.preferences.notifications', true] } } }); // Using array_contains operator const adminUsers = await prisma.user.findMany({ where: { metadata: { array_contains: 'admin' } } }); // Using string_contains operator const mayLogins = await prisma.user.findMany({ where: { metadata: { string_contains: '2023-05-15' } } }); ``` -------------------------------- ### Querying Nested JSON Fields with Drismify (TypeScript) Source: https://github.com/u007/drismify/blob/main/README.md This snippet demonstrates how to query nested JSON fields in a database using Drismify's dot notation. It shows examples of filtering records based on a specific property within a nested JSON object (`metadata.preferences.theme`) and by an element within a JSON array (`metadata.roles[0]`). This simplifies complex JSON data retrieval. ```typescript // Query by nested JSON property const darkThemeUsers = await prisma.user.findMany({ where: { 'metadata.preferences.theme': 'dark' } }); // Query by array element const admins = await prisma.user.findMany({ where: { 'metadata.roles[0]': 'admin' } }); ``` -------------------------------- ### Drismify CLI: Project Initialization and Database Operations (Bash) Source: https://github.com/u007/drismify/blob/main/README.md This snippet lists additional Drismify CLI commands for project initialization, client generation, and database operations. It covers initializing a new project with a specified database provider, generating a client from a schema, and performing database push and pull operations for schema synchronization. These commands streamline the development workflow. ```bash # Project initialization drismify init [directory] [--provider sqlite|turso|mongodb] # Client generation drismify generate [schema-path] [--output ./generated/client] # Database operations drismify db push [--schema schema.prisma] [--force] [--reset] drismify db pull [--schema schema.prisma] ``` -------------------------------- ### Launching Drismify Database Studio Source: https://github.com/u007/drismify/blob/main/README.md This Bash command launches the Drismify web-based Studio. The Studio provides a graphical interface for managing the database, including browsing records, viewing schemas, executing custom queries, and visualizing model relationships. ```bash npx drismify studio ``` -------------------------------- ### Running Drismify Tests - Bash Source: https://github.com/u007/drismify/blob/main/README.md This snippet demonstrates how to execute tests for the Drismify project using pnpm. It includes commands to run all tests once and to run tests in watch mode, which is useful for continuous development feedback. ```bash # Run all tests pnpm test # Run tests in watch mode pnpm test --watch ``` -------------------------------- ### Using Drismify Client for Database Operations (TypeScript) Source: https://github.com/u007/drismify/blob/main/tests/fixtures/generated/client/README.md This snippet demonstrates the fundamental steps for interacting with a database using the Drismify client. It covers initializing the client, establishing a connection, performing a data query (findMany), and properly disconnecting, with basic error handling. ```TypeScript import { PrismaClient } from './index'; const prisma = new PrismaClient(); async function main() { // Connect to the database await prisma.connect(); // Use the client const users = await prisma.user.findMany(); console.log(users); // Disconnect from the database await prisma.disconnect(); } main().catch(console.error); ``` -------------------------------- ### Drismify CLI: Help, Schema Validation, and Conversion (Bash) Source: https://github.com/u007/drismify/blob/main/README.md This snippet provides an overview of essential Drismify CLI commands. It demonstrates how to display help information, validate Prisma schema syntax and structure with optional verbose output, linting, and suggestions, and convert a Prisma schema into a Drizzle schema. These commands are crucial for schema management and migration workflows. ```bash # Show help and available commands drismify --help # Validate schema syntax and structure drismify validate [schema-path] [--verbose] [--lint] [--suggestions] # Convert Prisma schema to Drizzle schema drismify generate-schema [drizzle-output-path] ``` -------------------------------- ### Managing Database Migrations with Drismify CLI Source: https://github.com/u007/drismify/blob/main/README.md This snippet demonstrates the core Drismify CLI commands used for managing database migrations, including developing new migrations, deploying pending migrations, resetting the database, and checking migration status. These commands are essential for versioning and evolving the database schema. ```bash drismify migrate dev [schema-path] [migration-name] drismify migrate deploy drismify migrate reset drismify migrate status ``` -------------------------------- ### Launching Drismify Database Studio (Disabled) Source: https://github.com/u007/drismify/blob/main/README.md This command, currently disabled, is intended to launch the Drismify database studio, providing a web-based interface for database management. It allows specifying a schema path and a custom port for the studio application. ```bash drismify studio [schema-path] [--port 5555] ``` -------------------------------- ### Creating Corresponding SQL Database Views Source: https://github.com/u007/drismify/blob/main/README.md These SQL `CREATE VIEW` statements define the actual database views (`user_info`, `published_posts`) that correspond to the Prisma view definitions. They demonstrate how to join tables (`user`, `profile`, `post`) and select specific columns to form the view's structure. ```sql CREATE VIEW user_info AS SELECT u.id, u.email, u.name, p.bio FROM user u LEFT JOIN profile p ON u.id = p.user_id; CREATE VIEW published_posts AS SELECT p.id, p.title, p.content, u.name as author_name, u.email as author_email, p.created_at FROM post p JOIN user u ON p.author_id = u.id WHERE p.published = TRUE; ``` -------------------------------- ### Seeding Database Data with Drismify CLI Source: https://github.com/u007/drismify/blob/main/README.md This command is used to populate the database with initial data, often for development or testing purposes. It allows specifying a schema path and a seed script, with an optional flag to reset the database before seeding. ```bash drismify seed [schema-path] [seed-script] [--reset] ``` -------------------------------- ### Initializing Drismify Client with Custom Adapter and Extensions (TypeScript) Source: https://github.com/u007/drismify/blob/main/README.md This snippet demonstrates how to initialize a Drismify client with a custom SQLite adapter and define a model extension. It shows the creation of an adapter, client configuration with debugging enabled, and the application of a custom findByEmail method to the user model using the $extends API. ```typescript import { Drismify, DrismifyClient, createAdapter } from 'drismify'; // Create a custom adapter const adapter = createAdapter({ type: 'sqlite', connectionString: 'file:./my-app.db' }); // Create a client with custom configuration const client = new DrismifyClient({ adapter, debug: true }); // Use Drismify utilities const extension = Drismify.defineExtension({ model: { user: { async findByEmail(email: string) { return this.findFirst({ where: { email } }); } } } }); const extendedClient = client.$extends(extension); ``` -------------------------------- ### Using Drismify Client for Database Operations (TypeScript) Source: https://github.com/u007/drismify/blob/main/generated/client/README.md This snippet demonstrates the basic usage of the Drismify client. It shows how to initialize PrismaClient, connect to the database, perform a findMany operation on the user model, and then disconnect. It handles potential errors by catching them. ```TypeScript import { PrismaClient } from './index'; const prisma = new PrismaClient(); async function main() { // Connect to the database await prisma.connect(); // Use the client const users = await prisma.user.findMany(); console.log(users); // Disconnect from the database await prisma.disconnect(); } main().catch(console.error); ``` -------------------------------- ### Defining Reusable Drismify Model Extensions (TypeScript) Source: https://github.com/u007/drismify/blob/main/README.md This snippet illustrates how to define a reusable extension using `Drismify.defineExtension`. It adds a `signUp` method to the `user` model, encapsulating user creation logic. This approach promotes modularity and reusability of custom model methods across different Prisma client instances. ```typescript import { Drismify } from './generated/client'; const myExtension = Drismify.defineExtension({ model: { user: { async signUp(email: string, name: string) { return this.create({ data: { email, name } }); } } } }); const prisma = new PrismaClient().$extends(myExtension); ``` -------------------------------- ### Configuring Drismify Performance Optimization in TypeScript Source: https://github.com/u007/drismify/blob/main/README.md This TypeScript code demonstrates how to enable query optimization and caching for a Prisma client instance. It shows both initial configuration during client instantiation and dynamic enabling of these features after the client has been created, with a configurable time-to-live (TTL) for the cache. ```typescript // Enable query optimization and caching const prisma = new PrismaClient({ queryOptimization: true, cache: { enabled: true, ttl: 60 // seconds } }); // Or enable them dynamically prisma.$enableQueryOptimization(); prisma.$enableCache(); ``` -------------------------------- ### Managing Database Migrations with Drismify CLI Source: https://github.com/u007/drismify/blob/main/docs/advanced-features.md This section outlines various Drismify CLI commands for managing database migrations. It covers generating and applying migrations in development (`migrate dev`), deploying migrations in production (`migrate deploy`), resetting the database (`migrate reset`), and checking migration status (`migrate status`). ```bash # Generate and apply migrations in development npx drismify migrate dev [schema-path] [migration-name] # Apply migrations in production npx drismify migrate deploy # Reset the database npx drismify migrate reset # Show migration status npx drismify migrate status ``` -------------------------------- ### Extending Prisma Client with Custom Model Method (TypeScript) Source: https://github.com/u007/drismify/blob/main/README.md Demonstrates how to use Prisma's `$extends` API to add a custom method (`signUp`) to a specific model (`user`). This allows encapsulating common operations directly within the model's interface for cleaner and more reusable code. ```typescript const prisma = new PrismaClient().$extends({ model: { user: { async signUp(email: string, name: string) { return this.create({ data: { email, name } }); } } } }); // Use the extended client const user = await prisma.user.signUp('john@example.com', 'John Doe'); ``` -------------------------------- ### Using Drizzle ORM with Drismify Schema (TypeScript) Source: https://github.com/u007/drismify/blob/main/README.md Demonstrates how to connect to a Better SQLite3 database using Drizzle ORM, import a Drismify-generated schema, and perform basic CRUD operations (insert, query with relations) on `user` and `post` models. It shows creating new users, adding posts, and querying users with their associated posts. ```typescript // Import the generated Drizzle schema import { drizzle } from 'drizzle-orm/better-sqlite3'; import Database from 'better-sqlite3'; import { user, post, userRelations, postRelations } from './drizzle-schema'; // Create database connection const sqlite = new Database('./dev.db'); const db = drizzle(sqlite, { schema: { user, post, userRelations, postRelations } }); async function main() { // Create a new user const newUser = await db.insert(user).values({ email: 'alice@example.com', name: 'Alice' }).returning(); console.log('Created user:', newUser[0]); // Create posts for the user await db.insert(post).values([ { title: 'Hello World', content: 'This is my first post!', published: true, authorId: newUser[0].id }, { title: 'Getting Started', content: 'Learning Drismify...', published: false, authorId: newUser[0].id } ]); // Query users with their posts using relations const usersWithPosts = await db.query.user.findMany({ with: { posts: true } }); console.log('All users with posts:', usersWithPosts); } main().catch(console.error); ``` -------------------------------- ### Performing Native MongoDB Operations with Drismify (TypeScript) Source: https://github.com/u007/drismify/blob/main/README.md Shows how to use the `MongoDBAdapter` in Drismify to connect to a MongoDB database and perform native operations. It covers inserting documents, querying with MongoDB operators (`$in`, `$project`), and executing aggregation pipelines (`$lookup`, `$project`) on collections. ```typescript import { MongoDBAdapter } from 'drismify'; // Create MongoDB adapter const adapter = new MongoDBAdapter({ url: 'mongodb://localhost:37017', database: 'myapp' }); await adapter.connect(); // Get MongoDB collections const usersCollection = adapter.getCollection('User'); const postsCollection = adapter.getCollection('Post'); // Native MongoDB operations const user = await usersCollection.insertOne({ email: 'user@example.com', name: 'John Doe', metadata: { preferences: { theme: 'dark' } } }); // Query with MongoDB operators const posts = await postsCollection.find({ tags: { $in: ['mongodb', 'database'] }, published: true }).toArray(); // Aggregation pipeline const userStats = await usersCollection.aggregate([ { $lookup: { from: 'Post', localField: '_id', foreignField: 'authorId', as: 'posts' } }, { $project: { name: 1, email: 1, postCount: { $size: '$posts' } } } ]).toArray(); ``` -------------------------------- ### Executing Batch Operations with Drismify in TypeScript Source: https://github.com/u007/drismify/blob/main/docs/advanced-features.md This snippet demonstrates how to perform multiple database operations within a single batch using `drismify`'s `createBatchExtension`. It initializes a Prisma client with the batch extension and then executes a series of `findMany` queries for users and posts, ensuring related data is fetched efficiently. ```typescript import { PrismaClient } from './generated/client'; import { createBatchExtension } from 'drismify'; const prisma = new PrismaClient().$extends(createBatchExtension()); // Use batch operations const result = await prisma.$batch(async (batch) => { const users = await batch.user.findMany(); const posts = await batch.post.findMany({ where: { authorId: { in: users.map(u => u.id) } } }); return { users, posts }; }); ``` -------------------------------- ### Enabling Debugging with Drismify's Debug Extension (TypeScript) Source: https://github.com/u007/drismify/blob/main/docs/advanced-features.md This snippet demonstrates how to integrate and use createDebugExtension to add logging capabilities for database operations. It shows how to initialize the extension with a custom logger function and how to enable and disable debugging globally for the Prisma client. ```typescript import { PrismaClient } from './generated/client'; import { createDebugExtension } from 'drismify'; const prisma = new PrismaClient().$extends( createDebugExtension((message, data) => { console.log(`[DEBUG] ${message}`, data || ''); }) ); // Enable debugging prisma.$enableDebug(); // All queries will now log debug information const users = await prisma.user.findMany(); // Disable debugging prisma.$disableDebug(); ``` -------------------------------- ### Introspecting Database Schema with Drismify CLI Source: https://github.com/u007/drismify/blob/main/README.md This command allows Drismify to introspect an existing database, generating a schema file based on its current structure. It requires the database URL and can optionally specify a provider and an output path for the generated schema. ```bash drismify introspect [provider] [output-path] ```