@datastax/astra-db-ts
Version:
Data API TypeScript client
1,315 lines (1,275 loc) • 649 kB
TypeScript
// 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**: Shouldn't be directly instantiated, but rather spawned via {@link Collection.findAndRerank}/{@link Collection.find}, or their {@link Table} alternatives.
*
* ---
*
* ##### Typing
*
* > **🚨Important:** For most intents and purposes, you may treat the cursor as if it is typed simply as `Cursor<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.
*
* @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: _buffer */
/* Excluded from this release type: _state */
/* Excluded from this release type: _nextPageState */
/* Excluded from this release type: _mapping */
/* Excluded from this release type: _options */
/* Excluded from this release type: __constructor */
/**
* The current status of the cursor.
*/
get state(): CursorState;
/**
* 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 ({@link FindCursor.consumed} + {@link FindCursor.buffered}).
*/
buffered(): number;
/**
* The number of records that have been read be 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 ({@link FindCursor.consumed} + {@link FindCursor.buffered}).
*/
consumed(): number;
/**
* Consumes up to `max` records from the buffer, or all records if `max` is not provided.
*
* **Note that this actually consumes the buffer; it doesn't just peek at it.**
*
* @param max - The maximum number of records to read from the buffer. If not provided, all records will be read.
*
* @returns The records read from the buffer.
*/
consumeBuffer(max?: number): TRaw[];
/**
* 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 this cursor.
*/
rewind(): void;
/**
* Closes the cursor. The cursor will be unusable after this method is called, or until {@link FindCursor.rewind} is called.
*/
close(): void;
abstract clone(): this;
abstract map<R>(map: (doc: T) => R): AbstractCursor<R, TRaw>;
/**
* An async iterator that lazily iterates over all records in the cursor.
*
* **Note that there'll only be partial results if the cursor has been previously iterated over. You may use {@link FindCursor.rewind}
* to reset the cursor.**
*
* If the cursor is uninitialized, it will be initialized. If the cursor is closed, this method will return immediately.
*
* It will close the cursor when iteration is complete, even if it was broken early.
*
* @example
* ```typescript
* for await (const doc of cursor) {
* console.log(doc);
* }
* ```
*/
[Symbol.asyncIterator](): AsyncGenerator<T, void, void>;
/**
* Fetches the next record from the cursor. Returns `null` if there are no more records to fetch.
*
* If the cursor is uninitialized, it will be initialized. If the cursor is closed, this method will return `null`.
*
* @returns The next record, or `null` if there are no more records.
*/
next(): Promise<T | null>;
/**
* Tests if there is a next record in the cursor.
*
* If the cursor is uninitialized, it will be initialized. If the cursor is closed, this method will return `false`.
*
* @returns Whether or not there is a next record.
*/
hasNext(): Promise<boolean>;
/**
* Iterates over all records in the cursor, calling the provided consumer for each record.
*
* If the consumer returns `false`, iteration will stop.
*
* Note that there'll only be partial results if the cursor has been previously iterated over. You may use {@link FindCursor.rewind}
* to reset the cursor.
*
* If the cursor is uninitialized, it will be initialized. If the cursor is closed, this method will return immediately.
*
* It will close the cursor when iteration is complete, even if it was stopped early.
*
* @param consumer - The consumer to call for each record.
*
* @returns A promise that resolves when iteration is complete.
*
* @remarks
* If you get an IDE error "Promise returned from forEach argument is ignored", 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).
*/
forEach(consumer: ((doc: T) => boolean | Promise<boolean>) | ((doc: T) => void | Promise<void>)): Promise<void>;
/**
* Returns an array of all matching records in the cursor. The user should ensure that there is enough memory to
* store all records in the cursor.
*
* Note that there'll only be partial results if the cursor has been previously iterated over. You may use {@link FindCursor.rewind}
* to reset the cursor.
*
* If the cursor is uninitialized, it will be initialized. If the cursor is closed, this method will return an empty array.
*
* @returns An array of all records in the cursor.
*/
toArray(): Promise<T[]>;
/* Excluded from this release type: _nextPage */
/* 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 WithTimeout<'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?: WithTimeout<'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>;
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
*
* 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 is provided for inspection or debugging, and contains fields not explicitly typed/present in this interface.
*/
raw: Record<string, any>;
}
/**
* Represents the available cloud providers that DataStax Astra offers for database hosting.
*
* @public
*/
export declare type AstraDatabaseCloudProvider = 'AWS' | 'GCP' | 'AZURE';
/**
* Represents all possible cloud providers that you can filter by.
*
* @public
*/
export declare type AstraDatabaseCloudProviderFilter = AstraDatabaseCloudProvider | 'ALL';
/**
* ##### Overview
*
* Represents the core definition options for creating a new vector-enabled DataStax Astra database.
*
* This includes required settings such as the database name, cloud provider, and region, as well as an optionally specified keyspace.
*
* Note that:
* - If no `keyspace` is provided, Astra will automatically provide a keyspace named `default_keyspace`.
* - Available regions may vary depending on the selected cloud provider.
* - It is **not possible** to create a non-vector database through the Data API clients.
*
* **Disclaimer: database creation is a lengthy operation, and may take upwards of 2-3 minutes**
*
* ---
*
* ##### Example
*
* These options are used in the first parameter of the `createDatabase` method.
*
* @example
* ```ts
* const dbAdmin = await admin.createDatabase({
* name: 'my-db',
* cloudProvider: 'GCP',
* region: 'us-central1',
* });
* ```
*
* @see AstraAdmin.createDatabase
* @see CreateAstraDatabaseOptions
*
* @public
*/
export declare interface AstraDatabaseConfig {
/**
* A user-defined name for the database, e.g. `my_database`.
*/
name: string;
/**
* The cloud provider where the database will be hosted.
*
* Supported values include `'AWS'`, `'GCP'`, and `'AZURE'`.
*
* **Note: available regions vary across providers.**
*/
cloudProvider: AstraDatabaseCloudProvider;
/**
* The specific cloud region in which the database will be deployed, e.g. `us-east1`.
*
* **Note: the region must be valid for the selected `cloudProvider`.**
*/
region: string;
/**
* The default keyspace to create within the database, e.g. `my_keyspace`.
*
* If omitted, Astra will automatically provide a keyspace named `default_keyspace`.
*/
keyspace?: string;
}
/**
* ##### Overview
*
* Represents data about a region in which an Astra database is hosted.
*
* This includes the region name, the API endpoint to use when interacting with that region, and the created-at timestamp.
*
* Used within the `regions` field of {@link AstraFullDatabaseInfo}, which may include multiple region entries for multi-region databases.
*
* @public
*/
export declare interface AstraDatabaseRegionInfo {
/**
* The name of the region where the database is hosted, e.g. `us-east1`.
*/
name: string;
/**
* The API endpoint for the region, e.g. `https://<db-id>-<region>.apps.astra.datastax.com`.
*/
apiEndpoint: string;
/**
* A timestamp representing when this region was created.
*/
createdAt: Date;
}
/**
* Represents the possible statuses of a database.
*
* For future compatability reasons, the enumeration is intentionally left open-ended, in case statuses may be added or modified in the future.
*
* @public
*/
export declare type AstraDatabaseStatus = LitUnion<'ACTIVE' | 'ERROR' | 'DECOMMISSIONING' | 'DEGRADED' | 'HIBERNATED' | 'HIBERNATING' | 'INITIALIZING' | 'MAINTENANCE' | 'PARKED' | 'PARKING' | 'PENDING' | 'PREPARED' | 'PREPARING' | 'RESIZING' | 'RESUMING' | 'TERMINATED' | 'TERMINATING' | 'UNKNOWN' | 'UNPARKING' | 'SYNCHRONIZING'>;
/**
* Represents all possible statuses of a database that you can filter by.
*
* @public
*/
export declare type AstraDatabaseStatusFilter = AstraDatabaseStatus | 'ALL' | 'NONTERMINATED';
/**
* An administrative class for managing Astra databases, including creating, listing, and deleting keyspaces.
*
* **Shouldn't be instantiated directly; use {@link Db.admin} or {@link AstraDbAdmin.dbAdmin} to obtain an instance of this class.**
*
* To manage databases as a whole, see {@link AstraAdmin}.
*
* @example
* ```typescript
* const client = new DataAPIClient('*TOKEN*');
*
* // Create an admin instance through a Db
* const db = client.db('*ENDPOINT*');
* const dbAdmin1 = db.admin();
* const dbAdmin2 = db.admin({ adminToken: 'stronger-token' });
*
* // Create an admin instance through an AstraAdmin
* const admin = client.admin();
* const dbAdmin3 = admin.dbAdmin('*ENDPOINT*');
* const dbAdmin4 = admin.dbAdmin('*DB_ID*', '*REGION*');
*
* const keyspaces = await admin1.listKeyspaces();
* console.log(keyspaces);
*
* const dbInfo = await admin1.info();
* console.log(dbInfo);
* ```
*
* @see Db.admin
* @see AstraDbAdmin.dbAdmin
*
* @public
*/
export declare class AstraDbAdmin extends DbAdmin {
/* Excluded from this release type: __constructor */
/**
* Gets the ID of the Astra DB instance this object is managing.
*
* @returns The ID of the Astra DB instance.
*/
get id(): string;
/**
* Gets the underlying `Db` object. The options for the db were set when the `AstraDbAdmin` instance, or whatever
* spawned it, was created.
*
* @example
* ```typescript
* const dbAdmin = client.admin().dbAdmin('<endpoint>', {
* keyspace: 'my_keyspace',
* useHttp2: false,
* });
*
* const db = dbAdmin.db();
* console.log(db.id);
* ```
*
* @returns The underlying `Db` object.
*/
db(): Db;
/**
* Fetches the complete information about the database, such as the database name, IDs, region, status, actions, and
* other metadata.
*
* The method issues a request to the DevOps API each time it is invoked, without caching mechanisms;
* this ensures up-to-date information for usages such as real-time collections validation by the application.
*
* @example
* ```typescript
* const info = await dbAdmin.info();
* console.log(info.info.name, info.creationTime);
* ```
*
* @returns A promise that resolves to the complete database information.
*/
info(options?: WithTimeout<'databaseAdminTimeoutMs'>): Promise<AstraFullDatabaseInfo>;
/**
* Lists the keyspaces in the database.
*
* The first element in the returned array is the default keyspace of the database, and the rest are additional
* keyspaces in no particular order.
*
* @example
* ```typescript
* const keyspaces = await dbAdmin.listKeyspaces();
*
* // ['default_keyspace', 'my_other_keyspace']
* console.log(keyspaces);
* ```
*
* @returns A promise that resolves to list of all the keyspaces in the database.
*/
listKeyspaces(options?: WithTimeout<'keyspaceAdminTimeoutMs'>): Promise<string[]>;
/**
* Creates a new, additional, keyspace for this database.
*
* **NB. this is a "long-running" operation. See {@link AstraAdminBlockingOptions} about such blocking operations.** The
* default polling interval is 1 second. Expect it to take roughly 8-10 seconds to complete.
*
* @example
* ```typescript
* await dbAdmin.createKeyspace('my_other_keyspace1');
*
* // ['default_keyspace', 'my_other_keyspace1']
* console.log(await dbAdmin.listKeyspaces());
*
* await dbAdmin.createKeyspace('my_other_keyspace2', {
* blocking: false,
* });
*
* // Will not include 'my_other_keyspace2' until the operation completes
* console.log(await dbAdmin.listKeyspaces());
* ```
*
* @remarks
* Note that if you choose not to block, the created keyspace will not be able to be used until the
* operation completes, which is up to the caller to determine.
*
* @param keyspace - The name of the new keyspace.
* @param options - The options for the blocking behavior of the operation.
*
* @returns A promise that resolves when the operation completes.
*/
createKeyspace(keyspace: string, options?: CreateAstraKeyspaceOptions): Promise<void>;
/**
* Drops a keyspace from this database.
*
* **NB. this is a "long-running" operation. See {@link AstraAdminBlockingOptions} about such blocking operations.** The
* default polling interval is 1 second. Expect it to take roughly 8-10 seconds to complete.
*
* @example
* ```typescript
* await dbAdmin.dropKeyspace('my_other_keyspace1');
*
* // ['default_keyspace', 'my_other_keyspace2']
* console.log(await dbAdmin.listKeyspaces());
*
* await dbAdmin.dropKeyspace('my_other_keyspace2', {
* blocking: false,
* });
*
* // Will still include 'my_other_keyspace2' until the operation completes
* // ['default_keyspace', 'my_other_keyspace2']
* console.log(await dbAdmin.listKeyspaces());
* ```
*
* @remarks
* Note that if you choose not to block, the keyspace will still be able to be used until the operation
* completes, which is up to the caller to determine.
*
* @param keyspace - The name of the keyspace to drop.
* @param options - The options for the blocking behavior of the operation.
*
* @returns A promise that resolves when the operation completes.
*/
dropKeyspace(keyspace: string, options?: DropAstraKeyspaceOptions): Promise<void>;
/**
* Drops the database.
*
* **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 db.admin().drop();
* ```
*
* @param options - The options for the blocking behavior of the operation.
*
* @returns A promise that resolves when the operation completes.
*
* @remarks Use with caution. Use a surge protector. Don't say I didn't warn you.
*/
drop(options?: DropAstraKeyspaceOptions): Promise<void>;
get _httpClient(): OpaqueHttpClient;
/* Excluded from this release type: _getDataAPIHttpClient */
}
/**
* Represents the options for dropping a database (i.e. blocking options + timeout options).
*
* @public
*/
export declare type AstraDropDatabaseOptions = AstraAdminBlockingOptions & WithTimeout<'databaseAdminTimeoutMs'>;
/**
* ##### Overview
*
* Represents the complete metadata returned for an Astra database.
*
* This is returned from {@link AstraDbAdmin.info} and {@link AstraAdmin.dbInfo}, whereas {@link AstraPartialDatabaseInfo} is used for {@link Db.info}.
*
* @example
* ```ts
* const fullInfo = await db.admin().info(),
*
* // 'ACTIVE'
* console.log(fullInfo.status),
*
* // 'https://<db-id>-<region>.apps.astra.datastax.com'
* console.log(fullInfo.regions[0].apiEndpoint),
* ```
*
* @see AstraBaseDatabaseInfo
*
* @public
*/
export declare interface AstraFullDatabaseInfo extends AstraBaseDatabaseInfo {
/**
* A timestamp representing when the database was initially created.
*/
createdAt: Date;
/**
* A timestamp representing the most recent time the database was accessed (read/write).
*/
lastUsed: Date;
/**
* Information about the regions in which the database is deployed.
*
* It should contain at least one value, but may have more for multi-region deployments.
*
* Contains the region name, API endpoint for that region, and the timestamp when that region was created.
*/
regions: AstraDatabaseRegionInfo[];
/**
* The unique organization UUID that owns this database.
*/
orgId: string;
/**
The unique user UUID that owns this database.
*/
ownerId: string;
}
/**
* ##### Overview (See {@link AstraAdminBlockingOptions})
*
* This is one of the possi