Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DOC-264 : Add DEFINE CONFIG #874

Merged
merged 2 commits into from
Sep 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
372 changes: 372 additions & 0 deletions src/content/doc-surrealql/statements/define/config.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,372 @@
---
sidebar_position: 3
sidebar_label: DEFINE CONFIG
title: DEFINE CONFIG statement | SurrealQL
description: This statement allows you to configure how your database's tables and functions are exposed via the GraphQL API. This configuration is essential for enabling GraphQL functionality in your database, specifying which tables and functions should be included or excluded from the GraphQL schema.
---
import Since from '@components/Since.astro'


# `DEFINE CONFIG GRAPHQL` statement

The `DEFINE CONFIG GRAPHQL` statement allows you to configure how your database's tables and functions are exposed via the GraphQL API. This configuration is essential for enabling GraphQL functionality in your database, specifying which tables and functions should be included or excluded from the GraphQL schema.

The GraphQL configuration defined using this statement dictates how clients interact with your database through GraphQL queries and mutations.

>[!IMPORTANT]
>The `DEFINE CONFIG GRAPHQL` statement is currently still experimental and is subject to change.


> [!WARNING]
> By running SurrealDB with the GraphQL module enabled, you are opting into an experimental feature. While the GraphQL module is fully functional, it is still considered experimental and may not be as stable as the core SurrealQL module which means we cannot guarantee that it will provide the same security guarantees. It is not recommended for production use. We welcome your feedback and contributions to help improve the feature and make it more robust.

## Requirements

- You **must** be authenticated as a **root**, **namespace**, or **database** user before you can use the `DEFINE CONFIG GRAPHQL` statement.
- You **must** select your **namespace** and **database** before you can use the `DEFINE CONFIG GRAPHQL` statement.
- You **must** define at least one table in your database for the GraphQL API to function.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is currently true, but will soon not be when functions are supported

- You **must** have started the SurrealDB instance with the `SURREAL_EXPERIMENTAL_GRAPHQL` environment variable set to `true`.

## Statement syntax

```surql title="SurrealQL Syntax"

DEFINE CONFIG [OVERWRITE | IF NOT EXISTS] GRAPHQL [ AUTO | NONE]
[ TABLES (AUTO | NONE | INCLUDE table1, table2, ...) ]
[ FUNCTIONS (AUTO | NONE | INCLUDE [function1, function2, ...] | EXCLUDE [function1, function2, ...]) ]
```


## Important Notes

- The `DEFINE CONFIG GRAPHQL` statement **must** be executed before any GraphQL queries can be made.
- If you attempt to use the GraphQL API without defining the configuration, you will receive a `NotConfigured` error.
- If no tables are defined in the database, you will receive an error stating "No tables found in database" when attempting to use the GraphQL API.

## Example usage

```surql
-- Define GraphQL configuration
DEFINE CONFIG GRAPHQL AUTO;
```

## Tables Configuration

The `TABLES` clause in the `DEFINE CONFIG GRAPHQL` statement specifies how tables are exposed via GraphQL. There are four options for the `TABLES` configuration:

- `AUTO`: Automatically include all tables in the GraphQL schema.
- `NONE`: Do not include any tables in the GraphQL schema.
- `INCLUDE`: Specify a list of tables to include in the GraphQL schema.
- `EXCLUDE`: Specify a list of tables to exclude from the GraphQL schema.

### `AUTO`

When you specify `TABLES AUTO`, all tables in the database are automatically included in the GraphQL schema.

```surql
DEFINE CONFIG GRAPHQL TABLES AUTO;
```

### `NONE`

When you specify `TABLES NONE`, no tables are included in the GraphQL schema.

```surql
DEFINE CONFIG GRAPHQL TABLES NONE;
```

### `INCLUDE`

You can specify a list of tables to include in the GraphQL schema using the `INCLUDE` clause. The list of tables is specified as a comma-separated list without brackets.

```surql
DEFINE CONFIG GRAPHQL TABLES INCLUDE user, post, comment;
```

> [!NOTE]
> The `EXCLUDE` option for `TABLES` is currently not implemented.
Ekwuno marked this conversation as resolved.
Show resolved Hide resolved

## Functions Configuration
Ekwuno marked this conversation as resolved.
Show resolved Hide resolved

