UNPKG

@datastax/astra-db-ts

Version:
1,365 lines (1,334 loc) 688 kB
// Copyright DataStax, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. declare function astraDbTsRequiresTypeScriptV5OrGreater<const AstraDbTsRequiresTypeScriptV5OrGreater>(_: AstraDbTsRequiresTypeScriptV5OrGreater): void; import { BigNumber } from 'bignumber.js'; /* Excluded from this release type: $CustomInspect */ /** * @public */ export declare const $DeserializeForCollection: unique symbol; /** * @public */ export declare const $DeserializeForTable: unique symbol; declare const $ERROR: unique symbol; /** * @public */ export declare const $SerializeForCollection: unique symbol; /** * @public */ export declare const $SerializeForTable: unique symbol; /* Excluded from this release type: __parsed */ /** * ##### Overview * * Represents some lazy, abstract iterable cursor over any arbitrary data, which may or may not be paginated. * * > **⚠️Warning:** This shouldn't be directly instantiated, but rather spawned via {@link Collection.findAndRerank}/{@link Collection.find}, or their {@link Table} alternatives. * * --- * * ##### Typing * * > **✏️Note:** You may generally treat the cursor as if it were typed simply as `AbstractCursor<T>`. * > * > If you're using a projection, it is heavily recommended to provide an explicit type representing the type of the document after projection. * * In full, the cursor is typed as `AbstractCursor<T, TRaw>`, where * - `T` is the type of the mapped records, and * - `TRaw` is the type of the raw records before any mapping. * * If no mapping function is provided, `T` and `TRaw` will be the same type. Mapping is done using the {@link AbstractCursor.map} method. * * `TRaw` is currently only publicly exposed in `consumeBuffer()`. * * @see CollectionFindCursor * @see CollectionFindAndRerankCursor * @see TableFindCursor * * @public */ export declare abstract class AbstractCursor<T, TRaw extends SomeDoc = SomeDoc> { /* Excluded from this release type: _consumed */ /* Excluded from this release type: _state */ /* Excluded from this release type: _currentPage */ /* Excluded from this release type: _isNextPage */ /* Excluded from this release type: _mapping */ /* Excluded from this release type: _timeoutOptions */ /* Excluded from this release type: __constructor */ /** * ##### Overview * * Gets the current status of the cursor. * * See {@link CursorState} for more information on the possible states, and how they may be transitioned between each other. * * @example * ```ts * const cursor = collection.find({}); * console.log(cursor.state); // 'idle' * * await cursor.next(); * console.log(cursor.state); // 'started' * * cursor.close(); * console.log(cursor.state); // 'closed' * ``` * * @see CursorState */ get state(): CursorState; /** * ##### Overview * * Gets the number of raw records in the buffer. * * Unless the cursor was closed before the buffer was completely read, the total number of records retrieved from the * server is equal to (`consumed()` + `buffered()`). * * @example * ```ts * const cursor = collection.find({}); * console.log(cursor.buffered()); // 0 * * await cursor.next(); // Fetches a page of results * console.log(cursor.buffered()); // Number of records in buffer * ``` * * @returns The number of raw records currently in the buffer. * * @see AbstractCursor.consumed */ buffered(): number; /** * ##### Overview * * Gets the number of records that have been read by the user from the cursor. * * Unless the cursor was closed before the buffer was completely read, the total number of records retrieved from the * server is equal to (`consumed()` + `buffered()`). * * @example * ```ts * const cursor = collection.find({}); * console.log(cursor.consumed()); // 0 * * await cursor.next(); * console.log(cursor.consumed()); // 1 * ``` * * @returns The number of records that have been read from the cursor. * * @see AbstractCursor.buffered */ consumed(): number; /** * ##### Overview * * Consumes up to `max` records from the buffer, or all records if `max` is not provided. * * > **⚠️Warning:** This actually consumes the buffer; it doesn't just peek at it. * * > **🚨Important:** The records returned from this method are not affected by `cursor.map()`. * * @example * ```ts * const cursor = collection.find({}); * await cursor.next(); // Populates the buffer * * // Consume up to 5 records from the buffer * const records = cursor.consumeBuffer(5); * console.log(records.length); // Number of records consumed (up to 5) * * // Consume all remaining records * const remaining = cursor.consumeBuffer(); * ``` * * @param max - The optional max number of records to read from the buffer. * * @returns The records read from the buffer. */ consumeBuffer(max?: number): TRaw[]; /** * ##### Overview * * Closes the cursor. The cursor will be unusable after this method is called, or until {@link AbstractCursor.rewind} is called. * * @example * ```ts * const cursor = collection.find({}); * * // Use the cursor * const doc = await cursor.next(); * * // Close the cursor when done * cursor.close(); * * // Attempting to use a closed cursor * await cursor.next(); // Throws CursorError * ``` * * @see AbstractCursor.rewind - To reset a closed cursor to make it usable again */ close(): void; /** * ##### Overview * * Creates a new cursor with the exact same configuration as the current cursor. * * The new cursor will be in the `'idle'` state, regardless of the state of the current cursor, and will start its own iteration from the beginning, sending new queries to the server, even if the resultant data was already fetched by the original cursor. * * @example * ```ts * const cursor = collection.find({ age: { $gt: 30 } }).sort({ name: 1 }); * * // Clone the cursor before use * const clone1 = cursor.clone(); * const clone2 = cursor.clone(); * * // Each cursor operates independently * const firstResult = await clone1.toArray(); * const firstTwoRecords = await clone2.next(); * * // Original cursor is still usable * for await (const doc of cursor) { * console.log(doc); * } * ``` * * --- * * ##### Cloning vs Rewinding * * Cloning a cursor is different from rewinding it. Cloning creates an independent new cursor with the same configuration as the original, while rewinding resets the current cursor to its initial state. * * See {@link AbstractCursor.rewind} for more information on rewinding. * * @returns A new cursor with the same configuration as the current cursor. * * @see AbstractCursor.rewind */ abstract clone(): this; /** * ##### Overview * * Rewinds the cursor to its uninitialized state, clearing the buffer and any state. * * Any configuration set on the cursor will remain, but iteration will start from the beginning, sending new queries to the server, even if the resultant data was already fetched by the cursor. * * @example * ```ts * const cursor = collection.find({}).sort({ name: 1 }); * * // Read some data * const first = await cursor.next(); * * // Rewind the cursor * cursor.rewind(); * * // Start again from the beginning * const firstAgain = await cursor.next(); * // first and firstAgain are the same record * ``` * * --- * * ##### Rewinding vs Cloning * * Rewinding a cursor is different from cloning it. Cloning creates an independent new cursor with the same state and configuration as the original, while rewinding resets the current cursor to its initial state. * * See {@link AbstractCursor.clone} for more information on cloning. * * @see AbstractCursor.clone */ rewind(): void; /** * ##### Overview * * Map all records using the provided mapping function. Previous mapping functions will be composed with the new * mapping function (new ∘ old). * * > **🚨Important:** This method does **NOT** mutate the cursor; it returns a new cursor with the new mapping function applied. * * > **⚠️Warning:** You may *NOT* provide a projection after a mapping is already provided, to prevent potential type de-sync errors. * * @example * ```ts * const cursor = table.find({ name: 'John' }) * .map(row => row.name); * .map(name => name.toLowerCase()); * * // T is `string` because the mapping function returns a string * const name = await cursor.next(); * name === 'john'; // true * ``` * * @param map - The mapping function to apply to all records. * * @returns A new cursor with the new mapping set. */ abstract map<R>(map: (doc: T) => R): AbstractCursor<R, TRaw>; /** * ##### Overview * * An async iterator that lazily iterates over all records in the cursor. * * > **⚠️Warning:** There'll only be partial results if the cursor has been consumed prior. You may use {@link AbstractCursor.rewind} to reset the cursor. * * --- * * ##### Behavior * * - If the cursor is uninitialized, it will be initialized * - If the consumer `break`s, iteration will stop early * - If the cursor is closed, this method will throw a {@link CursorError} * - It will close the cursor when iteration is complete, even if it was broken early * - If no records are found, no error will be thrown, and the iterator will simply finish * * @example * ```ts * const cursor = collection.find({ age: { $gt: 30 } }); * * // Iterate over all matching records * for await (const doc of cursor) { * console.log(doc); * * if (doc.name === 'John') { * break; // Stop iteration early * } * } * * // Cursor is now closed * console.log(cursor.state); // 'closed' * ``` */ [Symbol.asyncIterator](): AsyncGenerator<T, void, void>; /** * ##### Overview * * Fetches the next record from the cursor. Returns `null` if there are no more records to fetch. * * --- * * ##### Behavior * * - If the cursor is uninitialized, it will be initialized * - If the cursor is closed, this method will return `null` * - It will close the cursor when there are no more records to fetch * - If no records are found, no error will be thrown, and `null` will be returned * * @example * ```ts * const cursor = collection.find({ name: 'John' }); * * // Get the first record * const john = await cursor.next(); * * // Get the next record (or null if no more records) * const nextRecord = await cursor.next(); * * // Exhaust the cursor * let doc; * while ((doc = await cursor.next()) !== null) { * console.log(doc); * } * ``` * * @returns The next record, or `null` if there are no more records. */ next(): Promise<T | null>; /** * ##### Overview * * Tests if there is a next record in the cursor. * * --- * * ##### Behavior * * - If the cursor is uninitialized, it will be initialized * - If the cursor is closed, this method will return `false` * - It will close the cursor when there are no more records to fetch * * @example * ```ts * const cursor = collection.find({ name: 'John' }); * * // Check if there are any records * if (await cursor.hasNext()) { * const john = await cursor.next(); * console.log(john); * } * * // Use in a loop * while (await cursor.hasNext()) { * const record = await cursor.next(); * console.log(record); * } * ``` * * @returns Whether or not there is a next record. */ hasNext(): Promise<boolean>; /** * ##### Overview * * Iterates over all records in the cursor, calling the provided consumer for each record. * * > **⚠️Warning:** There'll only be partial results if the cursor has been consumed prior. You may use {@link AbstractCursor.rewind} to reset the cursor. * * > **✏️Note:** If you get an IDE error "Promise returned from forEach argument is ignored", you may simply ignore it. It is a [known WebStorm bug](https://youtrack.jetbrains.com/issue/WEB-55512/False-positive-for-Promise-returned-from-forEach-argument-is-ignored-with-custom-forEach-function). * * --- * * ##### Behavior * * - If the cursor is uninitialized, it will be initialized * - If the consumer returns `false` or `Promise<false>`, iteration will stop early * - If the cursor is closed, this method will throw a {@link CursorError} * - It will close the cursor when iteration is complete, even if it was stopped early * - If no records are found, no error will be thrown, and the iterator will simply finish * * @example * ```ts * const cursor = collection.find({ age: { $gt: 30 } }); * * // Process all records * await cursor.forEach((doc) => { * console.log(doc); * }); * * // Process records until a condition is met * await cursor.forEach(async (doc) => { * if (await isSpecial(doc)) { * return false; * } * }); * ``` * * @param consumer - The consumer to call for each record. Return `false` to stop iteration. * * @returns A promise that resolves when iteration is complete. */ forEach(consumer: ((doc: T) => boolean | Promise<boolean>) | ((doc: T) => void | Promise<void>)): Promise<void>; /** * ##### Overview * * Returns an array of all matching records in the cursor. * * > **⚠️Warning:** The user should ensure that there is enough memory to store all records in the cursor. * * > **⚠️Warning:** There'll only be partial results if the cursor has been consumed prior. You may use {@link AbstractCursor.rewind} to reset the cursor. * * --- * * ##### Behavior * * - If the cursor is uninitialized, it will be initialized * - If the cursor is closed, this method will throw a {@link CursorError} * - It will close the cursor when fetching is complete * - If no records are found, no error will be thrown, and an empty array will be returned * * @example * ```ts * const cursor = collection.find({ department: 'Engineering' }); * * // Get all matching records as an array * const engineers = await cursor.toArray(); * console.log(`Found ${engineers.length} engineers`); * * // For a large result set, consider using lazy iteration instead * for await (const doc of cursor.rewind()) { * // Process one document at a time * } * ``` * * @returns An array of all records in the cursor. */ toArray(): Promise<T[]>; /* Excluded from this release type: _fetchNextPage */ /* Excluded from this release type: _tm */ /* Excluded from this release type: _iterator */ /* Excluded from this release type: _next */ /* Excluded from this release type: _next */ /** * *This temporary error-ing property exists for migration convenience, and will be removed in a future version.* * * @deprecated - `.bufferedCount()` has been renamed to simply be `.buffered()`. */ bufferedCount: 'ERROR: `.bufferedCount()` has been renamed to be simply `.buffered()`'; /** * *This temporary error-ing property exists for migration convenience, and will be removed in a future version.* * * @deprecated - `.readBufferedDocuments()` has been renamed to be `.consumeBuffer()`. */ readBufferedDocuments: 'ERROR: `.readBufferedDocuments()` has been renamed to be `.consumeBuffer()`'; } /** * An operation to add columns to the table. * * @public */ export declare interface AddColumnOperation { /** * The columns to add to the table, of the same format as in `createTable` */ columns: CreateTableColumnDefinitions; } export declare type AdditionalHeaders = OneOrMany<HeadersProvider | Record<string, string | undefined>>; /** * @public */ export declare interface AddRerankingOperation { service: RerankServiceOptions; } /** * An operation to enable vectorize (auto-embedding-generation) on existing vector columns on the table. * * @public */ export declare interface AddVectorizeOperation<Schema extends SomeRow> { /** * The options for vectorize-ing each column. */ columns: Partial<Record<keyof Schema & string, VectorizeServiceOptions>>; } /** * Common base class for all admin command events. * * @public */ export declare abstract class AdminCommandEvent extends BaseClientEvent { /** * The path for the request, not including the Base URL. */ readonly url: string; /** * The HTTP method for the request. */ readonly requestMethod: 'GET' | 'POST' | 'DELETE'; /** * The request body, if any. */ readonly requestBody?: Record<string, any>; /** * The query parameters, if any. */ readonly requestParams?: Record<string, any>; /** * Whether the command is long-running or not, i.e. requires polling. */ readonly isLongRunning: boolean; /** * The method which invoked the request */ readonly invokingMethod: string; /* Excluded from this release type: __constructor */ getMessagePrefix(): string; /* Excluded from this release type: _modifyEventForFormatVerbose */ } /** * The events emitted by the {@link DataAPIClient}. These events are emitted at various stages of the * admin command's lifecycle. Intended for use for monitoring and logging purposes. * * @public */ export declare type AdminCommandEventMap = { /** * Emitted when an admin command is started, before the initial HTTP request is made. */ adminCommandStarted: AdminCommandStartedEvent; /** * Emitted when a command is polling in a long-running operation (i.e. create database). */ adminCommandPolling: AdminCommandPollingEvent; /** * Emitted when an admin command has succeeded, after any necessary polling. */ adminCommandSucceeded: AdminCommandSucceededEvent; /** * Emitted when an admin command has errored. */ adminCommandFailed: AdminCommandFailedEvent; /** * Emitted when an admin command has warnings. */ adminCommandWarnings: AdminCommandWarningsEvent; }; /** * Event emitted when an admin command has errored. * * See {@link AdminCommandEvent} for more information about all the common properties available on this event. * * @public */ export declare class AdminCommandFailedEvent extends AdminCommandEvent { /* Excluded from this release type: _permits */ /** * The duration of the command, in milliseconds. */ readonly duration: number; /** * The error that occurred. * * Typically, some {@link DevOpsAPIError}, commonly a {@link DevOpsAPIResponseError} or sometimes a * {@link DevOpsAPITimeoutError} */ readonly error: Error; /* Excluded from this release type: __constructor */ getMessage(): string; } /** * Event emitted when a command is polling in a long-running operation (i.e. create database). * * Emits every time the command polls. * * See {@link AdminCommandEvent} for more information about all the common properties available on this event. * * @public */ export declare class AdminCommandPollingEvent extends AdminCommandEvent { /* Excluded from this release type: _permits */ /** * The elapsed time since the command was started, in milliseconds. */ readonly elapsed: number; /** * The polling interval, in milliseconds. */ readonly pollInterval: number; /** * The number of times polled so far */ readonly pollCount: number; /* Excluded from this release type: __constructor */ getMessage(): string; } /** * Event emitted when an admin command is started. This is emitted before the initial HTTP request is made. * * See {@link AdminCommandEvent} for more information about all the common properties available on this event. * * @public */ export declare class AdminCommandStartedEvent extends AdminCommandEvent { /* Excluded from this release type: _permits */ /** * The timeout for the request, in milliseconds. */ readonly timeout: Partial<TimeoutDescriptor>; /* Excluded from this release type: __constructor */ getMessage(): string; } /** * Event emitted when an admin command has succeeded, after any necessary polling. * * See {@link AdminCommandEvent} for more information about all the common properties available on this event. * * @public */ export declare class AdminCommandSucceededEvent extends AdminCommandEvent { /* Excluded from this release type: _permits */ /** * The duration of the command, in milliseconds. */ readonly duration: number; /** * The response body of the command, if any. */ readonly responseBody?: Record<string, any>; /* Excluded from this release type: __constructor */ getMessage(): string; } /** * Event emitted when the Data API returned a warning for an admin command. * * See {@link AdminCommandEvent} for more information about all the common properties available on this event. * * @public */ export declare class AdminCommandWarningsEvent extends AdminCommandEvent { /* Excluded from this release type: _permits */ /** * The warnings that occurred. */ readonly warnings: ReadonlyNonEmpty<DataAPIWarningDescriptor>; /* Excluded from this release type: __constructor */ getMessage(): string; } /** * The options available spawning a new {@link AstraAdmin} instance. * * **Note that this is only available when using Astra as the underlying database.** * * If any of these options are not provided, the client will use the default options provided by the {@link DataAPIClient}. * * @public */ export declare interface AdminOptions { /** * The configuration for logging events emitted by the {@link DataAPIClient}. * * This can be set at any level of the major class hierarchy, and will be inherited by all child classes. * * See {@link LoggingConfig} for *much* more information on configuration, outputs, and inheritance. */ logging?: LoggingConfig; /** * The access token for the DevOps API, typically of the format `'AstraCS:...'`. * * If never provided, this will default to the token provided when creating the {@link DataAPIClient}. * * May be useful for if you want to use a stronger token for the DevOps API than the Data API. * * @example * ```typescript * const client = new DataAPIClient('weak-token'); * * // Using 'weak-token' as the token * const db = client.db(); * * // Using 'strong-token' instead of 'weak-token' * const admin = client.admin({ adminToken: 'strong-token' }); * ``` */ adminToken?: string | TokenProvider | null; /** * The base URL for the devops API, which is typically always going to be the following: * ``` * https://api.astra.datastax.com/v2 * ``` */ endpointUrl?: string; /** * The Astra environment to use when interacting with the DevOps API. * * In the case of {@link AstraDbAdmin}, if a database endpoint is provided, and its environment does NOT match * this value (if it is set), it will throw an error. * * In the case of {@link DataAPIDbAdmin}, it will simply ignore this value. */ astraEnv?: 'dev' | 'prod' | 'test'; /** * ##### Overview * * The default timeout options for any operation on this admin instance. * * See {@link TimeoutDescriptor} for much more information about timeouts. * * @example * ```ts * // The request timeout for all operations is set to 1000ms. * const client = new DataAPIClient('...', { * timeoutDefaults: { requestTimeoutMs: 1000 }, * }); * * // The request timeout for all operations borne from this Db is set to 2000ms. * const db = client.db('...', { * timeoutDefaults: { requestTimeoutMs: 2000 }, * }); * ``` * * ##### Inheritance * * The timeout options are inherited by all child classes, and can be overridden at any level, including the individual method level. * * Individual-method-level overrides can vary in behavior depending on the method; again, see {@link TimeoutDescriptor}. * * ##### Defaults * * The default timeout options are as follows: * - `requestTimeoutMs`: 15000 * - `generalMethodTimeoutMs`: 30000 * - `collectionAdminTimeoutMs`: 60000 * - `tableAdminTimeoutMs`: 30000 * - `databaseAdminTimeoutMs`: 600000 * - `keyspaceAdminTimeoutMs`: 30000 * * @see TimeoutDescriptor */ timeoutDefaults?: Partial<TimeoutDescriptor>; /** * *This temporary error-ing property exists for migration convenience, and will be removed in a future version.* * * @deprecated - `monitorCommands` has been overhauled, and replaced with the `logging` option. Please see its documentation for more information. */ monitorCommands?: 'ERROR: `monitorCommands` has been overhauled, and replaced with the `logging` option. Please see its documentation for more information'; } /* Excluded from this release type: AdminOptsHandler */ /* Excluded from this release type: AdminOptsTypes */ /** * The possible alterations that may be performed on the table. Only one out of the four may be used at a time. * * @public */ export declare interface AlterTableOperations<Schema extends SomeRow> { add?: AddColumnOperation; drop?: DropColumnOperation<Schema>; addVectorize?: AddVectorizeOperation<Schema>; dropVectorize?: DropVectorizeOperation<Schema>; addReranking?: AddRerankingOperation; dropReranking?: DropRerankingOperation; } /** * Options for altering a table. * * @public */ export declare interface AlterTableOptions<Schema extends SomeRow> extends CommandOptions<{ timeout: 'tableAdminTimeoutMs'; }> { /** * The operations to perform on the table. Must pick just one of `add`, `drop`, `addVectorize`, or `dropVectorize`. */ operation: AlterTableOperations<Schema>; } export declare interface AsCollectionCodecClassFns<Class extends SomeConstructor> { serializeForCollection: (this: InstanceType<Class>, ctx: CollectionSerCtx) => ReturnType<SerDesFn<any>>; deserializeForCollection: SerDesFn<CollectionDesCtx>; } export declare interface AsTableCodecClassFns<Class extends SomeConstructor> { serializeForTable: (this: InstanceType<Class>, ctx: TableSerCtx) => ReturnType<SerDesFn<any>>; deserializeForTable: SerDesFn<TableDesCtx>; } /** * An administrative class for managing Astra databases, including creating, listing, and deleting databases. * * **Shouldn't be instantiated directly; use {@link DataAPIClient.admin} to obtain an instance of this class.** * * To perform admin tasks on a per-database basis, see the {@link AstraDbAdmin} class. * * @example * ```typescript * const client = new DataAPIClient('token'); * * // Create an admin instance with the default token * const admin1 = client.admin(); * * // Create an admin instance with a custom token * const admin2 = client.admin({ adminToken: 'stronger-token' }); * * const dbs = await admin1.listDatabases(); * console.log(dbs); * ``` * * @see DataAPIClient.admin * @see AstraDbAdmin * * @public */ export declare class AstraAdmin extends HierarchicalLogger<AdminCommandEventMap> { /* Excluded from this release type: __constructor */ /** * Spawns a new {@link Db} instance using a direct endpoint and given options. * * This endpoint should include the protocol and the hostname, but not the path. It's typically in the form of * `https://<db_id>-<region>.apps.astra.datastax.com`, but it can be used with DSE or any other Data-API-compatible * endpoint. * * The given options will override any default options set when creating the {@link DataAPIClient} through * a deep merge (i.e. unset properties in the options object will just default to the default options). * * @example * ```typescript * const admin = new DataAPIClient('token').admin(); * * const db1 = admin.db('https://<db_id>-<region>.apps.astra.datastax.com'); * * const db2 = admin.db('https://<db_id>-<region>.apps.astra.datastax.com', { * keyspace: 'my_keyspace', * useHttp2: false, * }); * ``` * * @remarks * Note that this does not perform any IO or validation on if the endpoint is valid or not. It's up to the user to * ensure that the endpoint is correct. If you want to create an actual database, see {@link AstraAdmin.createDatabase} * instead. * * @param endpoint - The direct endpoint to use. * @param options - Any options to override the default options set when creating the {@link DataAPIClient}. * * @returns A new {@link Db} instance. */ db(endpoint: string, options?: DbOptions): Db; /** * Spawns a new {@link Db} instance using a direct endpoint and given options. * * This overload is purely for user convenience, but it **only supports using Astra as the underlying database**. For * DSE or any other Data-API-compatible endpoint, use the other overload instead. * * The given options will override any default options set when creating the {@link DataAPIClient} through * a deep merge (i.e. unset properties in the options object will just default to the default options). * * @example * ```typescript * const admin = new DataAPIClient('token').admin(); * * const db1 = admin.db('a6a1d8d6-31bc-4af8-be57-377566f345bf', 'us-east1'); * * const db2 = admin.db('a6a1d8d6-31bc-4af8-be57-377566f345bf', 'us-east1', { * keyspace: 'my_keyspace', * useHttp2: false, * }); * ``` * * @remarks * Note that this does not perform any IO or validation on if the endpoint is valid or not. It's up to the user to * ensure that the endpoint is correct. If you want to create an actual database, see {@link AstraAdmin.createDatabase} * instead. * * @param id - The database ID to use. * @param region - The region to use. * @param options - Any options to override the default options set when creating the {@link DataAPIClient}. * * @returns A new {@link Db} instance. */ db(id: string, region: string, options?: DbOptions): Db; /** * Spawns a new {@link AstraDbAdmin} instance for a database using a direct endpoint and given options. * * This endpoint should include the protocol and the hostname, but not the path. It's typically in the form of * `https://<db_id>-<region>.apps.astra.datastax.com`, but it can be used with DSE or any other Data-API-compatible * endpoint. * * The given options are for the underlying implicitly-created {@link Db} instance, not the {@link AstraDbAdmin} instance. * The db admin will use the same options as this {@link AstraAdmin} instance. * * The given options will override any default options set when creating the {@link DataAPIClient} through * a deep merge (i.e. unset properties in the options object will just default to the default options). * * @example * ```typescript * const admin = new DataAPIClient('token').admin(); * * const dbAdmin1 = admin.dbAdmin('https://<db_id>-<region>...'); * * const dbAdmin2 = admin.dbAdmin('https://<db_id>-<region>...', { * keyspace: 'my_keyspace', * useHttp2: false, * }); * ``` * * @remarks * Note that this does not perform any IO or validation on if the endpoint is valid or not. It's up to the user to * ensure that the endpoint is correct. If you want to create an actual database, see {@link AstraAdmin.createDatabase} * instead. * * @param endpoint - The direct endpoint to use. * @param options - Any options to override the default options set when creating the {@link DataAPIClient}. * * @returns A new {@link Db} instance. */ dbAdmin(endpoint: string, options?: DbOptions): AstraDbAdmin; /** * Spawns a new {@link Db} instance using a direct endpoint and given options. * * This overload is purely for user convenience, but it **only supports using Astra as the underlying database**. For * DSE or any other Data-API-compatible endpoint, use the other overload instead. * * The given options are for the underlying implicitly-created {@link Db} instance, not the {@link AstraDbAdmin} instance. * The db admin will use the same options as this {@link AstraAdmin} instance. * * The given options will override any default options set when creating the {@link DataAPIClient} through * a deep merge (i.e. unset properties in the options object will just default to the default options). * * @example * ```typescript * const admin = new DataAPIClient('token').admin(); * * const dbAdmin1 = admin.dbAdmin('a6a1d8d6-...-377566f345bf', 'us-east1'); * * const dbAdmin2 = admin.dbAdmin('a6a1d8d6-...-377566f345bf', 'us-east1', { * keyspace: 'my_keyspace', * useHttp2: false, * }); * ``` * * @remarks * Note that this does not perform any IO or validation on if the endpoint is valid or not. It's up to the user to * ensure that the endpoint is correct. If you want to create an actual database, see {@link AstraAdmin.createDatabase} * instead. * * @param id - The database ID to use. * @param region - The region to use. * @param options - Any options to override the default options set when creating the {@link DataAPIClient}. * * @returns A new {@link Db} instance. */ dbAdmin(id: string, region: string, options?: DbOptions): AstraDbAdmin; /** * Fetches the complete information about the database, such as the database name, IDs, region, status, actions, and * other metadata. * * @example * ```typescript * const info = await admin.info('<db_id>'); * console.log(info.info.name, info.creationTime); * ``` * * @returns A promise that resolves to the complete database information. */ dbInfo(id: string, options?: CommandOptions<{ timeout: 'databaseAdminTimeoutMs'; }>): Promise<AstraFullDatabaseInfo>; /** * Lists all databases in the current org/account, matching the optionally provided filter. * * Note that this method is paginated, but the page size is high enough that most users won't need to worry about it. * However, you can use the `limit` and `skip` options to control the number of results returned and the starting point * for the results, as needed. * * You can also filter by the database status using the `include` option, and by the database provider using the * `provider` option. * * See {@link ListAstraDatabasesOptions} for complete information about the options available for this operation. * * @example * ```typescript * const admin = new DataAPIClient('AstraCS:...').admin(); * * const activeDbs = await admin.listDatabases({ include: 'ACTIVE' }); * * for (const db of activeDbs) { * console.log(`Database ${db.name} is active`); * } * ``` * * @param options - The options to filter the databases by. * @returns A list of the complete information for all the databases matching the given filter. */ listDatabases(options?: ListAstraDatabasesOptions): Promise<AstraFullDatabaseInfo[]>; /** * Creates a new database with the given configuration. * * **NB. this is a long-running operation. See {@link AstraAdminBlockingOptions} about such blocking operations.** The * default polling interval is 10 seconds. Expect it to take roughly 2 min to complete. * * Note that **the `name` field is non-unique** and thus creating a database, even with the same options, is **not * idempotent**. * * You may also provide options for the implicit {@link Db} instance that will be created with the database, which * will override any default options set when creating the {@link DataAPIClient} through a deep merge (i.e. unset * properties in the options object will just default to the default options). * * See {@link CreateAstraDatabaseOptions} for complete information about the options available for this operation. * * @example * ```typescript * const newDbAdmin1 = await admin.createDatabase({ * name: 'my_database_1', * cloudProvider: 'GCP', * region: 'us-east1', * }); * * // Prints '[]' as there are no collections in the database yet * console.log(newDbAdmin1.db().listCollections()); * * const newDbAdmin2 = await admin.createDatabase({ * name: 'my_database_2', * cloudProvider: 'GCP', * region: 'us-east1', * keyspace: 'my_keyspace', * }, { * blocking: false, * dbOptions: { * useHttp2: false, * token: '<weaker-token>', * }, * }); * * // Can't do much else as the database is still initializing * console.log(newDbAdmin2.db().id); * ``` * * @remarks * Note that if you choose not to block, the returned {@link AstraDbAdmin} object will not be very useful until the * operation completes, which is up to the caller to determine. * * @param config - The configuration for the new database. * @param options - The options for the blocking behavior of the operation. * * @returns The AstraDbAdmin instance for the newly created database. */ createDatabase(config: AstraDatabaseConfig, options?: CreateAstraDatabaseOptions): Promise<AstraDbAdmin>; /** * Terminates a database by ID or by a given {@link Db} instance. * * **NB. this is a long-running operation. See {@link AstraAdminBlockingOptions} about such blocking operations.** The * default polling interval is 10 seconds. Expect it to take roughly 6-7 min to complete. * * The database info will still be accessible by ID, or by using the {@link AstraAdmin.listDatabases} method with the filter * set to `'ALL'` or `'TERMINATED'`. However, all of its data will very much be lost. * * @example * ```typescript * const db = client.db('https://<db_id>-<region>.apps.astra.datastax.com'); * await admin.dropDatabase(db); * * // Or just * await admin.dropDatabase('a6a1d8d6-31bc-4af8-be57-377566f345bf'); * ``` * * @param db - The database to drop, either by ID or by instance. * @param options - The options for the blocking behavior of the operation. * * @returns A promise that resolves when the operation completes. * * @remarks Use with caution. Wear a harness. Don't say I didn't warn you. */ dropDatabase(db: Db | string, options?: AstraDropDatabaseOptions): Promise<void>; /** * ##### Overview * * Finds available regions for Astra database deployments. * * The returned information includes details about each region such as its cloud provider, * classification tier, geographic zone, and availability status. * * @example * ```ts * // Find all regions enabled for the current organization (default) * const enabledRegions = await admin.findAvailableRegions(); * * // Find AWS regions in North America * const awsNaRegions = allRegions * .filter(r => r.cloudProvider === 'AWS' && r.zone === 'na'); * ``` * * --- * * ##### Including non-org-enabled regions * * By default, it returns only regions that are enabled for the current organization, but this behavior can be controlled with the {@link AstraFindAvailableRegionsOptions.onlyOrgEnabledRegions} option. * * @example * ```ts * // Find all regions, including those not enabled for the current organization * const allRegions = await admin.findAvailableRegions({ * onlyOrgEnabledRegions: false, * }); * ``` * * @param options - Options for filtering the regions to return * * @returns A promise that resolves to an array of the region information * * @see AstraAvailableRegionInfo * @see AstraRegionClassification */ findAvailableRegions(options?: AstraFindAvailableRegionsOptions): Promise<AstraAvailableRegionInfo[]>; get _httpClient(): OpaqueHttpClient; } /** * ##### Overview * * Options controlling the blocking behavior of certain admin operations. * * Some admin operations require repeatedly polling the database's status to check if said operation is complete. * These operations may be long- or short-running, but they are not instantaneous. * * By default, these operations **block** until completion, with a method-defined polling interval that can be overridden. * * Alternatively, you can opt for **non-blocking** behavior, in which case the operation returns immediately, leaving it up to the caller to manually determine completion. * * --- * * ##### Blocking * * When `blocking` is `true` (default), the operation will **not return** until it is *fully complete*. * Completion is determined by polling the database's status at a regular interval. * * You can customize the polling interval using the `pollInterval` option (in milliseconds). * * @example * ```ts * // Will block by default until the operation is complete. * const dbAdmin1 = await admin.createDatabase({ ... }); * * // Blocks with a custom poll interval (e.g. every 5 seconds). * const dbAdmin2 = await admin.createDatabase({ ... }, { * pollInterval: 5000, * }); * ``` * * --- * * ##### Non-blocking * * When `blocking` is `false`, the operation returns immediately after initiating the request. * It becomes your responsibility to check when the operation has completed. * * **Important:** In this mode, *resources will still not be usable until the operation finishes.* * * For instance: * - `createDatabase` returns an `AstraDbAdmin` object, but it won’t point to an active database until creation is complete. * - `createKeyspace` won't actually allow you to use that keyspace until the database is back to active. * * @example * ```ts * // Will return immediately without waiting for operation completion * // * // The AstraDbAdmin object is still returned, but it's not very useful * // until the operation completes. * const dbAdmin3 = await admin.createDatabase({...}, { * blocking: false, * }); * ``` * * --- * * @field blocking - Whether to block the operation until it is complete *(default: `true`)* * @field pollInterval - The interval (in milliseconds) at which to poll the operation for completion *(optional)* * * @public */ export declare type AstraAdminBlockingOptions = AstraPollBlockingOptions | AstraNoBlockingOptions; /** * ##### Overview * * Information about an available region for Astra database deployments. * * This provides details about each available region including classification, cloud provider, display name, and availability status. * * @example * ```ts * // Basic usage * const regions = await admin.findAvailableRegions(); * console.log(regions[0].displayName); // 'Moncks Corner, South Carolina' * * // Further filterting & transformation may be done using native list methods * const awsRegions = regions.filter(region => region.cloudProvider === 'AWS'); * ``` * * @see AstraAdmin.findAvailableRegions * @see AstraFindAvailableRegionsOptions * * @public */ export declare interface AstraAvailableRegionInfo { /** * Represents the classification tier of an Astra database region. * * Region availability will depend on the user's account level. * * @example * ```ts * 'standard' * ``` */ classification: AstraRegionClassification; /** * The cloud provider hosting this region. * * @example * ```ts * 'GCP' * ``` */ cloudProvider: AstraDatabaseCloudProvider; /** * A human-readable display name for the region. * * @example * ```ts * 'Moncks Corner, South Carolina' * ``` */ displayName: string; /** * Whether this region is currently enabled for use. * * > **✏️Note:** If {@link AstraFindAvailableRegionsOptions.onlyOrgEnabledRegions} is `false`, and `enabled` is still `true`, it does not guarantee that the region is usable by the current organization. */ enabled: boolean; /** * The unique identifier for the region. * * @example * ```ts * 'us-east1' * ``` */ name: string; /** * Whether this region is reserved for qualified users only, meaning special access is required to use it. */ reservedForQualifiedUsers: boolean; /** * The geographic zone where this region is located. * * @example * ```ts * 'na' * ``` */ zone: AstraRegionZone; } /** * ##### Overview * * Represents the common properties shared by both {@link AstraPartialDatabaseInfo} and {@link AstraFullDatabaseInfo}. * * This includes identifiers, basic configuration, status, and environment details. * * @public */ export declare interface AstraBaseDatabaseInfo { /** * The unique UUID of the database. */ id: string; /** * The user-provided name of the database. */ name: string; /** * The list of keyspaces currently present in the database. * * The list may technically be empty in rare corner cases, if they have all been deleted, but it is quite unlikely. */ keyspaces: string[]; /** * The current status of the database. * * Common values include: * - `'PENDING'` * - `'ACTIVE'` * - `'DELETING'` * - `'HIBERNATED'` * - `'TERMINATED'` * * Status values indicate the provisioning/operational state of the database. * * {@link AstraDatabaseStatus} contains a large amount of possible statuses (though many are unlikely), but the enumeration is open to other statuses not mentioned. */ status: AstraDatabaseStatus; /** * The cloud provider where the database is hosted. * * Valid values include `'AWS'`, `'GCP'`, and `'AZURE'`. */ cloudProvider: AstraDatabaseCloudProvider; /** * The Astra environment in which the database is running. * * Not relevant for most users' usage. */ environment: 'dev' | 'test' | 'prod'; /** * The full raw response received from the DevOps API when querying for database metadata. * * This field