D
D
deep_orange2014-09-29 17:29:56
SQL
deep_orange, 2014-09-29 17:29:56

Golang gorm querying a boolean from a database, not a table field, is that possible?

Hello. I use GORM to work with a Postgres database. In the psql console, I can simply query (does an origin column exist in the items table with such and such a value):

SELECT EXISTS( SELECT 1 FROM items WHERE origin = 'http://example.com/path' );
and get response:
?column?
----------
 t
(1 row)

At the same time, GORM itself provides the ability to execute an SQL query, but I can’t figure out how to get this value. Because all the examples given for use are based on the name of the column (column) in the database - and here it turns out that there is no column and `f` or `t` is not attached to anything. There is an option to bypass Gorm and use database / sql - which, in principle, does not bring it closer to the goal. As far as I understand, to get the value, you need to perform Scan( &VarOfType ), which is unacceptable (or I don't understand the end of the magic). Of course, I can just query the data from the table, but I don't need them - I just want to check if they exist or not.
Links:
gorm ( github | godoc )
database/sql to godoc
postgresql driver
udp
One of the options suggested by @sim3x works great, too bad he deleted the answer
var thd bool
x := mygormdb.Raw(`SELECT EXISTS( 
   SELECT 1 FROM items WHERE origin = 'http://www.infokam.su/n17724.html' ) 
as isfieldexists;`).Row()
x.Scan(&thd)
fmt.Println("Result:", thd)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tyranron, 2014-09-29
@deep_orange

On pure database/sql:

r, err := db.Query("SELECT 1 FROM items WHERE origin='http://example.com/path' LIMIT 1")
if err != nil {
    // Oops!
}
thisTableReallyHasThatRow := r.Next()
r.Close()

The same can be done on gorm using raw sql, or using RecordNotFound() to do something like this:
thisTableReallyHasThatRow := !db.Find(&Item{}, "origin = ?", "http://example.com/path").RecordNotFound()

M
melonnik, 2016-12-15
@melonnik

func isExist(vlan int) bool {
    var exists bool
    query := fmt.Sprintf("SELECT exists (%s)", "SELECT 1 FROM computers WHERE vlan=$1")
    err := db.QueryRow(query, vlan).Scan(&exists)
       if err != nil {
           // err
      }
    return exists
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question