Creating a SQL generator app with ChatGPT, PostgreSQL, and ToolJet
Tags: sql, tooljet, javascript, chatgpt
Published: 2023-03-21 12:17:27

In this tutorial, you'll learn how to build a SQL Generator application using ChatGPT, ToolJet, and PostgreSQL.

Users can state the kind of data they want to retrieve from the database in plain English sentences, then ChatGPT converts them to the appropriate SQL syntax required to fetch the data from the database.
We'll be using ToolJet for the application interface.

## What is ToolJet?

[ToolJet](https://github.com/ToolJet/ToolJet) is an open-source low-code framework that enables us to build full-stack web applications within a few minutes. With ToolJet, you can create standalone fully-functional full-stack applications or embed applications into other websites.

ToolJet allows you to build applications that use relational and non-relational databases, REST APIs, and cloud storage like [Google Cloud Storage](https://cloud.google.com/storage), [AWS S3](https://aws.amazon.com/pm/serv-s3), and [Minio](https://min.io/). It is an excellent development tool helping individuals, developers, and businesses create and ship products faster.

**Before we continue**
I would be super happy if you could give us a star! And let me also know in the comments section. ❤️

[https://github.com/ToolJet/ToolJet](https://github.com/ToolJet/ToolJet)

![https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExZjlhNzRjMWJlYzgyNWZjYjcyOGMxYjJiYjQxOTQzYTU1NTg5YzAzNiZjdD1n/dfbMVqwq8GrC19xSEF/giphy.gif](https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExZjlhNzRjMWJlYzgyNWZjYjcyOGMxYjJiYjQxOTQzYTU1NTg5YzAzNiZjdD1n/dfbMVqwq8GrC19xSEF/giphy.gif)

## What is ChatGPT?

ChatGPT is the most talked about technology at the moment. It is an AI language model trained by [OpenAI](https://openai.com/) to answer questions, provide information, and engage in human language conversations with users.

[ChatGPT](https://openai.com/blog/chatgpt) performs tasks such as writing, debugging, and explaining code snippets. With its latest language model [GPT-4](https://openai.com/product/gpt-4), ChatGPT can accept images as prompts and provides answers based on the given prompt or commands.

In this article, we'll use ChatGPT to generate SQL query syntax from plain English words. Before we begin, let's set up the application's database.

## Setting up an ElephantSQL (PostgreSQL) database

[ElephantSQL](https://www.elephantsql.com/) enables us to create a PostgreSQL database on the cloud instead of your local machine. Follow the steps below to create a PostgreSQL database:

Create an ElephantSQL account [here](https://customer.elephantsql.com/login).

Add a new database instance. No credit card or billing information is required.

Once you've created the database instance, your database information is displayed.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f3b2z0bgxc582jgqwb30.png)

Congratulations! You've successfully created the database needed for this application. Next, let's design the application interface and connect the database to the application.

## Designing the application interface with ToolJet

Here, you'll learn how to create a ToolJet account and design a fully functional application with ToolJet.

If you are new to ToolJet, [create an account](https://app.tooljet.com/signup).

Create a Workspace and a new app called SQL Generator.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1zv6f21fhqw3k7mv8pk2.png)

Design a user interface similar to the image below. ToolJet enables you to create applications' interfaces by dragging and dropping various UI components.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fsqyog123m1lilrz4g6g.png)


From the image above, I added the following:

- the Table component with columns name and age,
- the Text component that serves as a form label,
- the TextInput component that accepts the SQL query in plain English.
- a read-only Text Input component that displays the generated SQL query, and
- two Buttons. One for generating the SQL query from ChatGPT and the other for executing the query on the PostgreSQL database.

## How to communicate with ChatGPT in ToolJet

Here, you'll learn how to communicate with ChatGPT via Rest API in ToolJet.

ToolJet allows us to communicate with external resources or create custom functions via a panel, known as [Query Panel](https://docs.tooljet.com/docs/app-builder/query-panel/). In ToolJet, any function that communicates with either of the following: database, API, cloud storage, and runs a JavaScript or Python code is called a Query.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4gmq8sopkt1kzcmyt2yn.png)

### Setting up an OpenAI account

Log in or create an OpenAI account [here](https://openai.com/product).

Click `Personal` on the navigation bar and select `View API keys` from the menu bar to create a new secret key.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/chcm65u0eof884a10jhl.png)


Generate a new API key and copy it somewhere on your computer. We'll use it in the upcoming section.

### Communicating with the ChatGPT API in ToolJet

On your Query Panel, select REST API and create a POST request to the ChatGPT endpoint - `https://api.openai.com/v1/chat/completions`.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lfznjk0calsn20u38p9g.png)


As shown in the image above, I added the following to the Query Headers variables.

```
Content-Type: application/json
Authorization: Bearer <YOUR_CHATGPT_API_KEY>
```

Enable Transformations and copy the code below into the code editor to retrieve the exact response needed from the request.

```jsx
const choices = data.choices[0];
return choices.message.content;
```

Click Body, enable Raw JSON, and copy the code below into the code editor - it contains parameters sent along with the POST request.

```json
{
	"model": "gpt-3.5-turbo",
	"messages": [
		{
			"role": "user",
			"content": "Write the SQL query for this operation: {{components.textarea1.value}}. I need only the SQL query. No explanations, please."
		}
	]
}
```

The code snippet above uses the GPT-3.5 Turbo model provided by OpenAI, and the content variable contains the prompt sent to the ChatGPT API.
ToolJet allows users to access the attributes and values of each component. Hence, the `{{components.textarea1.value}}` represents the value (plain English command) provided by the user.

> **PS:** Yours may not be `textarea1`, if so, change it to the component’s name for the user's input.
> 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2js3lqhnd9b9650xgv06.png)



Finally, click the `Save` button.🎉

So far, we've configured the ChatGPT query. Next, let's execute the query when a user clicks the `Generate SQL Command` button.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bek95zspe7cpr2p4hpmu.png)


From the image above, I added an `on Click` event to the button, and the ChatGPT query runs when a user clicks the button. It takes the user's input and sends a request for its equivalent SQL syntax when a user clicks the button.

To display the result, update the default value of the read-only Text Input component by setting it to `{{queries.chatgptQuery.data}}`.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p8ea6c3b3naehsykhrey.png)

Congratulations!🎊 You've been able to communicate with ChatGPT. Next, let's learn how to connect and communicate with the PostgreSQL database created earlier.

## How to communicate with a PostgreSQL database in ToolJet

Here, you'll learn how to communicate with a PostgreSQL database in ToolJet. First, let me walk you through connecting a PostgreSQL database to ToolJet.

### Connecting a PostgreSQL database to ToolJet

Click `Add a Datasource` from the Query Panel on ToolJet, select PostgreSQL from the list of databases, and provide the required information as shown below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9yetdsfc1jz10r7vq2nl.png)


From the image above, the host is the same as the server name on ElephantSQL (excluding the brackets). The username and database name are the same, and copy and paste the password into its field.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1wyvomrogzlmjz5bjss8.png)


Scroll down the page and click `Test Connection`.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tzrmg24c207azi3bk9f9.png)


If the connection is verified, we can start making queries to the database.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sr80ndfs5u756z2awhfi.png)


