Skip to content

Commit 6b92d5c

Browse files
Merge pull request #66 from stepzen-dev/aswany/dbquery-custom-query-snippet
feat(snippet): add example for @dbquery with SQL queries
2 parents 0808d91 + 8f9a6f0 commit 6b92d5c

File tree

7 files changed

+221
-0
lines changed

7 files changed

+221
-0
lines changed

dbquery/custom-query/README.md

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
2+
# SQL Queries with `@dbquery`
3+
4+
This snippet demonstrates how to configure the `@dbquery` directive for custom SQL queries.
5+
6+
## Getting Started
7+
8+
[Install](https://www.ibm.com/docs/en/api-connect/ace/saas?topic=setting-up-your-environment) the StepZen command line interface.
9+
10+
To run these examples,
11+
12+
- `git clone` this repo
13+
- Change to the right working directory.
14+
- run `stepzen deploy`
15+
16+
This example uses a demo database filled with mock data, you can inspect the `config.yaml` file to find the credentials for this database. Also you can configure the connection in the `config.yaml` file by providing your database credentials.
17+
18+
Here’s a more generalized and specific description of the `@dbquery` directive functionality without referring to any particular data:
19+
20+
---
21+
22+
## The `@dbquery` Directive with SQL Query
23+
24+
The `@dbquery` directive in StepZen is used to connect your GraphQL API to databases and allows you to execute custom SQL queries within your schema. It supports various database types, such as MySQL, PostgreSQL, MSSQL, and Snowflake.
25+
26+
In this snippet, the `query` argument is used to define custom SQL queries for more control over the data being fetched. The functionality of the `query` argument allows for:
27+
28+
- Running complex SQL queries directly from GraphQL fields.
29+
- Retrieving data from specific columns or joining multiple tables based on your query requirements.
30+
- Filtering and querying data using SQL syntax when database field names or structures differ from the GraphQL schema.
31+
32+
The `query` argument provides the flexibility to write any SQL statement, while the **configuration** argument references the connection settings defined in the `config.yaml` file.
33+
34+
For example, a query may look like this:
35+
36+
```graphql
37+
@dbquery(
38+
query: "SELECT column1, column2 FROM your_table WHERE condition = $1",
39+
type: "postgresql",
40+
configuration: "your_config"
41+
)
42+
```
43+
44+
This allows you to fetch exactly the data you need, based on the custom SQL query provided. You can adjust the queries to match your database schema and use case.
45+
46+
## Try it Out!
47+
48+
Deploy the schema from `dbquery/custom-query` relative to the repository's root directory:
49+
50+
```
51+
stepzen deploy
52+
```
53+
54+
Run the [sample operations](operations.graphql):
55+
56+
- **Fetch all customers**:
57+
```
58+
stepzen request -f operations.graphql --operation-name=Customers
59+
```
60+
61+
- **Fetch a customer by ID**:
62+
```
63+
stepzen request -f operations.graphql --operation-name=Customer --var id=1
64+
```
65+

dbquery/custom-query/api.graphql

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# This example shows how @dbquery is configured for custom SQL queries with Customer data.
2+
3+
"""
4+
Represents a customer in the system, stored in the 'customer' table of a PostgreSQL database.
5+
Each customer has an ID, name, and email. The 'Customer' type maps directly to the
6+
corresponding table fields.
7+
"""
8+
type Customer {
9+
id: ID!
10+
name: String
11+
email: String
12+
}
13+
14+
"""
15+
Defines the root-level queries for fetching customer data.
16+
These queries use the `@dbquery` directive to execute custom SQL queries.
17+
The SQL queries include parameter markers, which correspond to the GraphQL field arguments.
18+
19+
The 'customer' table in PostgreSQL has the following structure:
20+
21+
CREATE TABLE customer (
22+
id SERIAL PRIMARY KEY, -- Unique identifier with sequence
23+
name CHARACTER(50) NOT NULL, -- Customer's name, max 50 characters
24+
email CHARACTER(50) NOT NULL, -- Customer's email, max 50 characters, must be unique
25+
CONSTRAINT customer_email_key UNIQUE (email) -- Unique constraint on email
26+
);
27+
These queries demonstrate basic SQL interactions with this table.
28+
"""
29+
type Query {
30+
"""
31+
Fetches a list of all customers from the database.
32+
33+
The custom SQL query retrieves the `id`, `name`, and `email` fields from the 'customer' table.
34+
35+
**@dbquery Directive Usage**:
36+
- `query`: This is the SQL query that will be executed. Here, it fetches all records from the 'customer' table.
37+
- `type`: Specifies the type of database being queried. In this case, it’s a PostgreSQL database.
38+
- `configuration`: References the database configuration (connection details) in StepZen.
39+
40+
This field does not take any arguments, and hence there are no parameter markers in the SQL query.
41+
The SQL query is static, always returning all customers from the database.
42+
"""
43+
customers: [Customer]
44+
@dbquery(
45+
query: "SELECT id, name, email FROM customer"
46+
type: "postgresql"
47+
configuration: "postgresql_config"
48+
)
49+
50+
"""
51+
Fetches a single customer by their ID from the database.
52+
53+
**Field Argument to Parameter Marker Mapping**:
54+
- Maps the `id` argument to the `$1` marker in the SQL query, allowing dynamic ID-based retrieval.
55+
- `$1` serves as a placeholder, which will be replaced by the provided `id` value during execution.
56+
57+
**@dbquery Directive Usage**:
58+
- `query`: This is the SQL query that will be executed. Here, the customer data is fetched based on the provided `id` value.
59+
- The `$1` marker is a placeholder for the value of the `id` argument, which is passed as a variable when executing the query.
60+
- `type`: Specifies the type of database being queried (PostgreSQL).
61+
- `configuration`: References the database configuration (connection details) in StepZen.
62+
63+
This field requires an `id` argument as input, which is passed as a variable from the GraphQL request. The variable's value is used to fetch the corresponding customer from the database.
64+
"""
65+
customer(id: Int!): Customer
66+
@dbquery(
67+
query: "SELECT id, name, email FROM customer WHERE id = $1"
68+
type: "postgresql"
69+
configuration: "postgresql_config"
70+
)
71+
}

dbquery/custom-query/config.yaml

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
configurationset:
2+
- configuration:
3+
name: postgresql_config
4+
uri: postgresql://postgresql.introspection.stepzen.net/introspection?user=testUserIntrospection&password=HurricaneStartingSample1934

dbquery/custom-query/index.graphql

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
schema @sdl(files: ["api.graphql"]) {
2+
query: Query
3+
}
+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Retrieve a specific customer by ID using a variable
2+
query Customer($id: Int!) {
3+
customer(id: $id) {
4+
id
5+
name
6+
email
7+
}
8+
}
9+
10+
# Retrieve all customers in the system
11+
query Customers {
12+
customers {
13+
id
14+
name
15+
email
16+
}
17+
}
+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"endpoint": "api/miscellaneous"
3+
}
4+

