Sqlx "missing destination name" for struct tag through pointer
Asked Answered
S

3

6

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?

Superincumbent answered 8/7, 2017 at 10:49 Comment(0)
O
5

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")
Orsay answered 8/7, 2017 at 10:56 Comment(4)
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?Superincumbent
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?Lawley
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.Orsay
If i have to scan directly than i don't need sqlx because it's like plain database/sql works.Superincumbent
S
2

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.

Superincumbent answered 8/7, 2017 at 11:38 Comment(0)
H
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.

Heterogenetic answered 25/4, 2018 at 16:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.