avatarTomas Svojanovsky

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2641

Abstract

ction)

<span class="hljs-keyword">defer</span> db.Close()

<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> { log.Fatal(err) }

<span class="hljs-keyword">if</span> err = db.Ping(); err != <span class="hljs-literal">nil</span> { log.Fatal(err) } }</pre></div><h2 id="e7f4">Test</h2><p id="035c">If everything works correctly we should be able to run this code without an error.</p><div id="db92"><pre>go run main.go</pre></div><h2 id="64db">Create a table</h2><p id="e0bb">To execute certain SQL queries, we require tables. Let’s create one using the <code>Exec</code> method.</p><p id="8e6b">Note that we need to pass a DB instance as a pointer.</p><div id="5453"><pre><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> { <span class="hljs-comment">// ... code</span>

createTodo(db) }

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">createTodo</span><span class="hljs-params">(db *sql.DB)</span></span> { query := <span class="hljs-string"> CREATE TABLE todo ( id SERIAL PRIMARY KEY, label TEXT NOT NULL, created_at TIMESTAMP DEFAULT NOW() ); </span>

_, err := db.Exec(query) 
    
<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
    log.Fatal(err)
}

}</pre></div><p id="fe11">After running the code, the expected outcome is the creation of a new table in the database.</p><figure id="e333"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*2NuMvqYyBPdZGeiwfbx-aw.png"><figcaption>Todo table in Supabase</figcaption></figure><h2 id="afdd">Insert data into the table</h2><div id="b42f"><pre><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> { <span class="hljs-comment">// code ...</span>

<span class="hljs-comment">// createTodo(db)</span> todo := Todo{label: <span class="hljs-string">"Walk a dog"</span>}

insertTodo(db, todo) }

<span class="hljs-keyword">type</span> Todo <span class="hljs-keyword">struct</span> { id <span class="hljs-type">int</span> label <span class="hljs-type">string</span> created_at <span class="hljs-type">string</span> }

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">insertTodo</span><span class="hljs-params">(db *sql.DB, todo Todo)</span></span> <span class="hljs-type">int

Options

</span> { query := <span class="hljs-string"> INSERT INTO todo (label) VALUES ($1) RETURNING id; </span>

<span class="hljs-keyword">var</span> primaryKey <span class="hljs-type">int</span> err := db.QueryRow(query, todo.label).Scan(&primaryKey)

<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> { log.Fatal(err) }

<span class="hljs-keyword">return</span> primaryKey }</pre></div><p id="9434">Now, let’s try executing the code, and we should see the newly created row in the database.</p><figure id="71cf"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*lCMUQSQTnIK4rhjB11czrw.png"><figcaption>A new row in the database</figcaption></figure><h2 id="cd4a">Fetch a row</h2><p id="01cf">We can use our struct to map the data with the <code>Scan</code> method. If there is no error, we should see the printed data from the database.</p><div id="7b87"><pre><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> { <span class="hljs-comment">// code ...</span>

query := <span class="hljs-string">"SELECT id, label, created_at FROM todo WHERE id = $1;"</span>

<span class="hljs-keyword">var</span> todo Todo

err = db.QueryRow(query, <span class="hljs-number">1</span>).Scan(&amp;todo.id, &amp;todo.label, &amp;todo.created_at)

<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
    log.Fatal(err)
}

fmt.Println(todo.id, todo.label, todo.created_at) <span class="hljs-comment">// 1 Walk a dog 2023-12-07T15:39:07.819697Z</span>

}</pre></div><p id="5831"><b>Thanks for reading my article!</b></p><p id="fca5">If you enjoyed the read and want to be part of our growing community, hit the follow button, and let’s embark on a knowledge journey together.</p><p id="9ac2">Your feedback and comments are always welcome, so don’t hold back!</p><h1 id="aa58">Stackademic</h1><p id="453b"><i>Thank you for reading until the end. Before you go:</i></p><ul><li><i>Please consider <b>clapping</b> and <b>following</b> the writer! 👏</i></li><li><i>Follow us on <a href="https://twitter.com/stackademichq"><b>Twitter(X)</b></a>, <a href="https://www.linkedin.com/company/stackademic"><b>LinkedIn</b></a>, and <a href="https://www.youtube.com/c/stackademic"><b>YouTube</b></a><b>.</b></i></li><li><i>Visit <a href="http://stackademic.com/"><b>Stackademic.com</b></a> to find out more about how we are democratizing free programming education around the world.</i></li></ul></article></body>

