Skip to main content

Go

Relyt supports the PostgreSQL connection protocol, which means any tools or software that can connect to PostgreSQL can also be used for Relyt connections.

This guide will walk you through the process of connecting to Relyt using Go or Golang.

1. Prepare the environment

Initialize a module and obtain the PostgreSQL Go module:

cd <your-working-directory>
go mod init relyt_demo_go
go get github.com/lib/pq

2. Create a Go program

  1. Create a .go file:

    vim relyt_demo.go
  2. Write the program code in the file:

    package main

    import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/lib/pq"
    )

    const (
    host = "<endpoint_domain>"
    port = <endpoint_port>
    user = "<dw_user>"
    password = "<dw_user_password>"
    dbname = "<database>"
    )

    func main() {
    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
    "password=%s dbname=%s sslmode=disable",
    host, port, user, password, dbname)

    db, err := sql.Open("postgres", psqlInfo)
    if err != nil {
    panic(err)
    }
    defer db.Close()

    _, err = db.Exec("DROP TABLE IF EXISTS items;")
    if err != nil {
    log.Fatal(err)
    }

    _, err = db.Exec("CREATE TABLE IF NOT EXISTS items (id INTEGER, name VARCHAR);")
    if err != nil {
    log.Fatal(err)
    }

    _, err = db.Exec("INSERT INTO items (id, name) VALUES (1, 'item1'), (2, 'item2');")
    if err != nil {
    log.Fatal(err)
    }

    rows, err := db.Query("SELECT * FROM items;")
    if err != nil {
    log.Fatal(err)
    }
    defer rows.Close()

    for rows.Next() {
    var id int
    var name string
    err = rows.Scan(&id, &name)
    if err != nil {
    log.Fatal(err)
    }
    fmt.Println(id, name)
    }

    err = rows.Err()
    if err != nil {
    log.Fatal(err)
    }
    }

    The following table describes the constants declared in const(). Set them based on your actual conditions.

    ConstantDescription
    hostThe public endpoint for connecting to the Relyt DW service unit.
    portThe port for connecting to the Relyt DW service unit. The default port is 5432.
    userThe name of the DW user that connects to the Relyt DW service unit.
    passwordThe password of the DW user.
    dbnameThe name of the Relyt database to connect.

    The SQL commands provided in the example perform the following operations in sequence:

    • Drop a table named items if it exists

    • Create a table named items

    • Insert data to table items

    • Query data from items

    They are for reference only. You can replace them with any SQL commands you want to run.

3. Run the program

Run the program:

go build relyt_demo.go
./relyt_demo