Skip to content
Advertisement

How to create SQL query with multiple JSON parameters in golang application?

As you can see in my Golang application I have an array called layers.

I want to insert data of that array to the table of the PostgreSQL database. My question is how to create such SQL query in the application?

QUERY:

Advertisement

Answer

Because I cannot comment, I assume that:

  1. You’re using golang’s database/sql or similar package.
  2. In your database, details column has type JSONB

A simple approach is to loop your slice layers and build query string to this:

For id and city, you can pass the params easily, however you need to pass JSON bytes for details. Which means, you’ll need to marshal Details struct to JSON bytes for insert/update and unmarshal ‘details’ result to struct when SELECT

You will need to:

  1. Define new struct that encapsulates the slice of Detail (we’ll call it Details) then the Details should implement these interfaces.
  2. Implements driver.Valuer interface to convert Details to JSON byte slice that can be understood by the database
  3. Implements sql.Scanner interface to unmarshal JSON byte slice from database to your struct

The code should look like this:

The complete code:

Reference:

https://www.alexedwards.net/blog/using-postgresql-jsonb

https://golang.org/pkg/database/sql/

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement