4

I have a database calendar with tsrange type from postgres. It allows me to have multiple appointments and time range such as :

["2018-11-08 10:00:00","2018-11-08 10:45:00"]

How do I store this value in a Go variable ?

I tried

var tsrange []string

And when I log tsrange[0] it is empty. What is the proper type for it ?

More code :

rows, err := db.Query("SELECT * FROM appointments")
utils.CheckErr(err)

var id int
var userID int
var tsrange []string

rows.Next()
err = rows.Scan(&id, &userID, &tsrange)

fmt.Println(tsrange[0])

When I replace var tsrange []string with var tsrange string the log is ["2018-11-08 10:00:00","2018-11-08 10:45:00"].

3
  • Try var tsrange []time.Time. BTW which db driver you're using? Commented Nov 8, 2018 at 8:13
  • What does the error tell you? Commented Nov 8, 2018 at 8:18
  • Getting index out of range when logging tsrange[0] and an empty array when logging tsrange while setting var tsrange []time.Time. Driver used is the pq package (github.com/lib/pq). Commented Nov 8, 2018 at 8:20

1 Answer 1

6

You should be able to retrieve the individual bounds of a range at the sql level.

// replace tsrange_col with the name of your tsrange column
rows, err := db.Query("SELECT id, user_id, lower(tsrange_col), upper(tsrange_col) FROM appointments")
utils.CheckErr(err)

var id int
var userID int
var tsrange [2]time.Time

rows.Next()
err = rows.Scan(&id, &userID, &tsrange[0], &tsrange[1])

fmt.Println(tsrange[0]) // from
fmt.Println(tsrange[1]) // to
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.