Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gorm raw SQL query execution

I'm running a 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?

like image 780
jkerone Avatar asked Jun 28 '26 13:06

jkerone


1 Answers

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
like image 151
Milan Avatar answered Jun 30 '26 03:06

Milan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!