Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long queries in golang

Tags:

go

This is a question based on absolute no knowledge of golang and the aim is to find if there is a way to make long queries readable.

My attempt is to put the sql text in a variable and then execute the variable.

Pseudocode (no real code):

var query = 
SELECT * FROM foo
UNION ALL
SELECT * FROM bar
UNION ALL
SELECT * FROM other
...

db.prepare (var query)
db.query (var query)

This is maybe a dumb question, but I have searched and found no clue how to make long queries more "readable" in go. Most examples are based on "hello world" level. In the real world queries can be quite long.

TIA,

like image 830
sibert Avatar asked Mar 27 '16 07:03

sibert


1 Answers

You can declare the query as a multiline string literal.

query := `
  SELECT * FROM foo
  UNION ALL
  SELECT * FROM bar
  UNION ALL
  SELECT * FROM other`

And use it with DB.Query.

rows, err := db.Query(query)

There are many different drivers for many different sql databases you can use. They all would give you a DB object to work with. So you can use DB.Prepare, DB.Query appropriately. Check docs of database/sql package for more info.

like image 91
Aruna Herath Avatar answered Oct 04 '22 02:10

Aruna Herath