Azion SQL library

The Edge SQL library provides methods to interact with the Edge SQL API, allowing you to create, delete, and query databases. This client is configurable and supports both debug mode and environment variable-based configuration.

Go to Azion Libraries Overview

You can interact with the API using a client or calling the methods directly from the library. When making direct calls, you can use the environment variables to configure the client without passing the token and debug parameters directly.

This is an example of how a .env file with your environment variables may look like:

Terminal window
AZION_TOKEN=<your-api-token>
AZION_DEBUG=true
VariableDescription
AZION_TOKENYour Azion API token.
AZION_DEBUGEnable debug mode (true/false).

If you want to create a specific client for interacting with SQL, do it by calling the createClient method from the library:

import { createClient } from 'azion/purge';
import type { AzionSQLClient, AzionSQLResponse, AzionSQL } from 'azion/purge';
const client: AzionSQLClient = createClient({ token: 'your-api-token', options: { debug: true } });
const { data, error } = await client.createDatabase('my-new-db');
if (data) {
console.log(`Database created with ID: ${data.id}`);
} else {
console.error('Failed to create database', error);
}

The createClient method has the following parameters and return value:

Parameters:

ParameterTypeDescription
configPartial<{ token: string; options?: OptionsParams }>Configuration options for the SQL client.

Returns:

Return TypeDescription
AzionSQLClientAn object with methods to interact with SQL.

Usage

createDatabase

Creates a new database.

Parameters:

ParameterTypeDescription
namestringName of the new database.
optionsAzionClientOptions (optional)Optional parameters for the creation.

Returns:

Return TypeDescription
Promise<AzionDatabaseResponse<AzionDatabase>>The created database object or error.

Example:

import { createDatabase, AzionDatabase } from 'azion/sql';
import type { AzionDatabaseResponse, AzionDatabase } from 'azion/sql';
const { data, error }: AzionDatabaseResponse<AzionDatabase> = await createDatabase('my-new-database', { debug: true });
if (data) {
const database: AzionDatabase = data;
console.log(`Database created with ID: ${database.id}`);
} else {
console.error('Failed to create database', error);
}

deleteDatabase

Deletes a database by its ID.

Parameters:

ParameterTypeDescription
idnumberID of the database to delete.
optionsAzionClientOptions (optional)Optional parameters for the deletion.

Returns:

Return TypeDescription
Promise<AzionDatabaseResponse<AzionDatabaseDeleteResponse>>Object confirming deletion or error.

Example:

import { deleteDatabase } from 'azion/sql';
import type { AzionDatabaseResponse, AzionDatabaseDeleteResponse } from 'azion/sql';
const { data, error }: AzionDatabaseResponse<AzionDatabaseDeleteResponse> = await deleteDatabase(123, { debug: true });
if (data) {
console.log(`Database ${data.id} deleted successfully`);
} else {
console.error('Failed to delete database', error);
}

getDatabase

Retrieves a database by its name.

Parameters:

ParameterTypeDescription
namestringName of the database to retrieve.
optionsAzionClientOptions (optional)Optional parameters for the retrieval.

Returns:

Return TypeDescription
Promise<AzionDatabaseResponse<AzionDatabase>>The retrieved database object or error.

Example:

import { getDatabase } from 'azion/sql';
import type { AzionDatabaseResponse, AzionDatabase } from 'azion/sql';
const { data, error }: AzionDatabaseResponse<AzionDatabase> = await getDatabase('my-db', { debug: true });
if (data) {
const database: AzionDatabase = data;
console.log(`Retrieved database: ${database.id}`);
} else {
console.error('Database not found', error);
}

getDatabases

Retrieves a list of databases with optional filtering and pagination.

Parameters:

ParameterTypeDescription
paramsAzionDatabaseCollectionOptions (optional)Optional parameters for filtering and pagination.
optionsAzionClientOptions (optional)Optional parameters for the retrieval.

Returns:

Return TypeDescription
Promise<AzionDatabaseResponse<AzionDatabaseCollections>>Array of database objects or error.

Example:

import { getDatabases } from 'azion/sql';
import type { AzionDatabaseResponse, AzionDatabaseCollections } from 'azion/sql';
const { data: allDatabases, error }: AzionDatabaseResponse<AzionDatabaseCollections> = await getDatabases(
{ page: 1, page_size: 10 },
{ debug: true },
);
if (allDatabases) {
console.log(`Retrieved ${allDatabases.count} databases`);
} else {
console.error('Failed to retrieve databases', error);
}

useQuery

Executes a query on a specific database.

Parameters:

ParameterTypeDescription
namestringName of the database to query.
statementsstring[]Array of SQL statements to execute.
optionsAzionClientOptions (optional)Optional parameters for the query.

Returns:

Return TypeDescription
Promise<AzionDatabaseResponse<AzionDatabaseQueryResponse>>Query result object or error.

Example:

