avm99963 | 83f8f29 | 2021-08-24 18:26:52 +0200 | [diff] [blame^] | 1 | package db |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "fmt" |
| 7 | |
| 8 | pb "gomodules.avm99963.com/twpt-server/api_proto" |
| 9 | ) |
| 10 | |
| 11 | func GetFeatureByCodename(db *sql.DB, ctx context.Context, codename string) (*pb.Feature, error) { |
| 12 | query := db.QueryRowContext(ctx, "SELECT feat_id, codename, feat_type FROM Feature WHERE codename = ?", codename) |
| 13 | var f pb.Feature |
| 14 | if err := query.Scan(&f.Id, &f.Codename, &f.Type); err != nil { |
| 15 | if err == sql.ErrNoRows { |
| 16 | return nil, nil |
| 17 | } |
| 18 | return nil, fmt.Errorf("Error while querying feature by codename: %v.", err) |
| 19 | } |
| 20 | return &f, nil |
| 21 | } |
| 22 | |
| 23 | func ListFeatures(db *sql.DB, ctx context.Context, withDeprecatedFeatures bool) ([]*pb.Feature, error) { |
| 24 | var rows *sql.Rows |
| 25 | var err error |
| 26 | if withDeprecatedFeatures { |
| 27 | rows, err = db.QueryContext(ctx, "SELECT feat_id, codename, feat_type FROM Feature") |
| 28 | } else { |
| 29 | rows, err = db.QueryContext(ctx, "SELECT feat_id, codename, feat_type FROM Feature WHERE feat_type <> ?", pb.Feature_TYPE_DEPRECATED) |
| 30 | } |
| 31 | if err != nil { |
| 32 | return nil, fmt.Errorf("ListFeatures: ", err) |
| 33 | } |
| 34 | defer rows.Close() |
| 35 | |
| 36 | var features []*pb.Feature |
| 37 | for rows.Next() { |
| 38 | var f pb.Feature |
| 39 | if err := rows.Scan(&f.Id, &f.Codename, &f.Type); err != nil { |
| 40 | return nil, fmt.Errorf("ListFeatures: ", err) |
| 41 | } |
| 42 | features = append(features, &f) |
| 43 | } |
| 44 | if err := rows.Err(); err != nil { |
| 45 | return nil, fmt.Errorf("ListFeatures: ", err) |
| 46 | } |
| 47 | return features, nil |
| 48 | } |
| 49 | |
| 50 | func AddFeature(db *sql.DB, ctx context.Context, f *pb.Feature) error { |
| 51 | _, err := db.ExecContext(ctx, "INSERT INTO Feature (codename, feat_type) VALUES (?, ?)", f.Codename, f.Type) |
| 52 | return err |
| 53 | } |
| 54 | |
| 55 | func UpdateFeature(db *sql.DB, ctx context.Context, id int32, f *pb.Feature) error { |
| 56 | _, err := db.ExecContext(ctx, "UPDATE Feature SET feat_type = ? WHERE id = ?", f.Type, id) |
| 57 | return err |
| 58 | } |