### Communicating the PostgreSQL database in ToolJet

Here, you'll learn how to send the SQL queries generated by ChatGPT to the PostgreSQL database and view the queried data within the Table component on the user interface.

Before we begin, let's add some data to the database. Click on the PostgreSQL query, select SQL mode, and run the code snippet below to create a new table containing the data below.``


`
CREATE TABLE People(NAME varchar(255), AGE int);
INSERT INTO People(name, age) VALUES(‘David’, 19);
INSERT INTO People(name, age) VALUES(‘Tabby’, 21);
INSERT INTO People(name, age) VALUES('Teja', 24);
INSERT INTO People(name, age) VALUES('Julius', 27);
INSERT INTO People(name, age) VALUES('Kedrick', 26);
SELECT * FROM people;
`


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tfaum4rn3zwsckqg2c6r.png)


You can view the data on ElephantSQL once it has been uploaded.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kyvvsz948dsk8168020.png)


Next, let's receive the SQL command from the ChatGPT and display the data within the Table component on the user interface.

Update the SQL editor to contain the query retrieved from ChatGPT and save it.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qfqwjvb9eqlhrcoev1cb.png)


Add an `on Click` event that runs the database query to the `Execute` button.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7bm8n8wqf5rxblnf6bqj.png)


Lastly, update the Table component to display the data retrieved from the database.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5he99rr43yc9d4it2a4j.png)


Congratulations!🎉 You've completed the application for this tutorial. Click the Release button and the share icon to host and make the application public.

Here is the desktop version of the application: [https://app.tooljet.com/applications/480a5bbb-3607-4c19-ac95-038d4e56cc2a](https://app.tooljet.com/applications/480a5bbb-3607-4c19-ac95-038d4e56cc2a).
You can also import this application into your ToolJet workspace by [downloading its JSON file](https://github.com/tejakummarikuntla/ToolJet-Sample-Apps/tree/main/SQL%20generator%20with%20ChatGPT)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7m2mwwlsotlyy0jsuqh5.gif)


## Conclusion

So far, you have learnt how to:

- add a PostgreSQL database to ToolJet
- communicate with ChatGPT via REST API in ToolJet, and
- design applications in a few minutes with ToolJet.

[ToolJet](https://github.com/ToolJet/ToolJet) is both an excellent development tool and open-source - meaning its code is readily available for everyone to modify and improve. It has a large [community](https://tooljet.slack.com/ssb/redirect) of developers and talented contributors constantly maintaining and improving the software. As a user, you can be sure of getting the best performance when you use ToolJet.

Are you interested in contributing to ToolJet? Feel free to check out our GitHub repo - [https://github.com/ToolJet/ToolJet](https://github.com/ToolJet/ToolJet) to contribute and raise issues about ToolJet.

Thank you for reading!