import { useQuery, AzionDatabaseQueryResponse, AzionDatabaseResponse } from 'azion/sql';
const { data: result, error }: AzionDatabaseResponse<AzionDatabaseQueryResponse> = await useQuery(
'my-db',
['SELECT * FROM users'],
{
debug: true,
},
);
if (result) {
console.log(`Query executed. Rows returned: ${result.rows.length}`);
} else {
console.error('Query execution failed', error);
}

useExecute

Executes a set of SQL statements on a specific database.

Parameters:

ParameterTypeDescription
namestringName of the database on which the statements will be executed.
statementsstring[]Array of SQL statements to execute.
optionsAzionClientOptions (optional)Optional parameters for the execution.

Returns:

Return TypeDescription
Promise<AzionDatabaseResponse<AzionDatabaseQueryResponse>>Execution result object or error.

Example:

import { useExecute, AzionDatabaseQueryResponse } from 'azion/sql';
const result: AzionDatabaseQueryResponse | null = await useExecute(
'my-db',
['INSERT INTO users (name) VALUES ("John")'],
{
debug: true,
},
);
if (result?.state === 'executed') {
console.log('Executed with success');
} else {
console.error('Execution failed');
}

Types

These are the types used by the SQL Library and its methods:

ClientConfig

Configuration options for the SQL client.

ParameterTypeDescription
tokenstring (optional)Your Azion API token.
optionsAzionClientOptions (optional)Optional parameters for the client configuration.

AzionSQLClient

An object with methods to interact with SQL databases.

MethodParametersReturn Type
createDatabasename: stringPromise<AzionDatabaseResponse<AzionDatabase>>
deleteDatabaseid: numberPromise<AzionDatabaseResponse<AzionDatabaseDeleteResponse>>
getDatabasename: stringPromise<AzionDatabaseResponse<AzionDatabase>>
getDatabasesparams?: AzionDatabaseCollectionOptionsPromise<AzionDatabaseResponse<AzionDatabaseCollections>>
useQueryname: string, statements: string[], options?: AzionClientOptionsPromise<AzionDatabaseResponse<AzionDatabaseQueryResponse>>
useExecutename: string, statements: string[], options?: AzionClientOptionsPromise<AzionDatabaseResponse<AzionDatabaseExecutionResponse>>

AzionDatabase

The database object.

PropertyTypeDescription
idnumberUnique identifier for the database.
namestringThe name of the database.
clientIdstringThe client ID associated with the database.
statusstringThe current status of the database.
createdAtstringThe timestamp of when the database was created.
updatedAtstringThe timestamp of when the database was last updated.
deletedAtstring | nullTimestamp of when the database was deleted, or null if not deleted.
query(statements: string[], options?: AzionClientOptions) => Promise<AzionDatabaseResponse<AzionDatabaseQueryResponse>>Executes a query on the database.
execute(statements: string[], options?: AzionClientOptions) => Promise<AzionDatabaseResponse<AzionDatabaseExecutionResponse>>Executes a SQL statement on the database.
getTables(options?: AzionClientOptions) => Promise<AzionDatabaseResponse<AzionDatabaseQueryResponse>>Retrieves a list of tables in the database.

AzionDatabaseResponse<T>

The response object from a database operation.

PropertyTypeDescription
dataT (optional)The data returned from the operation.
error{ message: string, operation: string } (optional)The error details if the operation fails.

QueryResult

PropertyTypeDescription
statestringThe state of the query execution.
columnsstring[]An array of column names.
statementstringThe SQL statement executed.
rows(number | string)[][]A 2D array of rows, where each row is an array of values.

AzionClientOptions

Optional parameters for the client configuration.

PropertyTypeDescription
debugboolean (optional)Enables debug mode.
forceboolean (optional)Forces the operation to be executed.

AzionDatabaseCollectionOptions

Optional parameters for filtering and pagination.

PropertyTypeDescription
orderingstring (optional)Specifies the ordering of the results.
pagenumber (optional)The page number for pagination.
page_sizenumber (optional)The number of items per page.
searchstring (optional)A search query to filter the results.

AzionDatabaseQueryResponse

The response object from a query execution.

PropertyTypeDescription
state('executed' | 'pending' | 'executed-runtime' | 'failed')The state of the query execution.
dataQueryResult[]The data returned from the operation.
toObject() => JsonObjectQueryExecutionResponse (optional)A method to convert the response to a JSON object.

AzionDatabaseExecutionResponse

The response object from a query execution.

PropertyTypeDescription
state('executed' | 'pending' | 'executed-runtime' | 'failed')The state of the query execution.
dataQueryResult[]The data returned from the operation.
toObject() => JsonObjectQueryExecutionResponse (optional)A method to convert the response to a JSON object.

AzionQueryExecutionParams

Parameters for query execution.

PropertyTypeDescription
statementsstring[]An array of SQL statements.
params(AzionQueryParams | Record<string, AzionQueryParams>)[] (optional)An array of query parameters.

AzionQueryParams

Query parameters.

PropertyTypeDescription
param`stringnumber

Contributors