The `FUNCTIONS` clause in the `DEFINE CONFIG GRAPHQL` statement specifies how functions are exposed via GraphQL. There are four options for the `FUNCTIONS` configuration:

- `AUTO`: Automatically include all functions in the GraphQL schema.
- `NONE`: Do not include any functions in the GraphQL schema.
- `INCLUDE`: Specify a list of functions to include in the GraphQL schema.
- `EXCLUDE`: Specify a list of functions to exclude from the GraphQL schema.

### `AUTO`

When you specify `FUNCTIONS AUTO`, all functions in the database are automatically included in the GraphQL schema.

```surql
DEFINE CONFIG GRAPHQL FUNCTIONS AUTO;
```

### `NONE`

When you specify `FUNCTIONS NONE`, no functions are included in the GraphQL schema.

```surql
DEFINE CONFIG GRAPHQL FUNCTIONS NONE;
```

### `INCLUDE`

You can specify a list of functions to include in the GraphQL schema using the `INCLUDE` clause. The list of functions is specified as a comma-separated list enclosed in square brackets `[]`.

```surql
DEFINE CONFIG GRAPHQL FUNCTIONS INCLUDE [getUser, listPosts, searchComments];
```

### `EXCLUDE`

You can specify a list of functions to exclude from the GraphQL schema using the `EXCLUDE` clause. The list of functions is specified as a comma-separated list enclosed in square brackets `[]`.

```surql
DEFINE CONFIG GRAPHQL FUNCTIONS EXCLUDE [debugFunction, testFunction];
```

## Using `IF NOT EXISTS` clause

The `IF NOT EXISTS` clause can be used to define the GraphQL configuration only if it does not already exist. This is useful when you want to ensure that the configuration is only created if it does not already exist, preventing errors due to duplicate definitions.

```surql
-- Define GraphQL configuration only if it does not already exist
DEFINE CONFIG GRAPHQL IF NOT EXISTS TABLES AUTO FUNCTIONS AUTO;
```

## Using `OVERWRITE` clause

The `OVERWRITE` clause can be used to redefine the GraphQL configuration, overwriting any existing configuration. This is useful when you want to update or modify the existing GraphQL configuration.

```surql
-- Redefine GraphQL configuration, overwriting existing configuration
DEFINE CONFIG OVERWRITE GRAPHQL TABLES INCLUDE user, post FUNCTIONS NONE;
```

## Examples

### Example 1: Include specific tables and functions

This example defines a GraphQL configuration that includes specific tables and functions.

```surql
DEFINE CONFIG GRAPHQL TABLES INCLUDE user, post FUNCTIONS INCLUDE [getUser, listPosts];
```

### Example 2: Automatically include all tables and functions

This example defines a GraphQL configuration that automatically includes all tables and functions.

```surql
DEFINE CONFIG GRAPHQL TABLES AUTO FUNCTIONS AUTO;
```

### Example 3: Exclude specific functions

This example defines a GraphQL configuration that includes all functions except specific ones.

```surql
DEFINE CONFIG GRAPHQL FUNCTIONS EXCLUDE [debugFunction, testFunction];
```


## Error Handling

### NotConfigured Error

If you attempt to access the GraphQL endpoint without defining the GraphQL configuration, you will receive a `NotConfigured` error.

```bash title="Error Response"
{
"error": "NotConfigured: GraphQL endpoint is not configured. Please define the GraphQL configuration using DEFINE CONFIG GRAPHQL."
}
```

Execute the `DEFINE CONFIG GRAPHQL` statement to define the GraphQL configuration.

```surql
-- Define GraphQL configuration
DEFINE CONFIG GRAPHQL TABLES AUTO FUNCTIONS AUTO;
```

### No Tables Found Error

If you have defined the GraphQL configuration but no tables are defined in the database, you will receive an error stating "No tables found in database" when attempting to use the GraphQL API. You can fix this by defining at least one table in your database using the [`DEFINE TABLE`](/docs/surrealql/statements/define/table) statement.

```bash title="Error Response"
{
"error": "No tables found in database. Please define at least one table to use the GraphQL API."
}
```

**Solution**: Define at least one table in your database.

```surql
DEFINE TABLE foo SCHEMAFUL;
DEFINE FIELD val ON foo TYPE int;
CREATE foo:1 SET val = 42;
```

## Authentication Errors When Accessing Data via GraphQL

