Skip to main content
The libSQL package is designed to work with database/sql to provide the usual methods you’d expect when working with databases in Go. In this Go quickstart we will learn how to:
  • Retrieve database credentials
  • Install Go libSQL
  • Connect to a local or remote Turso database
  • Execute a query using SQL
  • Sync changes to local database
1

Retrieve database credentials

You will need an existing database to continue. If you don’t have one, create one.Get the database URL:
turso db show --url <database-name>
Get the database authentication token:
turso db tokens create <database-name>
Assign credentials to the environment variables inside .env.
TURSO_DATABASE_URL=
TURSO_AUTH_TOKEN=
You will want to store these as environment variables.
2

Install

First begin by adding libSQL to your project:
go get github.com/tursodatabase/go-libsql
go get github.com/tursodatabase/libsql-client-go/libsql
3

Connect

Now connect to your local or remote database using the libSQL connector:
Starting a new project? Consider using Turso Database for Go — it offers concurrent writes, vector search, and a modern async engine built on the next evolution of SQLite.
package main

import (
  "database/sql"
  "fmt"
  "os"

  _ "github.com/tursodatabase/go-libsql"
)

func main() {
  dbName := "file:./local.db"

  db, err := sql.Open("libsql", dbName)
  if err != nil {
    fmt.Fprintf(os.Stderr, "failed to open db %s", err)
    os.Exit(1)
  }
  defer db.Close()
}
package main

import (
  "database/sql"
  "fmt"
  "os"

  _ "github.com/tursodatabase/libsql-client-go/libsql"
)

func main() {
  url := "libsql://[DATABASE].turso.io?authToken=[TOKEN]"

  db, err := sql.Open("libsql", url)
  if err != nil {
    fmt.Fprintf(os.Stderr, "failed to open db %s: %s", url, err)
    os.Exit(1)
  }
  defer db.Close()
}
4

Execute

You can execute a SQL query against your existing database. Create a function to query your database that accepts the pointer to sql.DB as an argument:
type User struct {
	ID   int
	Name string
}

func queryUsers(db *sql.DB)  {
  rows, err := db.Query("SELECT * FROM users")
  if err != nil {
    fmt.Fprintf(os.Stderr, "failed to execute query: %v\n", err)
    os.Exit(1)
  }
  defer rows.Close()

  var users []User

  for rows.Next() {
    var user User

    if err := rows.Scan(&user.ID, &user.Name); err != nil {
      fmt.Println("Error scanning row:", err)
      return
    }

    users = append(users, user)
    fmt.Println(user.ID, user.Name)
  }

  if err := rows.Err(); err != nil {
    fmt.Println("Error during rows iteration:", err)
  }
}
Now inside func main() call queryUsers and pass in the pointer to sql.DB:
queryUsers(db)
5

Sync

If you need to sync your local database with a remote Turso Cloud database (local reads and writes with push/pull to the cloud), use Turso Sync. Turso Sync is built on the Turso Database engine and provides true local-first sync with explicit push() and pull() operations.