Go and PostgreSQL: A Seamless Data Journey with Supabase

If you’ve worked with Psycopg in Python, you’ll find many similarities here. If not, don’t worry — I’ll guide you through the straightforward process of connecting to PostgreSQL in a few steps. Additionally, we’ll cover creating a table, inserting data, and fetching it into variables. Let’s get started!

Note

I will use Supabase, but feel free to choose any other method for connecting to Postgres that suits you best.

Create a project

Create a file named main.go and initialize a Go module by running go mod init.

go mod init main

Install dependencies

go get github.com/lib/pq

Connection

What’s going on here?

  1. Credentials: The connection string for PostgreSQL is defined, specifying details such as the username, password, host, port, and database name.
  2. Connection Setup: The program opens a connection to the PostgreSQL database using the sql.Open method. The defer statement ensures that the database connection is closed when the main() function exits.
  3. Error Handling: The code checks for errors during the database connection setup. If an error occurs, the program logs the error and exits using log.Fatal().
  4. Connection Verification: The code uses the Ping method to verify the database connection. If the verification fails, an error is logged and the program exits. The code up to this point establishes a connection to the PostgreSQL database and ensures that the connection is successfully established without errors.
package main

import (
 "database/sql"
 "log"
 _ "github.com/lib/pq"
)

func main() {
   connection := "postgres://postgres:KPAuwVRd@[email protected]:5432/postgres"
  
   db, err := sql.Open("postgres", connection)
  
   defer db.Close()
  
   if err != nil {
      log.Fatal(err)
   }
  
   if err = db.Ping(); err != nil {
      log.Fatal(err)
   }
}

Test

If everything works correctly we should be able to run this code without an error.

go run main.go

Create a table

To execute certain SQL queries, we require tables. Let’s create one using the Exec method.

Note that we need to pass a DB instance as a pointer.

func main() {
   // ... code

   createTodo(db)
}

func createTodo(db *sql.DB) {
    query := `
        CREATE TABLE todo (
         id SERIAL PRIMARY KEY,
         label TEXT NOT NULL,
         created_at TIMESTAMP DEFAULT NOW()
        );
        `
        
    _, err := db.Exec(query) 
        
    if err != nil {
        log.Fatal(err)
    }
}

After running the code, the expected outcome is the creation of a new table in the database.

Todo table in Supabase

Insert data into the table

func main() {
   // code ...
  
   // createTodo(db)
   todo := Todo{label: "Walk a dog"}
  
   insertTodo(db, todo)
}

type Todo struct {
   id         int
   label      string
   created_at string
}

func insertTodo(db *sql.DB, todo Todo) int {
   query := `
      INSERT INTO todo (label) VALUES ($1) RETURNING id;
   `
  
   var primaryKey int
   err := db.QueryRow(query, todo.label).Scan(&primaryKey)
  
   if err != nil {
      log.Fatal(err)
   }
  
   return primaryKey
}

Now, let’s try executing the code, and we should see the newly created row in the database.

A new row in the database

Fetch a row

We can use our struct to map the data with the Scan method. If there is no error, we should see the printed data from the database.

func main() {
    // code ...

    query := "SELECT id, label, created_at FROM todo WHERE id = $1;"
    
    var todo Todo
    
    err = db.QueryRow(query, 1).Scan(&todo.id, &todo.label, &todo.created_at)
    
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Println(todo.id, todo.label, todo.created_at) // 1 Walk a dog 2023-12-07T15:39:07.819697Z
}

Thanks for reading my article!

If you enjoyed the read and want to be part of our growing community, hit the follow button, and let’s embark on a knowledge journey together.

Your feedback and comments are always welcome, so don’t hold back!

Stackademic

Thank you for reading until the end. Before you go:

  • Please consider clapping and following the writer! 👏
  • Follow us on Twitter(X), LinkedIn, and YouTube.
  • Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.
Software Development
Golang
Postgres
Supabase
Recommended from ReadMedium