### Batch Query Execution Example - TypeScript Source: https://webbeetechnologies.github.io/taylordb/classes/batch-query-builder.BatchQueryBuilder An example demonstrating how to use the execute method of BatchQueryBuilder to run a batch of select and insert queries, retrieving results for each. ```typescript const [users, newUser] = await qb.batch([ qb.selectFrom('users').select(['id', 'name']), qb.insertInto('users').values({ name: 'New User' }).returning(['id', 'name']), ]).execute(); ``` -------------------------------- ### Batch Query Subscription Example - TypeScript Source: https://webbeetechnologies.github.io/taylordb/classes/batch-query-builder.BatchQueryBuilder Illustrates how to use the subscribe method of BatchQueryBuilder to receive real-time updates for a batch of subscribable queries (select and aggregate). ```typescript const unsubscribe = qb.batch([ qb.selectFrom('users').select(['id', 'name']), qb.aggregateFrom('users').groupBy('role').withAggregates({ id: ['count'] }), ]).subscribe(([users, userAggregates]) => { console.log('Users:', users); console.log('User Aggregates:', userAggregates); }); // To stop listening for updates unsubscribe(); ``` -------------------------------- ### Create Aggregation Query - TypeScript Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.RootQueryBuilder Initializes an AggregationQueryBuilder for a specified table. This method is part of the RootQueryBuilder and is used to start building aggregation queries. ```typescript const qb = createQueryBuilder({ ... }); const aggregateQuery = qb.aggregateFrom('users'); ``` -------------------------------- ### Create Insert Query - TypeScript Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.RootQueryBuilder Initializes an InsertQueryBuilder for a specified table. This method is used to start building insert operations for new data into a table. ```typescript const qb = createQueryBuilder({ ... }); const insertQuery = qb.insertInto('users'); ``` -------------------------------- ### Insert New Customer Data Source: https://webbeetechnologies.github.io/taylordb/index This example demonstrates inserting a new record into the 'customers' table. It uses the `values` method to provide the data for the new customer, including 'firstName' and 'lastName'. ```typescript const newCustomer = await qb .insertInto('customers') .values({ firstName: 'Jane', lastName: 'Doe', }) .execute(); ``` -------------------------------- ### Where Clause - Simple Condition Source: https://webbeetechnologies.github.io/taylordb/classes/where-query-builder.FilterableQueryBuilder This example demonstrates how to add a simple 'where' clause to filter users by their name. ```APIDOC ## SELECT FROM users with WHERE clause ### Description Filters the query results to include only users matching a specific name. ### Method SELECT (implicitly) ### Endpoint /users ### Parameters #### Query Parameters - **name** (string) - Required - The name to filter users by. ### Request Example ```javascript const users = await qb.selectFrom('users').where('name', '=', 'John Doe').execute(); ``` ### Response #### Success Response (200) - **users** (array) - An array of user objects matching the filter. #### Response Example ```json { "users": [ { "id": 1, "name": "John Doe", "email": "john.doe@example.com" } ] } ``` ``` -------------------------------- ### Where Clause - Cross-Filter (hasAnyOf) Source: https://webbeetechnologies.github.io/taylordb/classes/where-query-builder.FilterableQueryBuilder This example demonstrates filtering users based on whether their 'posts' property contains any published posts. ```APIDOC ## SELECT FROM users with Cross-Filter (hasAnyOf) ### Description Filters the query results to include users who have at least one post where 'isPublished' is true. ### Method SELECT (implicitly) ### Endpoint /users ### Parameters #### Query Parameters - **posts** (array) - Required - Filters users based on their associated posts. - **isPublished** (boolean) - Required - Condition for posts to be considered published. ### Request Example ```javascript const users = await qb.selectFrom('users').where('posts', 'hasAnyOf', (qb) => qb.where('isPublished', '=', true)).execute(); ``` ### Response #### Success Response (200) - **users** (array) - An array of user objects matching the filter. #### Response Example ```json { "users": [ { "id": 1, "name": "John Doe", "email": "john.doe@example.com" } ] } ``` ``` -------------------------------- ### Create Update Query - TypeScript Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.RootQueryBuilder Initializes an UpdateQueryBuilder for a specified table. This method is used to start building update operations for existing data in a table. ```typescript const qb = createQueryBuilder({ ... }); const updateQuery = qb.update('users'); ``` -------------------------------- ### Create Delete Query - TypeScript Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.RootQueryBuilder Initializes a DeleteQueryBuilder for a specified table. This method is used to start building delete operations for rows within a table. ```typescript const qb = createQueryBuilder({ ... }); const deleteQuery = qb.deleteFrom('users'); ``` -------------------------------- ### Including related posts for users Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.QueryBuilder Retrieves user data along with their associated 'posts'. This example demonstrates the basic usage of the 'with' method to include linked records. ```typescript const usersWithPosts = await qb .selectFrom('users') .select(['id', 'name']) .with(['posts']) // Assuming 'posts' is a link field on the 'users' table .execute(); ``` -------------------------------- ### Where Clause - Nested Conditions (OR) Source: https://webbeetechnologies.github.io/taylordb/classes/where-query-builder.FilterableQueryBuilder This example shows how to use nested 'where' clauses with an 'orWhere' condition to filter users by name OR email. ```APIDOC ## SELECT FROM users with Nested WHERE (OR) ### Description Filters the query results to include users whose name is 'John Doe' OR whose email is 'john.doe@example.com'. ### Method SELECT (implicitly) ### Endpoint /users ### Parameters #### Query Parameters - **name** (string) - Required - The name to filter users by. - **email** (string) - Required - The email to filter users by. ### Request Example ```javascript const users = await qb.selectFrom('users').where((qb) => qb.where('name', '=', 'John Doe').orWhere('email', '=', 'john.doe@example.com')).execute(); ``` ### Response #### Success Response (200) - **users** (array) - An array of user objects matching the filter. #### Response Example ```json { "users": [ { "id": 1, "name": "John Doe", "email": "john.doe@example.com" } ] } ``` ``` -------------------------------- ### Including filtered related posts for users Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.QueryBuilder Retrieves user data and includes only the 'posts' that are published. This example shows how to apply conditions to the related data being included using a subquery within 'with'. ```typescript const usersWithPublishedPosts = await qb .selectFrom('users') .select(['id', 'name']) .with({ posts: (qb) => qb.select(['title', 'content']).where('isPublished', '=', true), }) .execute(); ``` -------------------------------- ### RootQueryBuilder Constructor Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.RootQueryBuilder Initializes a new RootQueryBuilder instance. This is the main entry point for all query operations. ```APIDOC ## Constructors ### constructor * `new RootQueryBuilder(config: { apiKey: string; baseUrl: string }): RootQueryBuilder` #### Type Parameters * `DB` extends `AnyDB` #### Parameters * `config` (`{ apiKey: string; baseUrl: string }`) - Configuration object containing API key and base URL. #### Returns * `RootQueryBuilder` - A new instance of `RootQueryBuilder`. ``` -------------------------------- ### SubscriptionManager Constructor Source: https://webbeetechnologies.github.io/taylordb/classes/subscription-manager.SubscriptionManager Initializes a new instance of the SubscriptionManager class. It requires an executor, and a configuration object containing apiKey and baseUrl, with optional clientId and timeZone. ```APIDOC ## Constructor SubscriptionManager ### Description Initializes a new instance of the SubscriptionManager class. ### Method constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "executor": "", "config": { "apiKey": "your_api_key", "baseUrl": "https://your.taylordb.url", "clientId": "optional_client_id", "timeZone": "UTC" } } ``` ### Response #### Success Response (200) Returns an instance of SubscriptionManager. #### Response Example ```json { "instance": "" } ``` ``` -------------------------------- ### RootQueryBuilder Methods Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.RootQueryBuilder Provides methods to initiate different types of query builders. ```APIDOC ## Methods ### aggregateFrom * `aggregateFrom(tableName: TableName): AggregationQueryBuilder` Creates a new aggregation query builder for the specified table. #### Type Parameters * `TableName` extends `string` #### Parameters * `tableName` (`TableName`) - The name of the table to aggregate from. #### Returns * `AggregationQueryBuilder` - A new `AggregationQueryBuilder` instance. #### Example ```javascript const qb = createQueryBuilder({ ... }); const aggregateQuery = qb.aggregateFrom('users'); ``` ### batch * `batch(builders: TBuilders): AreAllBuildersSubscribable extends true ? BatchQueryBuilder : Omit, "subscribe">` Creates a new batch query builder to execute multiple queries concurrently. #### Type Parameters * `TBuilders` extends `readonly AnyQueryBuilder[]` #### Parameters * `builders` (`TBuilders`) - An array of query builders to execute in a batch. #### Returns * `BatchQueryBuilder` or `Omit, "subscribe">` - A new `BatchQueryBuilder` instance. #### Example ```javascript const qb = createQueryBuilder({ ... }); const batchQuery = qb.batch([ qb.selectFrom('users').select(['id', 'name']), qb.insertInto('users').values({ name: 'New User' }), ]); const [users, newUser] = await batchQuery.execute(); ``` ### deleteFrom * `deleteFrom(tableName: TableName): DeleteQueryBuilder` Creates a new delete query builder for the specified table. #### Type Parameters * `TableName` extends `string` #### Parameters * `tableName` (`TableName`) - The name of the table to delete from. #### Returns * `DeleteQueryBuilder` - A new `DeleteQueryBuilder` instance. #### Example ```javascript const qb = createQueryBuilder({ ... }); const deleteQuery = qb.deleteFrom('users'); ``` ### insertInto * `insertInto(into: TableName): InsertQueryBuilder` Creates a new insert query builder for the specified table. #### Type Parameters * `TableName` extends `string` #### Parameters * `into` (`TableName`) - The name of the table to insert into. #### Returns * `InsertQueryBuilder` - A new `InsertQueryBuilder` instance. #### Example ```javascript const qb = createQueryBuilder({ ... }); const insertQuery = qb.insertInto('users'); ``` ### selectFrom * `selectFrom(from: TableName): QueryBuilder` Creates a new select query builder for the specified table. #### Type Parameters * `TableName` extends `string` #### Parameters * `from` (`TableName`) - The name of the table to select from. #### Returns * `QueryBuilder` - A new `QueryBuilder` instance. #### Example ```javascript const qb = createQueryBuilder({ ... }); const userQuery = qb.selectFrom('users'); ``` ### update * `update(tableName: TableName): UpdateQueryBuilder` Creates a new update query builder for the specified table. #### Type Parameters * `TableName` extends `string` #### Parameters * `tableName` (`TableName`) - The name of the table to update. #### Returns * `UpdateQueryBuilder` - A new `UpdateQueryBuilder` instance. #### Example ```javascript const qb = createQueryBuilder({ ... }); const updateQuery = qb.update('users'); ``` ``` -------------------------------- ### BatchQueryBuilder Constructor and Methods - TypeScript Source: https://webbeetechnologies.github.io/taylordb/classes/batch-query-builder.BatchQueryBuilder Demonstrates the constructor for BatchQueryBuilder, which accepts an array of query builders and an executor. It also showcases the compile, execute, and subscribe methods for managing batch queries. ```typescript /** * A query builder for executing multiple queries in a single batch. * @template TBuilders An array of query builders to execute. */ new BatchQueryBuilder( builders: TBuilders, executor: Executor ): BatchQueryBuilder /** * Compiles the batch query into a single query string and variables. * @returns An object containing the query string and variables. */ compile(): { query: string; variables: Record } /** * Executes the batch query. * @returns A promise that resolves with an array of the results from each query in the batch. */ execute(): Promise<{ readonly [K in keyof TBuilders]: InferExecuteResult; }> ``` -------------------------------- ### AggregationQueryBuilder Constructor Source: https://webbeetechnologies.github.io/taylordb/classes/aggregation-query-builder.AggregationQueryBuilder Initializes a new AggregationQueryBuilder instance. It requires an AggregateNode and an Executor to perform queries. ```typescript new AggregationQueryBuilder( node: AggregateNode, executor: Executor ) ``` -------------------------------- ### SubscriptionManager Constructor - TypeScript Source: https://webbeetechnologies.github.io/taylordb/classes/subscription-manager.SubscriptionManager Initializes a new instance of the SubscriptionManager class. It requires an Executor instance and a configuration object containing API key and base URL. Optional parameters include clientId and timeZone. ```TypeScript new SubscriptionManager( executor: Executor, config: { apiKey: string; baseUrl: string; clientId?: string; timeZone?: string; } ): SubscriptionManager ``` -------------------------------- ### Initialize Query Builder with TaylorDB Types Source: https://webbeetechnologies.github.io/taylordb/index Demonstrates how to create a query builder instance, specifying the generic type for your database schema. It requires your TaylorDB base URL and API key for authentication. ```typescript import { createQueryBuilder } from '@taylordb/query-builder'; import { TaylorDatabase } from './taylorclient.types'; const qb = createQueryBuilder({ baseUrl: 'YOUR_TAYLORDB_BASE_URL', apiKey: 'YOUR_TAYLORDB_API_KEY', }); ``` -------------------------------- ### InsertQueryBuilder Class Source: https://webbeetechnologies.github.io/taylordb/classes/insert-query-builder.InsertQueryBuilder The InsertQueryBuilder class provides methods to construct and execute SQL INSERT statements. ```APIDOC ## Class InsertQueryBuilder A query builder for creating new records in the database. #### Type Parameters * DB extends AnyDB The database type. * TableName extends keyof DB The name of the table to insert into. * Selection = { id: number } The type of the selected fields. ### Constructors #### constructor * new InsertQueryBuilder(node: InsertNode, executor: Executor): InsertQueryBuilder ##### Parameters * node: InsertNode * executor: Executor ##### Returns InsertQueryBuilder ### Methods #### _prepareMetadata * _prepareMetadata(): any ##### Returns any #### compile * compile(): { query: string; variables: Record } ##### Returns { query: string; variables: Record } #### execute * execute(): Promise Executes the insert query. ##### Returns Promise A promise that resolves with an array of the selected fields from the inserted records. ##### Example ```javascript const newUsers = await qb .insertInto('users') .values([{ name: 'John Doe' }, { name: 'Jane Doe' }]) .returning(['id', 'name']) .execute(); ``` #### executeTakeFirst * executeTakeFirst(): Promise Executes the insert query and returns the first result. ##### Returns Promise A promise that resolves with the first inserted record, or `null` if no records were inserted. ##### Example ```javascript const newUser = await qb .insertInto('users') .values({ name: 'John Doe' }) .returning(['id', 'name']) .executeTakeFirst(); ``` #### returning * returning[]>(fields: TFields): InsertQueryBuilder> The fields to return after the insert operation. ##### Type Parameters * const TFields extends readonly NonLinkColumnNames[] ##### Parameters * fields: TFields An array of field names to return. ##### Returns InsertQueryBuilder> The `InsertQueryBuilder` instance for chaining. ##### Example ```javascript const newUser = await qb .insertInto('users') .values({ name: 'John Doe' }) .returning(['id', 'name']) .executeTakeFirst(); ``` #### values * values(values: Insertable | Insertable[]): InsertQueryBuilder The values to insert into the table. ##### Parameters * values: Insertable | Insertable[] An object or array of objects representing the records to create. ##### Returns InsertQueryBuilder The `InsertQueryBuilder` instance for chaining. ##### Example: Single Record Insertion ```javascript const newUser = await qb .insertInto('users') .values({ name: 'John Doe', email: 'john.doe@example.com' }) .executeTakeFirst(); ``` ##### Example: Multiple Record Insertion ```javascript const newUsers = await qb .insertInto('users') .values([{ name: 'John Doe' }, { name: 'Jane Doe' }]) .execute(); ``` ``` -------------------------------- ### Executor Class API Source: https://webbeetechnologies.github.io/taylordb/classes/executor.Executor This section covers the constructor and key methods of the Executor class, which is the primary interface for interacting with the TaylorDB backend. ```APIDOC ## Class Executor ### Description The Executor class provides methods to interact with the TaylorDB API, including executing compiled queries, sending raw requests, and subscribing to real-time data updates. ### Constructors #### constructor(baseUrl: string, apiKey: string) ##### Description Initializes a new instance of the Executor class. ##### Parameters - **baseUrl** (string) - Required - The base URL of the TaylorDB API endpoint. - **apiKey** (string) - Required - The API key for authentication. ##### Returns - Executor - An instance of the Executor class. ### Methods #### execute(builder: Compilable): Promise ##### Description Executes a compiled query builder against the TaylorDB API. ##### Type Parameters - **T**: The expected type of the result. ##### Parameters - **builder** (Compilable) - Required - The compilable query builder object. ##### Returns - Promise - A promise that resolves with the query result. #### rawRequest(query: string, variables: Record, headers?: Record): Promise ##### Description Sends a raw GraphQL query to the TaylorDB API with specified variables and optional headers. ##### Type Parameters - **T**: The expected type of the result. ##### Parameters - **query** (string) - Required - The raw GraphQL query string. - **variables** (Record) - Required - An object containing variables for the query. - **headers** (Record) - Optional - An object containing custom headers for the request. ##### Returns - Promise - A promise that resolves with the query result. #### subscribe(builders: AnySubscribableQueryBuilder[], callback: (result: TResult) => void): Promise<{ unsubscribe: () => Promise }> ##### Description Subscribes to real-time updates for one or more query builders. The callback function is invoked whenever new data is available. ##### Type Parameters - **TResult**: The expected type of the result for the subscribed queries. ##### Parameters - **builders** (AnySubscribableQueryBuilder[]) - Required - An array of subscribable query builder objects. - **callback** ((result: TResult) => void) - Required - The function to be called with the updated results. ##### Returns - Promise<{ unsubscribe: () => Promise }> - A promise that resolves with an object containing an `unsubscribe` function to stop receiving updates. ``` -------------------------------- ### UpdateQueryBuilder Class Source: https://webbeetechnologies.github.io/taylordb/classes/update-query-builder.UpdateQueryBuilder Details of the UpdateQueryBuilder class, including its type parameters, hierarchy, constructors, properties, and methods. ```APIDOC ## Class UpdateQueryBuilder A query builder for updating records in the database. #### Type Parameters * DB extends AnyDB The database type. * TableName extends keyof DB The name of the table to update. #### Hierarchy * FilterableQueryBuilder * UpdateQueryBuilder ### Constructors #### constructor * `new UpdateQueryBuilder(node: UpdateNode, executor: Executor): UpdateQueryBuilder` #### Type Parameters * DB extends AnyDB * TableName extends string | number | symbol #### Parameters * `node`: UpdateNode * `executor`: Executor #### Returns UpdateQueryBuilder ### Properties #### `_executor` * `_executor`: Executor #### `_node` * `_node`: FilterableNode ### Methods #### `_prepareMetadata()` * `_prepareMetadata(): any` #### Returns `any` #### `compile()` * `compile(): { query: string; variables: Record }` #### Returns `{ query: string; variables: Record }` #### `execute()` * `execute(): Promise<{ affectedRecords: number }>` Executes the update query. #### Returns `Promise<{ affectedRecords: number }>` A promise that resolves with the number of affected records. #### Example ```typescript const { affectedRecords } = await qb .update('users') .set({ name: 'New Name' }) .where('id', '=', 1) .execute(); ``` #### `orWhere(field: TField, operator: TOperator, value: DB[TableName][TField] extends LinkColumnType ? (qb: FilterableQueryBuilder ? any[any]["linkedTo"] : never>) => FilterableQueryBuilder ? any[any]["linkedTo"] : never> | any[any]["filters"][TOperator] : DB[TableName][TField]["filters"][TOperator]): this` Adds an `orWhere` clause to the query. This is similar to `where`, but the condition will be joined with `OR`. #### Type Parameters * `TField` extends string * `TOperator` extends string | number | symbol #### Parameters * `field`: TField - The field to filter on. * `operator`: TOperator - The filter operator. * `value`: DB[TableName][TField] extends LinkColumnType ? (qb: FilterableQueryBuilder ? any[any]["linkedTo"] : never>) => FilterableQueryBuilder ? any[any]["linkedTo"] : never> | any[any]["filters"][TOperator] : DB[TableName][TField]["filters"][TOperator] The value to filter by. #### Returns `this` The query builder instance for chaining. #### Example ```typescript const users = await qb .selectFrom('users') .where('name', '=', 'John Doe') .orWhere('name', '=', 'Jane Doe') .execute(); ``` #### `orWhere) => WhereQueryBuilder>(column: C): this` Adds an `orWhere` clause to the query. This is similar to `where`, but the condition will be joined with `OR`. #### Type Parameters * `C` extends (builder: WhereQueryBuilder) => WhereQueryBuilder #### Parameters * `column`: C #### Returns `this` The query builder instance for chaining. #### Example ```typescript const users = await qb .selectFrom('users') .where('name', '=', 'John Doe') .orWhere('name', '=', 'Jane Doe') .execute(); ``` #### `set(values: Updatable): UpdateQueryBuilder` * `set(values: Updatable): UpdateQueryBuilder` Sets the values to update for the records that match the where clauses. #### Parameters * `values`: Updatable - An object containing the fields and their new values. #### Returns `UpdateQueryBuilder` The `UpdateQueryBuilder` instance for chaining. #### Example ```typescript const { affectedRecords } = await qb .update('users') .set({ name: 'New Name' }) .where('id', '=', 1) .execute(); ``` #### `where(field: TField, operator: TOperator, value: DB[TableName][TField] extends LinkColumnType ? (any[any]["filters"][TOperator] | ((qb: FilterableQueryBuilder ? any[any]["linkedTo"] : never>) => FilterableQueryBuilder ? any[any]["linkedTo"] : never>)) : DB[TableName][TField]["filters"][TOperator]): this` * `where(field: TField, operator: TOperator, value: DB[TableName][TField] extends LinkColumnType ? (any[any]["filters"][TOperator] | ((qb: FilterableQueryBuilder ? any[any]["linkedTo"] : never>) => FilterableQueryBuilder ? any[any]["linkedTo"] : never>)) : DB[TableName][TField]["filters"][TOperator]): this` Adds a `where` clause to the query. This can be a simple condition, a nested query, or a cross-filter on a linked table. #### Parameters * `field`: TField * `operator`: TOperator * `value`: DB[TableName][TField] extends LinkColumnType ? (any[any]["filters"][TOperator] | ((qb: FilterableQueryBuilder ? any[any]["linkedTo"] : never>) => FilterableQueryBuilder ? any[any]["linkedTo"] : never>)) : DB[TableName][TField]["filters"][TOperator] #### Returns `this` ``` -------------------------------- ### Execute Delete Query - JavaScript Source: https://webbeetechnologies.github.io/taylordb/classes/delete-query-builder.DeleteQueryBuilder Executes a delete query constructed by the DeleteQueryBuilder. It returns a promise that resolves with the number of affected records. Ensure the query builder instance (`qb`) is properly initialized with a delete statement and any necessary `where` or `orWhere` clauses. ```javascript const { affectedRecords } = await qb .deleteFrom('users') .where('id', '=', 1) .execute(); ``` -------------------------------- ### Select Data from Customers Table Source: https://webbeetechnologies.github.io/taylordb/index Shows how to select specific fields ('firstName', 'lastName') from the 'customers' table. It includes filtering by 'firstName', sorting by 'lastName' in ascending order, and paginating results (page 1, 10 items per page). ```typescript const customers = await qb .selectFrom('customers') .select(['firstName', 'lastName']) .where('firstName', '=', 'John') .orderBy('lastName', 'asc') .paginate(1, 10) .execute(); ``` -------------------------------- ### Create Batch Query - TypeScript Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.RootQueryBuilder Creates a BatchQueryBuilder to execute multiple query builders in a single batch operation. It takes an array of query builders and returns a batch query instance. The return type depends on whether all builders are subscribable. ```typescript const qb = createQueryBuilder({ ... }); const batchQuery = qb.batch([ qb.selectFrom('users').select(['id', 'name']), qb.insertInto('users').values({ name: 'New User' }), ]); const [users, newUser] = await batchQuery.execute(); ``` -------------------------------- ### SELECT ALL FIELDS API Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.QueryBuilder Selects all available fields from the table for the query results. ```APIDOC ## SELECT ALL FIELDS API ### Description Selects all fields from the table. ### Method `selectAll(): QueryBuilder }, >` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const users = await qb .selectFrom('users') .selectAll() .execute(); ``` ### Response #### Success Response (200) A new `QueryBuilder` instance with all fields selected. #### Response Example (Query builder instance) ``` -------------------------------- ### Execute Batch Queries Source: https://webbeetechnologies.github.io/taylordb/index Demonstrates executing multiple queries (a select and an insert) in a single batch request for efficiency. The results are returned as a tuple corresponding to the order of the queries in the batch. ```typescript const [customers, newCustomer] = await qb .batch([ qb.selectFrom('customers').select(['firstName', 'lastName']), qb.insertInto('customers').values({ firstName: 'John', lastName: 'Doe' }), ]) .execute(); ``` -------------------------------- ### Execute Select Query, Take First - QueryBuilder (TypeScript) Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.QueryBuilder Executes the select query and returns only the first matching record. If no records are found, it resolves with `null`. Useful for fetching a single specific record. ```typescript const user = await qb .selectFrom('users') .where('id', '=', 1) .select(['id', 'name']) .executeTakeFirst(); ``` -------------------------------- ### Create Select Query - TypeScript Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.RootQueryBuilder Initializes a QueryBuilder (select query builder) for a specified table. This is the primary method for constructing select statements. ```typescript const qb = createQueryBuilder({ ... }); const userQuery = qb.selectFrom('users'); ``` -------------------------------- ### SubscriptionManager Subscribe Method Source: https://webbeetechnologies.github.io/taylordb/classes/subscription-manager.SubscriptionManager Subscribes to data changes with the provided metadata and a callback function. It returns a Promise that resolves with an unsubscribe function. ```APIDOC ## Method subscribe ### Description Subscribes to data changes. It takes an array of metadata and a callback function. The callback is invoked with the results of the subscription. The method returns a Promise that resolves with an object containing an `unsubscribe` function. ### Method subscribe ### Endpoint N/A (This is a class method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **metadatas** (any[]) - Required - An array of metadata objects defining the subscription. - **callback** ((...results: TResult[]) => void) - Required - A function to be called with the subscription results. ### Request Example ```json { "metadatas": [ { "query": "SELECT * FROM my_table" }, { "query": "SELECT * FROM another_table" } ], "callback": "(data1, data2) => { console.log(data1, data2); }" } ``` ### Response #### Success Response (200) - **unsubscribe** (() => Promise) - A function to cancel the subscription. #### Response Example ```json { "unsubscribe": "() => Promise" } ``` ``` -------------------------------- ### Compile Update Query - TypeScript Source: https://webbeetechnologies.github.io/taylordb/classes/update-query-builder.UpdateQueryBuilder Demonstrates compiling an update query into its raw SQL string and associated variables. This is useful for inspecting the generated query before execution or for manual execution in certain scenarios. ```typescript const compiledQuery = qb.compile(); console.log(compiledQuery.query); console.log(compiledQuery.variables); ``` -------------------------------- ### Select all fields Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.QueryBuilder Selects all available fields from the table. This method returns a new QueryBuilder instance with all fields included in the selection. It's a convenient way to retrieve all columns without explicitly listing them. ```typescript const users = await qb .selectFrom('users') .selectAll() .execute(); ``` -------------------------------- ### Aggregate User Statistics Source: https://webbeetechnologies.github.io/taylordb/classes/aggregation-query-builder.AggregationQueryBuilder Performs aggregations on the 'users' table, counting the number of users and calculating the average and sum of their ages. This demonstrates the `withAggregates` method for defining aggregation functions. ```typescript const userStats = await qb .aggregateFrom('users') .withAggregates({ id: ['count'], age: ['avg', 'sum'], }) .execute(); ``` -------------------------------- ### AggregationQueryBuilder execute Method Source: https://webbeetechnologies.github.io/taylordb/classes/aggregation-query-builder.AggregationQueryBuilder Executes the configured aggregation query and returns a promise that resolves with the results. The results are typed as an array of AggregateRecord. ```typescript const userCounts = await qb .aggregateFrom('users') .groupBy('role') .withAggregates({ id: ['count'] }) .execute(); ``` -------------------------------- ### InsertQueryBuilder: Execute Insert and Return All Records Source: https://webbeetechnologies.github.io/taylordb/classes/insert-query-builder.InsertQueryBuilder Executes an insert query and returns all newly inserted records with specified fields. This method is part of the InsertQueryBuilder and is used for bulk insertions. ```typescript const newUsers = await qb .insertInto('users') .values([{ name: 'John Doe' }, { name: 'Jane Doe' }]) .returning(['id', 'name']) .execute(); ``` -------------------------------- ### Subscribe to aggregation query results Source: https://webbeetechnologies.github.io/taylordb/classes/aggregation-query-builder.AggregationQueryBuilder Subscribes to real-time updates of an aggregation query. A callback function is provided to handle incoming results, and an unsubscribe function is returned to stop listening. ```typescript const unsubscribe = qb .aggregateFrom('users') .groupBy('role') .withAggregates({ id: ['count'] }) .subscribe((userCounts) => { console.log('User counts by role:', userCounts); }); // To stop listening for updates unsubscribe(); ``` -------------------------------- ### Generate TaylorDB Schema Types Source: https://webbeetechnologies.github.io/taylordb/index This command uses the TaylorDB CLI to generate a TypeScript types file from your TaylorDB schema. This file is essential for enabling type safety and autocompletion within the query builder. ```bash npx @taylordb/cli generate-schema ``` -------------------------------- ### Execute Update Query - TypeScript Source: https://webbeetechnologies.github.io/taylordb/classes/update-query-builder.UpdateQueryBuilder Demonstrates how to execute an update query using the UpdateQueryBuilder. This involves setting new values for specified fields and applying a 'where' clause to filter which records to update. The result includes the number of affected records. ```typescript const { affectedRecords } = await qb .update('users') .set({ name: 'New Name' }) .where('id', '=', 1) .execute(); ``` -------------------------------- ### Perform Aggregation Query Source: https://webbeetechnologies.github.io/taylordb/index Illustrates performing an aggregation query on the 'customers' table. It groups results by 'firstName' (ascending) and 'lastName' (descending), and calculates aggregate functions (count and sum) for the 'id' field. ```typescript const aggregates = await qb .aggregateFrom('customers') .groupBy('firstName', 'asc') .groupBy('lastName', 'desc') .withAggregates({ id: ['count', 'sum'], }) .execute(); ``` -------------------------------- ### Execute Select Query - QueryBuilder (TypeScript) Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.QueryBuilder Executes the constructed select query and returns a promise that resolves with an array of the selected records. This is a fundamental method for retrieving data. ```typescript const users = await qb .selectFrom('users') .select(['id', 'name']) .execute(); ``` -------------------------------- ### Filtering Parameters Source: https://webbeetechnologies.github.io/taylordb/classes/delete-query-builder.DeleteQueryBuilder Defines the parameters used for filtering query results. This includes specifying the field, operator, and value for the filter. ```APIDOC ## WHERE CLAUSE PARAMETERS ### Description These parameters are used to define filtering conditions within a query. ### Parameters #### Query Parameters - **field** (TField) - Required - The field to filter on. - **operator** (TOperator) - Required - The filter operator. - **value** (DB[TableName][TField] extends LinkColumnType ? any[any]["filters"][TOperator] | ((qb: FilterableQueryBuilder ? any[any]["linkedTo"] : never>) => FilterableQueryBuilder ? any[any]["linkedTo"] : never>) : DB[TableName][TField]["filters"][TOperator]) - Required - The value to filter by. ### Returns this The query builder instance for chaining. ### Example ```javascript const users = await qb.selectFrom('users').where('name', '=', 'John Doe').execute(); ``` ### Example ```javascript const users = await qb.selectFrom('users').where((qb) => qb.where('name', '=', 'John Doe').orWhere('email', '=', 'john.doe@example.com')).execute(); ``` ### Example ```javascript const users = await qb.selectFrom('users').where('posts', 'hasAnyOf', (qb) => qb.where('isPublished', '=', true)).execute(); ``` ``` -------------------------------- ### PAGINATION API Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.QueryBuilder Paginates the results of a query, allowing you to specify the page number and the number of records per page. ```APIDOC ## PAGINATION API ### Description Paginates the results. ### Method `paginate(page: number, limit: number): QueryBuilder` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const users = await qb .selectFrom('users') .select(['id', 'name']) .paginate(2, 25) // Retrieves page 2 with 25 records per page .execute(); ``` ### Response #### Success Response (200) A new `QueryBuilder` instance with pagination applied. #### Response Example (Query builder instance) ``` -------------------------------- ### SELECT FIELDS API Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.QueryBuilder Selects a specific set of fields from the table for the query results. ```APIDOC ## SELECT FIELDS API ### Description Selects a set of fields from the table. ### Method `select[]>(fields: TFields): QueryBuilder>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const users = await qb .selectFrom('users') .select(['id', 'name']) .execute(); ``` ### Response #### Success Response (200) A new `QueryBuilder` instance with the specified fields selected. #### Response Example (Query builder instance) ``` -------------------------------- ### SelectionBuilder Class Source: https://webbeetechnologies.github.io/taylordb/classes/selection-builder.SelectionBuilder The SelectionBuilder is a class used internally by the QueryBuilder's `with` method to construct subqueries on linked records. ```APIDOC ## Class SelectionBuilder A builder for creating subqueries on linked records. This is used internally by the `with` method on the `QueryBuilder`. #### Type Parameters * DB extends AnyDB The database type. * CurrentTableName extends keyof DB The name of the table the selection is starting from. ### Constructor `new SelectionBuilder(executor: Executor): SelectionBuilder` #### Parameters * `executor` (Executor) - The executor instance. ### Properties * `_executor` (Executor) - Internal executor instance. ### Methods * `useLink(from: LinkName): QueryBuilder<...>` Creates a new query builder for a linked table. #### Type Parameters * `LinkName` extends `string` - The name of the link. #### Parameters * `from` (LinkName) - The name of the link field to select from. #### Returns A new `QueryBuilder` instance for the linked table. ``` -------------------------------- ### Paginate query results Source: https://webbeetechnologies.github.io/taylordb/classes/aggregation-query-builder.AggregationQueryBuilder Applies pagination to the query results, allowing retrieval of data in chunks. It requires specifying the page number and the number of records per page (limit). ```typescript qb.paginate(page, limit); ``` -------------------------------- ### Querying users with posts having specific conditions Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.QueryBuilder Selects users from the 'users' table who have posts that meet a certain criteria (e.g., published). This showcases cross-table filtering using 'hasAnyOf'. ```typescript const users = await qb .selectFrom('users') .where('posts', 'hasAnyOf', (qb) => qb.where('isPublished', '=', true)) .execute(); ``` -------------------------------- ### Querying users with name or email conditions Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.QueryBuilder Selects users from the 'users' table based on either their name or email address. This demonstrates using 'orWhere' for combined conditions. ```typescript const users = await qb .selectFrom('users') .where((qb) => qb.where('name', '=', 'John Doe').orWhere('email', '=', 'john.doe@example.com') ) .execute(); ``` -------------------------------- ### InsertQueryBuilder: Provide Values for Insertion (Multiple Records) Source: https://webbeetechnologies.github.io/taylordb/classes/insert-query-builder.InsertQueryBuilder Specifies multiple records' data to be inserted into the database table. This method accepts an array of objects, each representing a record. ```typescript const newUsers = await qb .insertInto('users') .values([{ name: 'John Doe' }, { name: 'Jane Doe' }]) .execute(); ``` -------------------------------- ### InsertQueryBuilder: Execute Insert and Return First Record Source: https://webbeetechnologies.github.io/taylordb/classes/insert-query-builder.InsertQueryBuilder Executes an insert query and returns only the first newly inserted record with specified fields. This is useful for single record insertions where only the first result is needed. ```typescript const newUser = await qb .insertInto('users') .values({ name: 'John Doe' }) .returning(['id', 'name']) .executeTakeFirst(); ``` -------------------------------- ### WHERE Clause Methods Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.QueryBuilder The `where` method allows you to add filtering conditions to your queries. It supports simple equality checks, OR conditions, and cross-table filtering using `hasAnyOf`. ```APIDOC ## WHERE Clause Methods ### Description Adds a `where` clause to the query. This can be a simple condition, a nested query, or a cross-filter on a linked table. ### Method `where` ### Parameters * **column** (function or string, operator, value) - Required - The condition to apply. Can be a string for direct column comparison, or a function for nested/complex conditions. ### Examples #### Simple Equality ```javascript const users = await qb .selectFrom('users') .where('name', '=', 'John Doe') .execute(); ``` #### OR Conditions ```javascript const users = await qb .selectFrom('users') .where((qb) => qb.where('name', '=', 'John Doe').orWhere('email', '=', 'john.doe@example.com') ) .execute(); ``` #### Cross-Table Filtering (hasAnyOf) ```javascript const users = await qb .selectFrom('users') .where('posts', 'hasAnyOf', (qb) => qb.where('isPublished', '=', true)) .execute(); ``` ``` -------------------------------- ### WITH Clause Method Source: https://webbeetechnologies.github.io/taylordb/classes/query-builder.QueryBuilder The `with` method is used to eagerly load related records from linked tables. It can fetch all fields from related records or allow custom subqueries for specific fields. ```APIDOC ## WITH Clause Method ### Description Includes related records from a linked table. This method has two overloads: 1. Pass an array of link field names to include all fields from the related records. 2. Pass an object to specify subqueries for each link field. ### Method `with` ### Parameters * **relations** (string[] or object) - Required - The relations to include. Can be an array of relation names or an object mapping relation names to subquery builders. ### Examples #### Including All Fields from a Relation ```javascript const usersWithPosts = await qb .selectFrom('users') .select(['id', 'name']) .with(['posts']) // Assuming 'posts' is a link field on the 'users' table .execute(); ``` #### Including Specific Fields with a Subquery ```javascript const usersWithPublishedPosts = await qb .selectFrom('users') .select(['id', 'name']) .with({ posts: (qb) => qb.select(['title', 'content']).where('isPublished', '=', true), }) .execute(); ``` ``` -------------------------------- ### Query Builder - WITH AGGREGATES Source: https://webbeetechnologies.github.io/taylordb/classes/aggregation-query-builder.AggregationQueryBuilder The `withAggregates` method is used to specify aggregation functions to be performed on the selected data. ```APIDOC ## withAggregates ### Description Specifies the aggregations to perform on the query results. ### Method `withAggregates` ### Parameters #### aggregates - **aggregates** (object) - Required - An object where keys are field names and values are arrays of aggregation functions (e.g., 'count', 'avg', 'sum'). ### Returns `AggregationQueryBuilder` ### Example ```javascript const userStats = await qb .aggregateFrom('users') .withAggregates({ id: ['count'], age: ['avg', 'sum'], }) .execute(); ``` ``` -------------------------------- ### SubscriptionManager Subscribe Method - TypeScript Source: https://webbeetechnologies.github.io/taylordb/classes/subscription-manager.SubscriptionManager Subscribes to data updates. It takes an array of metadata and a callback function that processes the results. It returns a Promise with an unsubscribe function to stop receiving updates. ```TypeScript subscribe( metadatas: any[], callback: (...results: TResult[]) => void, ): Promise<{ unsubscribe: () => Promise }> ```