georgysavva / scany

Library for scanning data from a database into Go structs and more
MIT License
1.31k stars 68 forks source link

How does struct mapping work? #144

Closed SharkFourSix closed 1 month ago

SharkFourSix commented 1 month ago

How does struct mapping work without using tags?

Does it depend on the order of the selected columns? If so, what happens if one executes something like this:

SELECT * FROM foo WHERE bar = 'baz';
georgysavva commented 1 month ago

Hi! When you say "tags," do you mean tags in Go struct fields or column tags in your database select statement?

If you don't provide Go struct tags, scany automatically translates your field names to snake case to match the columns in the database. If you don't specify column names in your select statement, the database just returns all the columns in the table with their default name. Note that by default, scany expects that your struct destination has the corresponding struct field for all the selected columns, so in the case of SELECT * FROM foo WHERE bar = 'baz';, your Go struct must contain fields for all the columns in the table. Since you can add a new column in a database migration and forget to change your Go code, doing SELECT * FROM foo WHERE bar = 'baz'; is not advisable. It's always better to list all the needed columns explicitly in your select statement.

Let me know if you have further questions.

SharkFourSix commented 1 month ago

@georgysavva

Tags are golang specific.

Anyway, I managed to just use the tags.