/
usda.go
284 lines (240 loc) · 7.25 KB
/
usda.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package db
import (
"context"
"fmt"
"strings"
"sync"
sq "github.com/Masterminds/squirrel"
"gopkg.in/guregu/null.v4/zero"
)
type Food struct {
Description string `db:"description"`
DataType string `db:"data_type"`
FdcID int `db:"fdc_id"`
CategoryID zero.Int `db:"food_category_id"`
}
type Foods []Food
func (c *Client) GetFood(ctx context.Context, fdcID int) (*Food, error) {
ctx, span := c.tracer.Start(ctx, "GetFood")
defer span.End()
q := c.psql.Select(
"food_category_id",
"data_type",
"description",
"fdc_id",
).From("usda_food").Where(sq.Eq{"fdc_id": fdcID})
f := &Food{}
return f, c.getContext(ctx, q, f)
}
func (c *Client) getFoods(ctx context.Context, addons func(q sq.SelectBuilder, count bool) sq.SelectBuilder) ([]Food, uint64, error) {
favoriteBrands := []string{
// brands
"Guittard Chocolate Co.",
"Bob's Red Mill Natural Foods, Inc.",
"The King Arthur Flour Company, Inc.",
// stores
"'Whole Foods Market, Inc.",
"WHOLE FOODS MARKET",
"TRADER JOE'S",
"Target Stores",
"Kikkoman Sales USA, Inc.",
}
for x := range favoriteBrands {
// escape single quote
favoriteBrands[x] = strings.ReplaceAll(favoriteBrands[x], "'", "''")
}
ctx, span := c.tracer.Start(ctx, "getFoods")
defer span.End()
q := c.psql.Select(
"food_category_id",
"data_type",
"description",
"usda_food.fdc_id as fdc_id",
).From("usda_food").
LeftJoin("usda_branded_food on usda_food.fdc_id = usda_branded_food.fdc_id").
OrderBy(fmt.Sprintf(`array_position(array['%s'], brand_owner)`, strings.Join(favoriteBrands, "','"))).
OrderBy("length(ingredients) asc") // shorter ingredient list = more likely to be 'pure'
cq := c.psql.Select("count(*)").From("usda_food")
q = addons(q, false)
cq = addons(cq, true)
cq = cq.RemoveLimit().RemoveOffset()
res := []Food{}
var count uint64
numQueries := 2
var wg sync.WaitGroup
wg.Add(numQueries)
errs := make(chan error, numQueries)
go func() {
if err := c.selectContext(ctx, q, &res); err != nil {
errs <- err
}
wg.Done()
}()
go func() {
if err := c.getContext(ctx, cq, &count); err != nil {
errs <- err
}
wg.Done()
}()
wg.Wait()
close(errs)
if len(errs) > 0 {
return nil, 0, <-errs
}
return res, count, nil
}
func (c *Client) SearchFoods(ctx context.Context, searchQuery string, dataType []string, foodCategoryID *int, opts ...SearchOption) ([]Food, uint64, error) {
ctx, span := c.tracer.Start(ctx, "GetIngrientsSameAs")
defer span.End()
return c.getFoods(ctx, func(q sq.SelectBuilder, count bool) sq.SelectBuilder {
w := `description ILIKE '%' || $1 || '%'`
q = q.Where(w, searchQuery)
q = newSearchQuery(opts...).apply(q)
if foodCategoryID != nil {
q = q.Where(sq.Eq{"food_category_id": &foodCategoryID})
}
if len(dataType) > 0 {
q = q.Where(sq.Eq{"data_type": dataType})
}
if !count {
q = q.OrderBy("length(description) ASC", "fdc_id DESC")
}
return q
})
}
func (c *Client) FoodsByIds(ctx context.Context, ids []int) ([]Food, uint64, error) {
ctx, span := c.tracer.Start(ctx, "FoodsByIds")
defer span.End()
return c.getFoods(ctx, func(q sq.SelectBuilder, count bool) sq.SelectBuilder {
q = q.Where(sq.Eq{"usda_food.fdc_id": ids})
if !count {
q = q.OrderBy("usda_food.fdc_id DESC")
}
return q
})
}
type FoodNutrient struct {
FdcID int `db:"fdc_id"`
NutrientID int `json:"nutrient" db:"nutrient_id"`
Amount float64 `json:"amount" db:"amount"`
DataPoints zero.Int `json:"data_points" db:"data_points"`
}
type FoodNutrients []FoodNutrient
func (c *Client) GetFoodNutrients(ctx context.Context, fdcID ...int) (FoodNutrients, error) {
ctx, span := c.tracer.Start(ctx, "GetFoodNutrients")
defer span.End()
q := c.psql.Select(
"nutrient_id",
"amount",
"data_points",
).From("usda_food_nutrient").Where(sq.Eq{"fdc_id": fdcID})
fns := []FoodNutrient{}
err := c.selectContext(ctx, q, &fns)
if err != nil {
return nil, fmt.Errorf("failed to select: %w", err)
}
return fns, nil
}
type Nutrient struct {
ID int `json:"id"`
Name string `json:"name"`
UnitName string `json:"unitName"`
}
type Nutrients []Nutrient
func (r Nutrients) ById() map[int]Nutrient {
m := make(map[int]Nutrient)
for _, x := range r {
m[x.ID] = x
}
return m
}
func (c *Client) GetNutrients(ctx context.Context, nutrientID ...int) (Nutrients, error) {
ctx, span := c.tracer.Start(ctx, "GetNutrients")
defer span.End()
q := c.psql.Select("id", "name", "unit_name AS unitName").From("usda_nutrient").Where(sq.Eq{"id": nutrientID})
ns := []Nutrient{}
err := c.selectContext(ctx, q, &ns)
if err != nil {
return nil, fmt.Errorf("failed to select: %w", err)
}
return ns, nil
}
func (c *Client) GetCategory(ctx context.Context, categoryID int64) (*FoodCategory, error) {
ctx, span := c.tracer.Start(ctx, "GetCategory")
defer span.End()
q := c.psql.Select(
"code",
"description",
).From("usda_food_category").Where(sq.Eq{"id": categoryID})
x := &FoodCategory{}
err := c.getContext(ctx, q, x)
if err != nil {
return nil, fmt.Errorf("failed to select: %w", err)
}
return x, nil
}
func (c *Client) GetBrandInfo(ctx context.Context, fdcID int) (*BrandedFood, error) {
ctx, span := c.tracer.Start(ctx, "GetBrandInfo")
defer span.End()
q := c.psql.Select(
"brand_owner",
"ingredients",
"serving_size",
"serving_size_unit",
"household_serving_fulltext",
"branded_food_category",
).From("usda_branded_food").Where(sq.Eq{"fdc_id": fdcID})
x := &BrandedFood{}
err := c.getContext(ctx, q, x)
if err != nil {
return nil, fmt.Errorf("faileo select: %w", err)
}
return x, nil
}
type BrandedFood struct {
BrandOwner *string `db:"brand_owner"`
Ingredients *string `db:"ingredients"`
ServingSize float64 `db:"serving_size"`
ServingSizeUnit string `db:"serving_size_unit"`
HouseholdServing *string `db:"household_serving_fulltext"`
BrandedFoodCategory *string `db:"branded_food_category"`
}
type FoodCategory struct {
Code string `json:"code"`
Description string `json:"description"`
}
type FoodPortion struct {
Id int `db:"id"`
FdcID int `db:"fdc_id"`
Amount zero.Float `db:"amount"`
GramWeight float64 `db:"gram_weight"`
Modifier zero.String `db:"modifier"`
PortionDescription zero.String `db:"portion_description"`
}
type FoodPortions []FoodPortion
func (r FoodPortions) ByFdcId() map[int][]FoodPortion {
m := make(map[int][]FoodPortion)
for _, x := range r {
m[x.FdcID] = append(m[x.FdcID], x)
}
return m
}
func (c *Client) GetFoodPortions(ctx context.Context, fdcId ...int) (FoodPortions, error) {
ctx, span := c.tracer.Start(ctx, "GetFoodPortions")
defer span.End()
q := c.psql.Select("id", "fdc_id", "amount", "portion_description", "modifier", "gram_weight").
From("usda_food_portion").Where(sq.Eq{"fdc_id": fdcId})
ns := []FoodPortion{}
err := c.selectContext(ctx, q, &ns)
if err != nil {
return nil, fmt.Errorf("failed to select: %w", err)
}
return ns, nil
}
func (c *Client) AssociateFoodWithIngredient(ctx context.Context, ingredient string, fdcId int) error {
ctx, span := c.tracer.Start(ctx, "AssociateFoodWithIngredient")
defer span.End()
q := c.psql.Update("ingredients").Set("fdc_id", fdcId).Where(sq.Eq{"id": ingredient})
_, err := c.execContext(ctx, q)
return err
}