### Install SurQL from JSR Source: https://github.com/albedosehen/surql/blob/main/README.md Demonstrates how to install the SurQL library directly from JSR into a Deno project. This is the primary method for adding SurQL to your Deno environment. ```typescript import { query, SurrealConnectionManager } from "jsr:@albedosehen/surql" ``` -------------------------------- ### Clone Repository and Setup Source: https://github.com/albedosehen/surql/blob/main/README.md Details the steps for setting up the SurQL project locally. It includes cloning the repository from GitHub and navigating into the project directory, preparing for development or contribution. ```bash # Clone the repository git clone https://github.com/albedosehen/surql.git cd surql ``` -------------------------------- ### Run Specific Example Source: https://github.com/albedosehen/surql/blob/main/README.md Provides a command-line instruction using Deno to run a specific example script from the `examples/` directory. This is useful for testing or understanding the library's functionality in a practical context. ```bash # Run a specific example denp run -A examples/basicCrud.ts ``` -------------------------------- ### Root User Authentication Example Source: https://github.com/albedosehen/surql/blob/main/README.md Provides an example of authenticating with SurrealDB using the root user credentials. It demonstrates fetching credentials from environment variables for security. ```typescript const rootToken = await client.signin({ type: 'root', username: Deno.env.get('SURREALDB_ROOT_USERNAME') ?? 'root', password: Deno.env.get('SURREALDB_ROOT_PASSWORD') ?? 'password' }); ``` -------------------------------- ### SurQL Pagination with Limit/Offset and Page Source: https://github.com/albedosehen/surql/blob/main/README.md Provides examples of implementing pagination using both traditional `limit`/`offset` parameters and a convenient `page` method. This allows for efficient retrieval of data subsets. ```typescript // Traditional limit/offset const paginatedResults = await client.query('users') .where({ active: true }) .orderBy('created_at', SortDirection.DESC) .limit(25) .offset(50) .execute(); // Offset-based pagination with page number and size const pageResults = await client.query('products') .where({ in_stock: true }) .orderBy('name') .page(3, 20) // Page 3, 20 items per page .execute(); // Complex grouped/paginated example const groupedPage = await client.query('analytics') .groupBy('date', 'channel') .sum('visits') .count('conversions') .having('SUM(visits)', Op.GREATER_THAN, 100) .orderBy('sum_visits', SortDirection.DESC) .page(1, 10) .execute(); ``` -------------------------------- ### Deno Development and Testing Commands Source: https://github.com/albedosehen/surql/blob/main/README.md Essential Deno CLI commands for project development and quality assurance. These commands are used for type checking, code linting, formatting, and running tests to ensure code integrity and adherence to project standards. Deno must be installed to execute these commands. ```shell deno check ``` ```shell deno lint ``` ```shell deno fmt ``` ```shell deno task test ``` -------------------------------- ### SurQL Error Handling with Try-Catch Source: https://github.com/albedosehen/surql/blob/main/README.md Explains that SurQL uses standard JavaScript error handling patterns, including `try-catch` with `async/await`. This example demonstrates a typical query execution within a `try` block and general error logging in the `catch` block. ```typescript try { const users = await client.query('users') .where({ active: true }) .map(mapUser) .execute() console.log('Success:', users) } catch (error) { console.error('Error:', error) // Handle specific error types if (error.message.includes('connection')) { // Handle connection errors } } ``` -------------------------------- ### Authenticate with Token and Session Management Source: https://github.com/albedosehen/surql/blob/main/README.md Authenticates the client using an existing token and provides methods for session management: checking authentication status, getting session info, invalidating the session, and retrieving the current token. ```typescript await client.authenticate(token); // Session management const sessionInfo = await client.info(); await client.invalidate(); const isLoggedIn = client.isAuthenticated(); const currentToken = client.getCurrentToken(); ``` -------------------------------- ### Handle Merge/Upsert Errors Source: https://github.com/albedosehen/surql/blob/main/README.md Provides an example of handling errors during a merge or upsert operation in TypeScript. This snippet checks for specific error messages, like 'returned no records', to identify cases where the target record was not found. ```typescript try { await client.merge('users', 'nonexistent:id', { name: 'test' }).execute() } catch (error) { if (error.message.includes('returned no records')) { console.error('Record not found for merge operation') } } ``` -------------------------------- ### Import SurQL using Alias Source: https://github.com/albedosehen/surql/blob/main/README.md Illustrates importing SurQL components after configuring an import alias in `deno.json`. This provides a cleaner import path. ```typescript import { query, SurrealConnectionManager } from "surql" ``` -------------------------------- ### Sign Up Scope User with Preferences Source: https://github.com/albedosehen/surql/blob/main/README.md Registers a new scope user, including optional preferences like theme. ```typescript await client.signup({ namespace: 'myapp', database: 'production', scope: 'user', username: 'jane@example.com', password: 'newpassword', email: 'jane@example.com', name: 'Jane Doe', preferences: { theme: 'dark' } }); ``` -------------------------------- ### SurQLClient Usage Source: https://github.com/albedosehen/surql/blob/main/README.md Shows how to create and use the `SurQLClient` for interacting with SurQL. This client provides a convenient interface for authentication and session management, suitable for lighter use cases or single connection scenarios. ```typescript // Create SurQL client with connection manager const client = new SurQLClient(config) // Use the client for queries const users = await client.query('users') .where({ active: true }) .map(mapUser) .execute() console.log('Success:', users) ``` -------------------------------- ### Configure SurQL Alias in Deno Source: https://github.com/albedosehen/surql/blob/main/README.md Shows how to set up a Deno import alias for SurQL in your `deno.json` configuration file. This simplifies imports throughout your project. ```json { "imports": { "surql": "jsr:@albedosehen/surql" } } ``` -------------------------------- ### SurQL Query Execution and Data Transformation Source: https://github.com/albedosehen/surql/blob/main/README.md Shows how to execute queries and optionally transform the results using the `.map()` method. It also demonstrates how to handle warnings related to unmapped data. ```typescript const rawUsers = await query(connectionProvider, userTable) .map((raw) => ({ ... })) .execute() // No warnings, explicit mapping provided const rawUsers = await query(connectionProvider, userTable) .execute() // Warning: Consider using .map() for type transformation const rawUsers = await query(connectionProvider, userTable, { warnings: 'suppress' }) .execute() // Suppress warning with explicit raw data usage ``` -------------------------------- ### Sign Up New Scope User Source: https://github.com/albedosehen/surql/blob/main/README.md Registers a new user for a specific scope, providing credentials, contact information, and optional profile details. ```typescript const newUserToken = await client.signup({ namespace: Deno.env.get('SURREALDB_NAMESPACE') ?? 'dev', database: Deno.env.get('SURREALDB_DATABASE') ?? 'myapp', scope: 'user', username: 'randomuser', password: 'randompassword', email: 'random@example.com', name: 'Random User' }); ``` -------------------------------- ### Convenience WHERE Methods Source: https://github.com/albedosehen/surql/blob/main/README.md Illustrates using shortcut methods for common filtering operations like equality, containment, and pattern matching. ```typescript const verifiedUsers = await client.query('users') .whereEquals('status', 'verified') .whereContains('tags', 'premium') .whereLike('email', '%@company.com') .execute(); ``` -------------------------------- ### Creating Data (Raw and Transformed) Source: https://github.com/albedosehen/surql/blob/main/README.md Illustrates the process of creating new records, with options to insert raw data or data that is immediately transformed into a target type. ```typescript // Raw types const newRawUser = await create(connectionProvider, userTable, { username: 'johndoe', email: 'john@example.com', active: true, profile: { firstName: 'John', lastName: 'Doe' } }).execute(); console.log('Created raw user:', newRawUser); // With transformation const newUser = await create(connectionProvider, userTable, { username: 'johndoe', email: 'john@example.com', active: true, profile: { firstName: 'John', lastName: 'Doe' } }).map(mapUser).execute(); console.log('Created transformed user:', newUser); ``` -------------------------------- ### Pagination with Limit and Offset Source: https://github.com/albedosehen/surql/blob/main/README.md Shows how to implement pagination by specifying the maximum number of records to return (limit) and the number of records to skip (offset). ```typescript const rawPagedUsers = await query(connectionProvider, userTable) .limit(25) .offset(50) .execute(); const users = await query(connectionProvider, userTable) .limit(25) .offset(50) .map(mapUser) .execute(); ``` -------------------------------- ### SurQL Error Handling with Specific Error Types Source: https://github.com/albedosehen/surql/blob/main/README.md Demonstrates how to catch and handle various SurQL-specific errors, such as authentication failures, using `instanceof` checks for granular error management. ```typescript // ... try { await client.signin({ type: 'scope', namespace: 'app', database: 'prod', scope: 'user', username: 'user@example.com', password: 'wrongpassword' }) } catch (error) { if (error instanceof InvalidCredentialsError) { console.error('Login failed: Invalid username or password') } else if (error instanceof ScopeAuthenticationError) { console.error('Scope authentication failed:', error.message) } else if (error instanceof AuthenticationError) { console.error('Authentication error:', error.code, error.message) } } ``` -------------------------------- ### Authenticate Namespace Admin Source: https://github.com/albedosehen/surql/blob/main/README.md Signs in as an administrator for a specific namespace, requiring namespace, username, and password. ```typescript await client.signin({ type: 'namespace', namespace: 'myapp', username: 'admin', password: 'password' }); ``` -------------------------------- ### SurQL Error Handling with Promise Chain Source: https://github.com/albedosehen/surql/blob/main/README.md Demonstrates SurQL error handling using the Promise chain pattern in JavaScript. It shows how to chain `.then()` for successful operations and `.catch()` for handling any errors that occur during the query execution. ```typescript client.query('users') .where({ active: true }) .map(mapUser) .execute() .then(users => { console.log('Success:', users) return processUsers(users) }) .catch(error => { console.error('Error:', error) return handleError(error) }) ``` -------------------------------- ### SurQL GROUP BY and Aggregations Source: https://github.com/albedosehen/surql/blob/main/README.md Demonstrates how to group query results by specified fields and apply aggregate functions like count, sum, and average. This allows for powerful data summarization directly within the query builder. ```typescript const salesByRegion = await client.query('sales') .groupBy('region') .count() .sum('amount') .avg('order_value') .execute(); const detailedAnalytics = await client.query('orders') .groupBy('customer_id', 'product_category', 'sales_channel') .count('order_id') .sum('total_amount') .min('order_date') .max('order_date') .execute(); const customAggregation = await client.query('products') .groupBy('category') .count() .sum('price') .avg('rating') .min('stock') .max('stock') .execute(); ``` -------------------------------- ### Fluent-style WHERE Clause Source: https://github.com/albedosehen/surql/blob/main/README.md Shows how to apply filters using a fluent API style, specifying field, operator, and value for each condition. ```typescript const rawFilteredUsers = await client.query('users') .where('age', Op.GREATER_THAN, 18) .where('username', Op.LIKE, '%admin%') .execute(); const users = await client.query('users') .where('age', Op.GREATER_THAN, 18) .where('username', Op.LIKE, '%admin%') .map(mapUser) .execute(); ``` -------------------------------- ### Authenticate Database User Source: https://github.com/albedosehen/surql/blob/main/README.md Signs in as a user with access to a specific database within a namespace, requiring namespace, database, username, and password. ```typescript await client.signin({ type: 'database', namespace: 'myapp', database: 'production', username: 'dbuser', password: 'password' }); ``` -------------------------------- ### Authenticate Root User Source: https://github.com/albedosehen/surql/blob/main/README.md Signs in as the root user, requiring only username and password. ```typescript await client.signin({ type: 'root', username: 'root', password: 'password' }); ``` -------------------------------- ### Smart Defaults for Serialization Source: https://github.com/albedosehen/surql/blob/main/README.md Demonstrates using SurQL utility types like `Serialized` and `createSerializer` to automatically convert raw SurrealDB record types into plain JavaScript objects with serialized dates and IDs. ```typescript import { SurQLClient, Serialized, createSerializer } from "surql" try { const rawUsers = await client.query('users') .where({ active: true }) .orderBy('username') .limit(10) .execute(); // Array of UserRaw console.log('Raw users with SurrealDB types:', rawUsers); // Use the Serialized utility type type SerializedUser = Serialized; // id: string; created_at: string; etc. // Create serializer const serializer = createSerializer(); const transformedUsers: SerializedUser[] = rawUsers.map(raw => ({ id: serializer.id(raw), username: raw.username, email: raw.email, created_at: serializer.date(raw.created_at), active: raw.active })); console.log('Transformed users:', transformedUsers); } catch (error) { console.error('Query failed:', error); } ``` -------------------------------- ### Field Selection Source: https://github.com/albedosehen/surql/blob/main/README.md Demonstrates how to select specific fields to retrieve from records, optimizing data transfer by fetching only necessary columns. ```typescript const partialUsers = await query(connectionProvider, userTable) .select('username', 'email', 'created_at') .execute(); ``` -------------------------------- ### Execute Basic Query Source: https://github.com/albedosehen/surql/blob/main/README.md Performs a query against a specified table with optional query parameters. ```typescript const result = await client.query(conn, 'posts', { warnings: 'suppress' }) .where({ published: true }) .execute(); ``` -------------------------------- ### SurrealConnectionManager Usage Source: https://github.com/albedosehen/surql/blob/main/README.md Demonstrates the usage of `SurrealConnectionManager` for managing connection pooling in SurQL. This class handles connection lifecycle automatically, allowing for multiple concurrent operations and connection reuse. ```typescript // Connection pooling is handled automatically for you const connectionProvider = new SurrealConnectionManager(config) // Use across multiple operations const users = await query(connectionProvider, userTable) .map(mapUser) .execute() const posts = await query(connectionProvider, postTable) .map(mapPost) .execute() // Close when done (optional - handles cleanup automatically) await connectionProvider.close() ``` -------------------------------- ### Sorting Records Source: https://github.com/albedosehen/surql/blob/main/README.md Demonstrates how to apply sorting to query results based on one or more fields in ascending or descending order. ```typescript const rawUsers = await query(connectionProvider, userTable) .orderBy('created_at', SortDirection.DESC) .orderBy('username', SortDirection.ASC) .execute(); const users = await query(connectionProvider, userTable) .orderBy('created_at', SortDirection.DESC) .orderBy('username', SortDirection.ASC) .map(mapUser) .execute(); ``` -------------------------------- ### Updating Data (Replace) Source: https://github.com/albedosehen/surql/blob/main/README.md Demonstrates how to completely replace an existing record with new data, overwriting all previous fields. ```typescript const replacedRawUser = await update( connectionProvider, userTable, 'users:123', { username: 'newusername', email: 'new@example.com', active: true } ).replace().execute(); const replacedUser = await update( connectionProvider, userTable, 'users:123', { username: 'newusername', email: 'new@example.com', active: true } ).replace().map(mapUser).execute(); ``` -------------------------------- ### Updating Data (Merge) Source: https://github.com/albedosehen/surql/blob/main/README.md Shows how to perform a partial update on an existing record, merging new data with the existing fields. ```typescript const updatedRawUser = await update( connectionProvider, userTable, 'users:123', { active: false, lastLogin: new Date() } ).execute(); const updatedUser = await update( connectionProvider, userTable, 'users:123', { active: false, lastLogin: new Date() } ).map(mapUser).execute(); ``` -------------------------------- ### Check Authentication and Session Info Source: https://github.com/albedosehen/surql/blob/main/README.md Verifies if the client is authenticated and retrieves current session details like ID and expiration time. ```typescript if (client.isAuthenticated()) { const sessionInfo = await client.info(); console.log('Logged in as:', sessionInfo.id); console.log('Session expires:', sessionInfo.expires); } ``` -------------------------------- ### Client JSON Patch (RFC 6902) Source: https://github.com/albedosehen/surql/blob/main/README.md Demonstrates applying complex modifications to a record using JSON Patch operations (add, replace, remove, move, copy, test) via the client interface. ```typescript const patchedRecord = await client.patch('users', 'user:123', [ { op: 'add', path: '/preferences/theme', value: 'dark' }, { op: 'replace', path: '/email', value: 'updated@example.com' }, { op: 'remove', path: '/tempField' }, { op: 'move', from: '/oldField', path: '/newField' }, { op: 'copy', from: '/template', path: '/newCopy' }, { op: 'test', path: '/version', value: '1.0' } ]).map(mapUser).execute(); const result = await client.patch('documents', 'doc:789', []) .addOperation({ op: 'add', path: '/sections/-', value: newSection }) .addOperation({ op: 'replace', path: '/lastModified', value: new Date() }) .addOperations([ { op: 'remove', path: '/draft' }, { op: 'add', path: '/published', value: true } ]) .execute(); ``` -------------------------------- ### Authenticate Scope User Source: https://github.com/albedosehen/surql/blob/main/README.md Signs in a user within a specific scope, requiring namespace, database, scope name, username, and password. ```typescript const userToken = await client.signin({ type: 'scope', namespace: Deno.env.get('SURREALDB_NAMESPACE') ?? 'dev', database: Deno.env.get('SURREALDB_DATABASE') ?? 'myapp', scope: 'user', username: Deno.env.get('SURREALDB_USER_USERNAME') ?? 'username', password: Deno.env.get('SURREALDB_USER_PASSWORD') ?? 'password' }); ``` -------------------------------- ### Client Merge (Partial Update) Source: https://github.com/albedosehen/surql/blob/main/README.md Shows an alternative method for partial updates using the client object, allowing for merging data into existing records, including nested properties. ```typescript const updatedUser = await client.merge('users', 'user:123', { email: 'newemail@example.com', lastLogin: new Date(), preferences: { notifications: true } }).map(mapUser).execute(); const updatedProduct = await client.merge('products', 'product:456', { 'pricing.discount': 0.15, 'metadata.updated_by': 'admin', tags: ['sale', 'featured'] }).execute(); ``` -------------------------------- ### Handle Patch Operation Errors Source: https://github.com/albedosehen/surql/blob/main/README.md Illustrates catching errors during a patch operation in TypeScript. It specifically shows how to handle a PatchOperationError, logging the error message and the problematic operation details. ```typescript try { await client.patch('users', 'user:123', [ { op: 'invalid', path: '/field', value: 'test' } // Invalid operation ]).execute() } catch (error) { if (error instanceof PatchOperationError) { console.error('Patch failed:', error.message) console.error('Operation:', error.operation) } } ``` -------------------------------- ### Object-style WHERE Clause Source: https://github.com/albedosehen/surql/blob/main/README.md Demonstrates filtering records using an object-based WHERE clause, allowing for multiple conditions and nested property access. ```typescript const rawUsers = await client.query('users') .where({ active: true, role: 'admin', 'profile.verified': true }) .execute(); const users = await client.query('users') .where({ active: true, role: 'admin', 'profile.verified': true }) .map(mapUser) .execute(); ``` -------------------------------- ### Read First Record Source: https://github.com/albedosehen/surql/blob/main/README.md Retrieves the first record from a specified table, available as raw SurrealDB types or as a transformed object. ```typescript // Get first user (raw) const firstRawUser = await client.query('users').first(); // Get first user (transformed) const firstUser = await client.query('users').map(mapUser).first(); ``` -------------------------------- ### Query with Strong Typing and Mapping Source: https://github.com/albedosehen/surql/blob/main/README.md Executes a typed query, filters results, orders them, limits the count, and maps raw data to a specific interface using a custom mapper function. ```typescript import { SurQLClient, RecordId } from "surql" // Define types for raw and serialized user data interface UserRaw { id: RecordId; username: string; email: string; created_at: Date; active: boolean; } interface SerializedUser { id: string; username: string; email: string; createdAt: string; active: boolean; } // Mapper to convert SurrealDB types to plain objects const mapUser = (raw: UserRaw): SerializedUser => ({ id: raw.id.toString(), username: raw.username, email: raw.email, createdAt: raw.created_at.toISOString(), active: raw.active }); // Execute a query and map the results try { const activeUsers = await client.query('users') .where({ active: true }) .orderBy('username') .limit(10) .map(mapUser) .execute(); console.log('Found active users:', activeUsers); } catch (error) { console.error('Query failed:', error); } ``` -------------------------------- ### Read All Records Source: https://github.com/albedosehen/surql/blob/main/README.md Fetches all records from a specified table, returning them either as raw SurrealDB types or as transformed objects using a mapping function. ```typescript // Get all users (raw SurrealDB types) const rawUsers = await client.query('users').execute(); // Get all users with transformation const users = await client.query('users').map(mapUser).execute(); ``` -------------------------------- ### Deleting Data Source: https://github.com/albedosehen/surql/blob/main/README.md Illustrates how to remove a record from the database using its identifier, with options for raw or transformed return values. ```typescript const deletedRawUser = await remove(connectionProvider, userTable, 'users:123').execute(); console.log('Deleted raw user:', deletedRawUser); const deletedUser = await remove(connectionProvider, userTable, 'users:123') .map(mapUser) .execute(); console.log('Deleted transformed user:', deletedUser); ``` -------------------------------- ### Handle Session Management Errors Source: https://github.com/albedosehen/surql/blob/main/README.md Demonstrates how to catch specific session-related errors like SessionExpiredError and InvalidTokenError in TypeScript. This allows for appropriate user feedback or redirection, such as prompting a re-login. ```typescript try { const sessionInfo = await client.info() } catch (error) { if (error instanceof SessionExpiredError) { console.error('Session expired, please login again') // Redirect to login } else if (error instanceof InvalidTokenError) { console.error('Invalid token, clearing session') // Clear stored token } } ``` -------------------------------- ### SurQL HAVING Conditions for Filtering Aggregations Source: https://github.com/albedosehen/surql/blob/main/README.md Illustrates the use of the `having` clause to filter grouped results based on aggregate conditions. This enables sophisticated filtering after data aggregation, similar to SQL's HAVING clause. ```typescript const highValueCustomers = await client.query('customer_orders') .groupBy('customer_id') .sum('order_total') .count() .having('SUM(order_total)', Op.GREATER_THAN, 10000) .having('COUNT(*)', Op.GREATER_THAN, 5) .execute(); const activeCategories = await client.query('products') .groupBy('category') .count() .having('COUNT(*) > 10') .having('AVG(price) BETWEEN 50 AND 500') .execute(); const premiumSegments = await client.query('sales') .groupBy('product_line', 'quarter') .sum('revenue') .avg('margin') .count('transactions') .having('SUM(revenue)', Op.GREATER_THAN, 100000) .having('AVG(margin)', Op.GREATER_THAN, 0.25) .having('COUNT(transactions)', Op.GREATER_THAN, 50) .execute(); ``` -------------------------------- ### Sign Out Session Source: https://github.com/albedosehen/surql/blob/main/README.md Invalidates the current client session, effectively logging the user out. ```typescript // Sign out await client.invalidate(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.