**Cause**: Insufficient permissions or incorrect authentication credentials.

**Solution**: Ensure you are authenticated as a user with the necessary permissions and that the permissions on tables and fields are correctly configured.

### Authentication and Permissions

- The GraphQL API respects SurrealDB's authentication and permission model.
- You must authenticate using the appropriate credentials to access data via GraphQL.
- Permissions set on tables and fields will affect the data accessible through the GraphQL API.
- If you attempt to access data without sufficient permissions, you will receive an authentication error.



### Example: Basic Authentication

```surql
-- Define a user with access permissions
DEFINE USER my_user ON DATABASE PASSWORD 'my_password';
DEFINE ACCESS user ON DATABASE TYPE RECORD
SIGNUP ( CREATE user SET email = $email, pass = crypto::argon2::generate($pass) )
SIGNIN ( SELECT * FROM user WHERE email = $email AND crypto::argon2::compare(pass, $pass) )
DURATION FOR SESSION 60s, FOR TOKEN 1d;

-- Define a table with permissions
DEFINE TABLE foo SCHEMAFUL PERMISSIONS FOR select WHERE $auth.email = email;
DEFINE FIELD email ON foo TYPE string;
DEFINE FIELD val ON foo TYPE int;

-- Insert data
CREATE foo:1 SET val = 42, email = "[email protected]";
CREATE foo:2 SET val = 43, email = "[email protected]";
```

When querying the GraphQL API as `[email protected]`, only the records where `email = "[email protected]"` will be accessible due to the permissions set.

## Examples

### Example 1: Defining GraphQL Configuration and Fetching Data

```surql
-- Define GraphQL configuration to include all tables automatically
DEFINE CONFIG GRAPHQL TABLES AUTO;

-- Define a table and insert data
DEFINE TABLE foo SCHEMAFUL;
DEFINE FIELD val ON foo TYPE int;
CREATE foo:1 SET val = 42;
CREATE foo:2 SET val = 43;
```

Now, you can fetch data via GraphQL:

```graphql
query {
foo {
id
val
}
}
```

**Response:**

```json
{
"data": {
"foo": [
{
"id": "foo:1",
"val": 42
},
{
"id": "foo:2",
"val": 43
}
]
}
}
```

### Example 2: Including Specific Tables

```surql
-- Define GraphQL configuration to include only specific tables
DEFINE CONFIG OVERWRITE GRAPHQL TABLES INCLUDE foo;
```

When querying the GraphQL schema, only the included tables will be available.

### Example 3: Using Limit, Start, Order, and Filter in GraphQL Queries

You can use `limit`, `start`, `order`, and `filter` in your GraphQL queries to control the data returned.

#### Limit

```graphql
query {
foo(limit: 1) {
id
val
}
}
```

#### Start

```graphql
query {
foo(start: 1) {
id
val
}
}
```

#### Order

```graphql
query {
foo(order: { desc: val }) {
id
val
}
}
```

#### Filter

```graphql
query {
foo(filter: { val: { eq: 42 } }) {
id
val
}
}
```

## More Information

The `DEFINE CONFIG GRAPHQL` statement is essential for enabling and configuring the GraphQL API in SurrealDB. By specifying which tables and functions are included or excluded, you can fine-tune the GraphQL schema to match your application's needs.

- **Authentication**: Ensure you are authenticated with the appropriate credentials.
- **Permissions**: Set up permissions on tables and fields to control access via GraphQL.
- **Configuration**: The GraphQL configuration must be defined before using the GraphQL API.
- **Error Handling**: Be aware of possible errors when the configuration is missing or incomplete.

> [!IMPORTANT]
> Always ensure you have the necessary permissions and have selected the appropriate namespace and database before using the `DEFINE CONFIG GRAPHQL` statement.


## Summary

- Use `DEFINE CONFIG GRAPHQL` to enable and configure the GraphQL API.
- Define your tables and set up permissions to control data access.
- Use the `OVERWRITE` and `IF NOT EXISTS` clauses as needed to manage your configuration.
- Always authenticate with appropriate credentials when accessing the GraphQL API.
- Utilize GraphQL query features like `limit`, `start`, `order`, and `filter` to control the data returned.

By following these guidelines, you can effectively use the `DEFINE CONFIG GRAPHQL` statement to configure and interact with your SurrealDB database via GraphQL.