dbquery/custom-query/tests/Test.js

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
const fs = require("fs");
2+
const path = require("node:path");
3+
const {
4+
deployAndRun,
5+
stepzen,
6+
getTestDescription,
7+
} = require("../../../tests/gqltest.js");
8+
9+
testDescription = getTestDescription("snippets", __dirname);
10+
11+
// Read the GraphQL operations from the operations file
12+
const requestsFile = path.join(path.dirname(__dirname), "operations.graphql");
13+
const requests = fs.readFileSync(requestsFile, "utf8").toString();
14+
15+
describe(testDescription, function () {
16+
17+
const tests = [
18+
{
19+
label: "fetch all customers",
20+
query: requests,
21+
operationName: "Customers",
22+
variables: {},
23+
expected: {
24+
customers: [
25+
{ id: "1", name: "Lucas Bill ", email: "[email protected] " },
26+
{ id: "2", name: "Mandy Jones ", email: "[email protected] " },
27+
{ id: "3", name: "Salim Ali ", email: "[email protected] " },
28+
{ id: "4", name: "Jane Xiu ", email: "[email protected] " },
29+
{ id: "5", name: "John Doe ", email: "[email protected] " },
30+
{ id: "6", name: "Jane Smith ", email: "[email protected] " },
31+
{ id: "7", name: "Sandeep Bhushan ", email: "[email protected] " },
32+
{ id: "8", name: "George Han ", email: "[email protected] " },
33+
{ id: "9", name: "Asha Kumari ", email: "[email protected] " },
34+
{ id: "10", name: "Salma Khan ", email: "[email protected] " }
35+
]
36+
},
37+
},
38+
{
39+
label: "fetch customer by ID",
40+
query: requests,
41+
operationName: "Customer",
42+
variables: {
43+
id: 1
44+
},
45+
expected: {
46+
customer: {
47+
id: "1",
48+
name: "Lucas Bill ",
49+
50+
}
51+
},
52+
},
53+
];
54+
55+
// Run the tests against the deployed schema
56+
return deployAndRun(__dirname, tests, stepzen.admin);
57+
});

0 commit comments

Comments
 (0)