How to Use Dotsql: A Golang Library for SQL Management

May 12, 2024 | Programming

Are you a Go developer looking for an efficient way to manage SQL queries in your projects? Dotsql might be the perfect solution for you! It’s a simple yet powerful library that keeps your SQL queries organized in files, making them easy to use without the complexity of an ORM or query builder. In this guide, we’ll walk through the steps to integrate and utilize Dotsql in your application effectively.

Getting Started with Dotsql

To get started with Dotsql, you’ll first need to install it. Follow these simple steps:

  • Open your terminal.
  • Run the following command to install Dotsql:
$ go get github.com/qustavodotsql

Defining Queries in SQL Files

Next, you need to define your SQL queries inside a SQL file. Each query must have a unique name for identification. Here’s how to set it up:

-- name: create-users-table
CREATE TABLE users (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    name VARCHAR(255),
    email VARCHAR(255));

-- name: create-user
INSERT INTO users (name, email) VALUES(?, ?);

-- name: find-users-by-email
SELECT id, name, email FROM users WHERE email = ?;

-- name: find-one-user-by-email
SELECT id, name, email FROM users WHERE email = ? LIMIT 1;

-- name: drop-users-table
DROP TABLE users;

In the example above, every SQL command is prefixed with a unique name declared using -- name:, allowing Dotsql to identify and run the correct query.

Loading and Executing Queries

Once your SQL file is ready, you can start using its queries in your Go application. Here’s a typical flow:

  1. Open a database connection.
  2. Load the SQL queries from your file.
  3. Execute the desired queries.

The code snippet below illustrates this process:

db, err := sql.Open("sqlite3", ":memory:") // Opens an in-memory database
dot, err := dotsql.LoadFromFile("queries.sql") // Loads queries from the file

// Running queries
res, err := dot.Exec(db, "create-users-table") // Executes table creation
res, err := dot.Exec(db, "create-user", "User Name", "main@example.com") // Inserts a record
rows, err := dot.Query(db, "find-users-by-email", "main@example.com") // Finds users by email
row, err := dot.QueryRow(db, "find-one-user-by-email", "user@example.com") // Finds one user
stmt, err := dot.Prepare(db, "drop-users-table") // Prepares statement
result, err := stmt.Exec() // Executes drop table

Here, think of the entire process like folder organization. The SQL files act like folders where you keep important documents (your queries). When you need a specific document, you simply open the correct folder and take what you need. This promotes clean design and keeps your queries accessible.

Merging Multiple Dotsql Instances

If your project requires multiple SQL files, you can also merge different Dotsql instances together. This allows you to have all your queries in a single, organized manner. Here’s how you can do it:

dot1, err := dotsql.LoadFromFile("queries1.sql") // Load first SQL file
dot2, err := dotsql.LoadFromFile("queries2.sql") // Load second SQL file
dot := dotsql.Merge(dot1, dot2) // Merge both instances

Text Interpolation

Dotsql also supports template style text interpolation. This lets you pass dynamic values into your SQL queries seamlessly. Use it as follows:

dot.WithData(map[string]any{"exclude_deleted": true}).Query(db, "count-users")
// SQL Query: SELECT count(*) FROM users IF .exclude_deleted WHERE deleted IS NULL END

This feature makes your SQL queries flexible and responsive to various inputs, enhancing the dynamism of your application.

Troubleshooting

If you encounter any issues while using Dotsql, consider these troubleshooting ideas:

  • Ensure that your SQL file is correctly formatted with proper naming conventions for the queries.
  • Check your database connection string for accuracy.
  • Make sure that your SQL file path is correct when loading queries.
  • Look for detailed error messages that might give insight into what went wrong.

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Embedding SQL Files

If you prefer not to distribute SQL files with your compiled binary, consider using tools like gotic. This allows you to embed all SQL files neatly within your executable, simplifying deployment.

Support for SQLX

Should you require support for sqlx, you can check out dotsqlx. This extension enhances Dotsql’s functionality to work seamlessly with the SQLX library.

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox