5

I have a model like this:

type Course struct {
    Name string `db:"course_name"`
}

type Group struct {
    Course *Course
}
type Groups []Group

And when i try to do sqlx.Select for Groups with a query like this:

SELECT c.name as course_name FROM courses as c;

I get

missing destination name course_name in *main.Groups

error.

What is the issue with this code?

evocatus
  • 111
  • 1
  • 2
  • 8

3 Answers3

3

You need to use sqlx.Select when you are selecting multiple rows and you want to scan the result into a slice, as is the case for your query, otherwise use sqlx.Get for a single row.

In addition, you can't scan directly into a Group struct because none of its fields are tagged (unlike the Course struct), and the Course field isn't embedded.

Try:

course := Course{}
courses := []Course{}

db.Get(&course, "SELECT name AS course_name FROM courses LIMIT 1")
db.Select(&courses, "SELECT name AS course_name FROM courses")
Decade Moon
  • 32,968
  • 8
  • 81
  • 101
  • You don't need to tag every field in order to use it with sqlx as long as there is no ambiguity. I still don't understand why my code (in the question) doesn't work. Sqlx can't read struct tags through pointers? Sqlx can't scan values to structs through pointers? – evocatus Jul 08 '17 at 11:13
  • Do you need to tag the struct Course itself (as opposed to just the Names field)? ie: `db:"courses"` after the `}` of your Course struct? – 64bit_twitchyliquid Jul 08 '17 at 11:35
  • 2
    The error message explains exactly what the issue is: the `Group` struct has no field tagged `course_name`, therefore you can't scan into it. Either tag an appropriate field in the `Group` struct as `course_name`, or scan directly into a `Course` struct instead. – Decade Moon Jul 08 '17 at 11:36
  • If i have to scan directly than i don't need sqlx because it's like plain database/sql works. – evocatus Jul 08 '17 at 11:41
1

I changed Course *Course to Course Course - no effect. When i made it embedded like this:

type Group struct {
    Course
}

it worked.

This is also valid:

type Group struct {
    *Course
}

Looks like sqlx doesn't understand anything except embedded fields.

evocatus
  • 111
  • 1
  • 2
  • 8
1

Ok, so when you are using an embbeded struct with Sqlx, capitalization is important, at least in my case.

You need to refer to the embedded struct in your sql, like so:

select name as "course.name" from courses...

Notice that course is lower case and the naming involves a dot/period between table and column.

Then your Get or Select should work just fine.

transistor
  • 891
  • 1
  • 10
  • 15