sqlpostgresqlgogo-gorm

Gorm raw SQL query execution


I mm running an SQL query to check if a table exists using the Gorm library for Golang. Below is my code.

package main

import (
    "fmt"
    "log"

    "gorm.io/driver/postgres"
    "gorm.io/gorm"

    _ "github.com/lib/pq"
)

// App sets up and runs the app
type App struct {
    DB *gorm.DB
}

`const tableCreationQuery = `SELECT count (*) 
FROM information_schema.TABLES 
WHERE (TABLE_SCHEMA = 'api_test') AND (TABLE_NAME = 'Users')`

func ensureTableExists() {
    if err := a.DB.Exec(tableCreationQuery); err != nil {
        log.Fatal(err)
    }
}`

The expected response should be either 1 or 0. I got this from another Stack Overflow answer. Instead I get this:

2020/09/03 00:27:18 &{0xc000148900 1 0xc000119ba0 0} exit status 1 FAIL go-auth 0.287s

My untrained mind says its a pointer but how do I reference the returned values to determine what was contained within?


Solution

  • If you want to check if your SQL statement was successfully executed in GORM you can use the following:

    tx := DB.Exec(sqlStr, args...)
    
    if tx.Error != nil {
        return false
    }
    
    return true
    

    However in your example are using a SELECT statement then you need to check the result, which will be better suited to use the DB.Raw() method like below

    var exists bool
    DB.Raw(sqlStr).Row().Scan(&exists)
    return exists