This commit is contained in:
Matthew Dillon 2015-10-02 16:20:07 -07:00
parent a880fdea82
commit efb0cc13fa
41 changed files with 569 additions and 386 deletions

View file

@ -11,9 +11,10 @@ import (
)
func init() {
DB.AddTableWithName(CharacteristicBase{}, "characteristics").SetKeys(true, "Id")
DB.AddTableWithName(CharacteristicBase{}, "characteristics").SetKeys(true, "ID")
}
// PreInsert is a modl hook
func (c *CharacteristicBase) PreInsert(e modl.SqlExecutor) error {
ct := helpers.CurrentTime()
c.CreatedAt = ct
@ -21,15 +22,17 @@ func (c *CharacteristicBase) PreInsert(e modl.SqlExecutor) error {
return nil
}
// PreUpdate is a modl hook
func (c *CharacteristicBase) PreUpdate(e modl.SqlExecutor) error {
c.UpdatedAt = helpers.CurrentTime()
return nil
}
// CharacteristicBase is what the DB expects for write operations
type CharacteristicBase struct {
Id int64 `json:"id,omitempty"`
ID int64 `json:"id,omitempty"`
CharacteristicName string `db:"characteristic_name" json:"characteristicName"`
CharacteristicTypeId int64 `db:"characteristic_type_id" json:"-"`
CharacteristicTypeID int64 `db:"characteristic_type_id" json:"-"`
SortOrder types.NullInt64 `db:"sort_order" json:"sortOrder"`
CreatedAt types.NullTime `db:"created_at" json:"createdAt"`
UpdatedAt types.NullTime `db:"updated_at" json:"updatedAt"`
@ -39,6 +42,8 @@ type CharacteristicBase struct {
DeletedBy types.NullInt64 `db:"deleted_by" json:"deletedBy"`
}
// Characteristic is what the DB expects for read operations, and is what the API
// expects to return to the requester.
type Characteristic struct {
*CharacteristicBase
Measurements types.NullSliceInt64 `db:"measurements" json:"measurements"`
@ -47,12 +52,15 @@ type Characteristic struct {
CanEdit bool `db:"-" json:"canEdit"`
}
// Characteristics are multiple characteristic entities
type Characteristics []*Characteristic
// CharacteristicMeta stashes some metadata related to the entity
type CharacteristicMeta struct {
CanAdd bool `json:"canAdd"`
}
// ListCharacteristics returns all characteristics
func ListCharacteristics(opt helpers.ListOptions, claims *types.Claims) (*Characteristics, error) {
var vals []interface{}
@ -66,9 +74,9 @@ func ListCharacteristics(opt helpers.ListOptions, claims *types.Claims) (*Charac
INNER JOIN characteristic_types ct ON ct.id=c.characteristic_type_id`
vals = append(vals, opt.Genus)
if len(opt.Ids) != 0 {
if len(opt.IDs) != 0 {
var counter int64 = 2
w := helpers.ValsIn("c.id", opt.Ids, &vals, &counter)
w := helpers.ValsIn("c.id", opt.IDs, &vals, &counter)
q += fmt.Sprintf(" WHERE %s", w)
}
@ -89,97 +97,106 @@ func ListCharacteristics(opt helpers.ListOptions, claims *types.Claims) (*Charac
return &characteristics, nil
}
// StrainOptsFromCharacteristics returns the options for finding all related strains
// for a set of characteristics.
func StrainOptsFromCharacteristics(opt helpers.ListOptions) (*helpers.ListOptions, error) {
relatedStrainIds := make([]int64, 0)
var relatedStrainIDs []int64
baseQ := `SELECT DISTINCT m.strain_id
FROM measurements m
INNER JOIN strains st ON st.id=m.strain_id
INNER JOIN species sp ON sp.id=st.species_id
INNER JOIN genera g ON g.id=sp.genus_id AND LOWER(g.genus_name)=LOWER($1)`
if opt.Ids == nil {
if opt.IDs == nil {
q := fmt.Sprintf("%s;", baseQ)
if err := DBH.Select(&relatedStrainIds, q, opt.Genus); err != nil {
if err := DBH.Select(&relatedStrainIDs, q, opt.Genus); err != nil {
return nil, err
}
} else {
var vals []interface{}
var count int64 = 2
vals = append(vals, opt.Genus)
q := fmt.Sprintf("%s WHERE %s ", baseQ, helpers.ValsIn("m.characteristic_id", opt.Ids, &vals, &count))
q := fmt.Sprintf("%s WHERE %s ", baseQ, helpers.ValsIn("m.characteristic_id", opt.IDs, &vals, &count))
if err := DBH.Select(&relatedStrainIds, q, vals...); err != nil {
if err := DBH.Select(&relatedStrainIDs, q, vals...); err != nil {
return nil, err
}
}
return &helpers.ListOptions{Genus: opt.Genus, Ids: relatedStrainIds}, nil
return &helpers.ListOptions{Genus: opt.Genus, IDs: relatedStrainIDs}, nil
}
// MeasurementOptsFromCharacteristics returns the options for finding all related
// measurements for a set of characteristics.
func MeasurementOptsFromCharacteristics(opt helpers.ListOptions) (*helpers.MeasurementListOptions, error) {
relatedMeasurementIds := make([]int64, 0)
var relatedMeasurementIDs []int64
baseQ := `SELECT m.id
FROM measurements m
INNER JOIN strains st ON st.id=m.strain_id
INNER JOIN species sp ON sp.id=st.species_id
INNER JOIN genera g ON g.id=sp.genus_id AND LOWER(g.genus_name)=LOWER($1)`
if opt.Ids == nil {
if opt.IDs == nil {
q := fmt.Sprintf("%s;", baseQ)
if err := DBH.Select(&relatedMeasurementIds, q, opt.Genus); err != nil {
if err := DBH.Select(&relatedMeasurementIDs, q, opt.Genus); err != nil {
return nil, err
}
} else {
var vals []interface{}
var count int64 = 2
vals = append(vals, opt.Genus)
q := fmt.Sprintf("%s WHERE %s;", baseQ, helpers.ValsIn("characteristic_id", opt.Ids, &vals, &count))
q := fmt.Sprintf("%s WHERE %s;", baseQ, helpers.ValsIn("characteristic_id", opt.IDs, &vals, &count))
if err := DBH.Select(&relatedMeasurementIds, q, vals...); err != nil {
if err := DBH.Select(&relatedMeasurementIDs, q, vals...); err != nil {
return nil, err
}
}
return &helpers.MeasurementListOptions{ListOptions: helpers.ListOptions{Genus: opt.Genus, Ids: relatedMeasurementIds}, Strains: nil, Characteristics: nil}, nil
return &helpers.MeasurementListOptions{ListOptions: helpers.ListOptions{Genus: opt.Genus, IDs: relatedMeasurementIDs}, Strains: nil, Characteristics: nil}, nil
}
func StrainsFromCharacteristicId(id int64, genus string, claims *types.Claims) (*Strains, *helpers.ListOptions, error) {
// StrainsFromCharacteristicID returns a set of strains (as well as the options for
// finding those strains) for a particular characteristic.
func StrainsFromCharacteristicID(id int64, genus string, claims *types.Claims) (*Strains, *helpers.ListOptions, error) {
opt := helpers.ListOptions{
Genus: genus,
Ids: []int64{id},
IDs: []int64{id},
}
strains_opt, err := StrainOptsFromCharacteristics(opt)
strainsOpt, err := StrainOptsFromCharacteristics(opt)
if err != nil {
return nil, nil, err
}
strains, err := ListStrains(*strains_opt, claims)
strains, err := ListStrains(*strainsOpt, claims)
if err != nil {
return nil, nil, err
}
return strains, strains_opt, nil
return strains, strainsOpt, nil
}
func MeasurementsFromCharacteristicId(id int64, genus string, claims *types.Claims) (*Measurements, *helpers.MeasurementListOptions, error) {
// MeasurementsFromCharacteristicID returns a set of measurements (as well as the
// options for finding those measurements) for a particular characteristic.
func MeasurementsFromCharacteristicID(id int64, genus string, claims *types.Claims) (*Measurements, *helpers.MeasurementListOptions, error) {
opt := helpers.ListOptions{
Genus: genus,
Ids: []int64{id},
IDs: []int64{id},
}
measurement_opt, err := MeasurementOptsFromCharacteristics(opt)
measurementOpt, err := MeasurementOptsFromCharacteristics(opt)
if err != nil {
return nil, nil, err
}
measurements, err := ListMeasurements(*measurement_opt, claims)
measurements, err := ListMeasurements(*measurementOpt, claims)
if err != nil {
return nil, nil, err
}
return measurements, measurement_opt, nil
return measurements, measurementOpt, nil
}
// GetCharacteristic returns a particular characteristic.
func GetCharacteristic(id int64, genus string, claims *types.Claims) (*Characteristic, error) {
var characteristic Characteristic
q := `SELECT c.*, ct.characteristic_type_name,
@ -194,7 +211,7 @@ func GetCharacteristic(id int64, genus string, claims *types.Claims) (*Character
GROUP BY c.id, ct.characteristic_type_name;`
if err := DBH.SelectOne(&characteristic, q, genus, id); err != nil {
if err == sql.ErrNoRows {
return nil, errors.CharacteristicNotFound
return nil, errors.ErrCharacteristicNotFound
}
return nil, err
}
@ -204,6 +221,8 @@ func GetCharacteristic(id int64, genus string, claims *types.Claims) (*Character
return &characteristic, nil
}
// InsertOrGetCharacteristicType performs an UPSERT operation on the database
// for a characteristic type.
func InsertOrGetCharacteristicType(val string, claims *types.Claims) (int64, error) {
var id int64
q := `SELECT id FROM characteristic_types WHERE characteristic_type_name=$1;`

View file

@ -3,6 +3,8 @@ package models
import "github.com/thermokarst/bactdb/Godeps/_workspace/src/github.com/jmoiron/modl"
var (
DB = &modl.DbMap{Dialect: modl.PostgresDialect{}}
// DB is a sqlx/modl database map.
DB = &modl.DbMap{Dialect: modl.PostgresDialect{}}
// DBH is a global database handler.
DBH modl.SqlExecutor = DB
)

View file

@ -12,9 +12,10 @@ import (
)
func init() {
DB.AddTableWithName(MeasurementBase{}, "measurements").SetKeys(true, "Id")
DB.AddTableWithName(MeasurementBase{}, "measurements").SetKeys(true, "ID")
}
// PreInsert is a modl hook.
func (m *MeasurementBase) PreInsert(e modl.SqlExecutor) error {
ct := helpers.CurrentTime()
m.CreatedAt = ct
@ -22,32 +23,35 @@ func (m *MeasurementBase) PreInsert(e modl.SqlExecutor) error {
return nil
}
// PreUpdate is a modl hook.
func (m *MeasurementBase) PreUpdate(e modl.SqlExecutor) error {
m.UpdatedAt = helpers.CurrentTime()
return nil
}
// MeasurementBase is what the DB expects for write operations
// There are three types of supported measurements: fixed-text, free-text,
// & numerical. The table has a constraint that will allow at most one
// for a particular combination of strain & characteristic.
// MeasurementBase is what the DB expects to see for inserts/updates
type MeasurementBase struct {
Id int64 `json:"id,omitempty"`
StrainId int64 `db:"strain_id" json:"strain"`
CharacteristicId int64 `db:"characteristic_id" json:"characteristic"`
TextMeasurementTypeId types.NullInt64 `db:"text_measurement_type_id" json:"-"`
ID int64 `json:"id,omitempty"`
StrainID int64 `db:"strain_id" json:"strain"`
CharacteristicID int64 `db:"characteristic_id" json:"characteristic"`
TextMeasurementTypeID types.NullInt64 `db:"text_measurement_type_id" json:"-"`
TxtValue types.NullString `db:"txt_value" json:"-"`
NumValue types.NullFloat64 `db:"num_value" json:"-"`
ConfidenceInterval types.NullFloat64 `db:"confidence_interval" json:"confidenceInterval"`
UnitTypeId types.NullInt64 `db:"unit_type_id" json:"-"`
UnitTypeID types.NullInt64 `db:"unit_type_id" json:"-"`
Notes types.NullString `db:"notes" json:"notes"`
TestMethodId types.NullInt64 `db:"test_method_id" json:"-"`
TestMethodID types.NullInt64 `db:"test_method_id" json:"-"`
CreatedAt types.NullTime `db:"created_at" json:"createdAt"`
UpdatedAt types.NullTime `db:"updated_at" json:"updatedAt"`
CreatedBy int64 `db:"created_by" json:"createdBy"`
UpdatedBy int64 `db:"updated_by" json:"updatedBy"`
}
// Measurement is what the DB expects for read operations, and is what the API
// expects to return to the requester.
type Measurement struct {
*MeasurementBase
TextMeasurementType types.NullString `db:"text_measurement_type_name" json:"-"`
@ -56,8 +60,10 @@ type Measurement struct {
CanEdit bool `db:"-" json:"canEdit"`
}
// FakeMeasurement is a dummy struct to prevent infinite-loop/stack overflow on serialization.
type FakeMeasurement Measurement
// MarshalJSON is custom JSON serialization to handle multi-type "Value".
func (m *Measurement) MarshalJSON() ([]byte, error) {
fm := FakeMeasurement(*m)
return json.Marshal(struct {
@ -69,6 +75,7 @@ func (m *Measurement) MarshalJSON() ([]byte, error) {
})
}
// UnmarshalJSON is custom JSON deserialization to handle multi-type "Value"
func (m *Measurement) UnmarshalJSON(b []byte) error {
var measurement struct {
FakeMeasurement
@ -81,7 +88,7 @@ func (m *Measurement) UnmarshalJSON(b []byte) error {
switch v := measurement.Value.(type) {
case string:
// Test if actually a lookup
id, err := GetTextMeasurementTypeId(v)
id, err := GetTextMeasurementTypeID(v)
if err != nil {
if err == sql.ErrNoRows {
measurement.TxtValue = types.NullString{sql.NullString{String: v, Valid: true}}
@ -89,7 +96,7 @@ func (m *Measurement) UnmarshalJSON(b []byte) error {
return err
}
} else {
measurement.TextMeasurementTypeId = types.NullInt64{sql.NullInt64{Int64: id, Valid: true}}
measurement.TextMeasurementTypeID = types.NullInt64{sql.NullInt64{Int64: id, Valid: true}}
}
case int64:
measurement.NumValue = types.NullFloat64{sql.NullFloat64{Float64: float64(v), Valid: true}}
@ -102,6 +109,7 @@ func (m *Measurement) UnmarshalJSON(b []byte) error {
return nil
}
// Value returns the value of the measurement
func (m *Measurement) Value() string {
if m.TextMeasurementType.Valid {
return m.TextMeasurementType.String
@ -115,12 +123,15 @@ func (m *Measurement) Value() string {
return ""
}
// Measurements are multiple measurement entities
type Measurements []*Measurement
// MeasurementMeta stashes some metadata related to the entity
type MeasurementMeta struct {
CanAdd bool `json:"canAdd"`
}
// ListMeasurements returns all measurements
func ListMeasurements(opt helpers.MeasurementListOptions, claims *types.Claims) (*Measurements, error) {
var vals []interface{}
@ -136,35 +147,35 @@ func ListMeasurements(opt helpers.MeasurementListOptions, claims *types.Claims)
LEFT OUTER JOIN test_methods te ON te.id=m.test_method_id`
vals = append(vals, opt.Genus)
strainIds := len(opt.Strains) != 0
charIds := len(opt.Characteristics) != 0
ids := len(opt.Ids) != 0
strainIDs := len(opt.Strains) != 0
charIDs := len(opt.Characteristics) != 0
ids := len(opt.IDs) != 0
if strainIds || charIds || ids {
if strainIDs || charIDs || ids {
var paramsCounter int64 = 2
q += "\nWHERE ("
// Filter by strains
if strainIds {
if strainIDs {
q += helpers.ValsIn("st.id", opt.Strains, &vals, &paramsCounter)
}
if strainIds && (charIds || ids) {
if strainIDs && (charIDs || ids) {
q += " AND "
}
// Filter by characteristics
if charIds {
if charIDs {
q += helpers.ValsIn("c.id", opt.Characteristics, &vals, &paramsCounter)
}
if charIds && ids {
if charIDs && ids {
q += " AND "
}
// Get specific records
if ids {
q += helpers.ValsIn("m.id", opt.Ids, &vals, &paramsCounter)
q += helpers.ValsIn("m.id", opt.IDs, &vals, &paramsCounter)
}
q += ")"
}
@ -183,6 +194,7 @@ func ListMeasurements(opt helpers.MeasurementListOptions, claims *types.Claims)
return &measurements, nil
}
// GetMeasurement returns a particular measurement.
func GetMeasurement(id int64, genus string, claims *types.Claims) (*Measurement, error) {
var measurement Measurement
@ -199,7 +211,7 @@ func GetMeasurement(id int64, genus string, claims *types.Claims) (*Measurement,
WHERE m.id=$2;`
if err := DBH.SelectOne(&measurement, q, genus, id); err != nil {
if err == sql.ErrNoRows {
return nil, errors.MeasurementNotFound
return nil, errors.ErrMeasurementNotFound
}
return nil, err
}
@ -209,15 +221,20 @@ func GetMeasurement(id int64, genus string, claims *types.Claims) (*Measurement,
return &measurement, nil
}
// CharacteristicOptsFromMeasurements returns the options for finding all related
// characteristics for a set of measurements.
func CharacteristicOptsFromMeasurements(opt helpers.MeasurementListOptions) (*helpers.ListOptions, error) {
return &helpers.ListOptions{Genus: opt.Genus, Ids: opt.Characteristics}, nil
return &helpers.ListOptions{Genus: opt.Genus, IDs: opt.Characteristics}, nil
}
// StrainOptsFromMeasurements returns the options for finding all related
// strains from a set of measurements.
func StrainOptsFromMeasurements(opt helpers.MeasurementListOptions) (*helpers.ListOptions, error) {
return &helpers.ListOptions{Genus: opt.Genus, Ids: opt.Strains}, nil
return &helpers.ListOptions{Genus: opt.Genus, IDs: opt.Strains}, nil
}
func GetTextMeasurementTypeId(val string) (int64, error) {
// GetTextMeasurementTypeID returns the ID for a particular text measurement type
func GetTextMeasurementTypeID(val string) (int64, error) {
var id int64
q := `SELECT id FROM text_measurement_types WHERE text_measurement_name=$1;`

View file

@ -12,9 +12,10 @@ import (
)
func init() {
DB.AddTableWithName(SpeciesBase{}, "species").SetKeys(true, "Id")
DB.AddTableWithName(SpeciesBase{}, "species").SetKeys(true, "ID")
}
// PreInsert is a modl hook.
func (s *SpeciesBase) PreInsert(e modl.SqlExecutor) error {
ct := helpers.CurrentTime()
s.CreatedAt = ct
@ -22,13 +23,15 @@ func (s *SpeciesBase) PreInsert(e modl.SqlExecutor) error {
return nil
}
// PreUpdate is a modl hook.
func (s *SpeciesBase) PreUpdate(e modl.SqlExecutor) error {
s.UpdatedAt = helpers.CurrentTime()
return nil
}
// SpeciesBase is what the DB expects for write operations.
type SpeciesBase struct {
Id int64 `db:"id" json:"id"`
ID int64 `db:"id" json:"id"`
GenusID int64 `db:"genus_id" json:"-"`
SubspeciesSpeciesID types.NullInt64 `db:"subspecies_species_id" json:"-"`
SpeciesName string `db:"species_name" json:"speciesName"`
@ -42,6 +45,8 @@ type SpeciesBase struct {
DeletedBy types.NullInt64 `db:"deleted_by" json:"deletedBy"`
}
// Species is what the DB expects for read operations, and is what the API expects
// to return to the requester.
type Species struct {
*SpeciesBase
GenusName string `db:"genus_name" json:"genusName"`
@ -51,57 +56,64 @@ type Species struct {
CanEdit bool `db:"-" json:"canEdit"`
}
// ManySpecies is multiple species entities.
type ManySpecies []*Species
// SpeciesMeta stashes some metadata related to the entity.
type SpeciesMeta struct {
CanAdd bool `json:"canAdd"`
}
func GenusIdFromName(genus_name string) (int64, error) {
var genus_id struct{ Id int64 }
// GenusIDFromName looks up the genus' ID.
func GenusIDFromName(genusName string) (int64, error) {
var genusID struct{ ID int64 }
q := `SELECT id FROM genera WHERE LOWER(genus_name) = LOWER($1);`
if err := DBH.SelectOne(&genus_id, q, genus_name); err != nil {
if err := DBH.SelectOne(&genusID, q, genusName); err != nil {
return 0, err
}
return genus_id.Id, nil
return genusID.ID, nil
}
// StrainOptsFromSpecies returns the options for finding all related strains for
// a set of species.
func StrainOptsFromSpecies(opt helpers.ListOptions) (*helpers.ListOptions, error) {
relatedStrainIds := make([]int64, 0)
var relatedStrainIDs []int64
if opt.Ids == nil {
if opt.IDs == nil {
q := `SELECT DISTINCT st.id
FROM strains st
INNER JOIN species sp ON sp.id=st.species_id
INNER JOIN genera g ON g.id=sp.genus_id AND LOWER(g.genus_name)=LOWER($1);`
if err := DBH.Select(&relatedStrainIds, q, opt.Genus); err != nil {
if err := DBH.Select(&relatedStrainIDs, q, opt.Genus); err != nil {
return nil, err
}
} else {
var vals []interface{}
var count int64 = 1
q := fmt.Sprintf("SELECT DISTINCT id FROM strains WHERE %s;", helpers.ValsIn("species_id", opt.Ids, &vals, &count))
q := fmt.Sprintf("SELECT DISTINCT id FROM strains WHERE %s;", helpers.ValsIn("species_id", opt.IDs, &vals, &count))
if err := DBH.Select(&relatedStrainIds, q, vals...); err != nil {
if err := DBH.Select(&relatedStrainIDs, q, vals...); err != nil {
return nil, err
}
}
return &helpers.ListOptions{Genus: opt.Genus, Ids: relatedStrainIds}, nil
return &helpers.ListOptions{Genus: opt.Genus, IDs: relatedStrainIDs}, nil
}
func StrainsFromSpeciesId(id int64, genus string, claims *types.Claims) (*Strains, error) {
// StrainsFromSpeciesID returns the options for finding all related strains for a
// particular species.
func StrainsFromSpeciesID(id int64, genus string, claims *types.Claims) (*Strains, error) {
opt := helpers.ListOptions{
Genus: genus,
Ids: []int64{id},
IDs: []int64{id},
}
strains_opt, err := StrainOptsFromSpecies(opt)
strainsOpt, err := StrainOptsFromSpecies(opt)
if err != nil {
return nil, err
}
strains, err := ListStrains(*strains_opt, claims)
strains, err := ListStrains(*strainsOpt, claims)
if err != nil {
return nil, err
}
@ -109,6 +121,7 @@ func StrainsFromSpeciesId(id int64, genus string, claims *types.Claims) (*Strain
return strains, nil
}
// ListSpecies returns all species
func ListSpecies(opt helpers.ListOptions, claims *types.Claims) (*ManySpecies, error) {
var vals []interface{}
@ -120,10 +133,10 @@ func ListSpecies(opt helpers.ListOptions, claims *types.Claims) (*ManySpecies, e
LEFT OUTER JOIN strains st ON st.species_id=sp.id`
vals = append(vals, opt.Genus)
if len(opt.Ids) != 0 {
if len(opt.IDs) != 0 {
var conds []string
s := "sp.id IN ("
for i, id := range opt.Ids {
for i, id := range opt.IDs {
s = s + fmt.Sprintf("$%v,", i+2) // start param index at 2
vals = append(vals, id)
}
@ -147,6 +160,7 @@ func ListSpecies(opt helpers.ListOptions, claims *types.Claims) (*ManySpecies, e
return &species, nil
}
// GetSpecies returns a particular species.
func GetSpecies(id int64, genus string, claims *types.Claims) (*Species, error) {
var species Species
q := `SELECT sp.*, g.genus_name, array_agg(st.id) AS strains,
@ -158,7 +172,7 @@ func GetSpecies(id int64, genus string, claims *types.Claims) (*Species, error)
GROUP BY sp.id, g.genus_name;`
if err := DBH.SelectOne(&species, q, genus, id); err != nil {
if err == sql.ErrNoRows {
return nil, errors.SpeciesNotFound
return nil, errors.ErrSpeciesNotFound
}
return nil, err
}

View file

@ -12,9 +12,10 @@ import (
)
func init() {
DB.AddTableWithName(StrainBase{}, "strains").SetKeys(true, "Id")
DB.AddTableWithName(StrainBase{}, "strains").SetKeys(true, "ID")
}
// PreInsert is a modl hook.
func (s *StrainBase) PreInsert(e modl.SqlExecutor) error {
ct := helpers.CurrentTime()
s.CreatedAt = ct
@ -22,14 +23,16 @@ func (s *StrainBase) PreInsert(e modl.SqlExecutor) error {
return nil
}
// PreUpdate is a modl hook.
func (s *StrainBase) PreUpdate(e modl.SqlExecutor) error {
s.UpdatedAt = helpers.CurrentTime()
return nil
}
// StrainBase is what the DB expects for write operations.
type StrainBase struct {
Id int64 `db:"id" json:"id"`
SpeciesId int64 `db:"species_id" json:"species"`
ID int64 `db:"id" json:"id"`
SpeciesID int64 `db:"species_id" json:"species"`
StrainName string `db:"strain_name" json:"strainName"`
TypeStrain bool `db:"type_strain" json:"typeStrain"`
AccessionNumbers types.NullString `db:"accession_numbers" json:"accessionNumbers"`
@ -45,6 +48,8 @@ type StrainBase struct {
DeletedBy types.NullInt64 `db:"deleted_by" json:"deletedBy"`
}
// Strain is what the DB expects for read operations, and is what the API expects
// to return to the requester.
type Strain struct {
*StrainBase
Measurements types.NullSliceInt64 `db:"measurements" json:"measurements"`
@ -54,20 +59,24 @@ type Strain struct {
CanEdit bool `db:"-" json:"canEdit"`
}
// Strains are multiple strain entities.
type Strains []*Strain
// StrainMeta stashes some metadata related to the entity.
type StrainMeta struct {
CanAdd bool `json:"canAdd"`
}
// SpeciesName returns a strain's species name.
func (s StrainBase) SpeciesName() string {
var species SpeciesBase
if err := DBH.Get(&species, s.SpeciesId); err != nil {
if err := DBH.Get(&species, s.SpeciesID); err != nil {
return ""
}
return species.SpeciesName
}
// ListStrains returns all strains.
func ListStrains(opt helpers.ListOptions, claims *types.Claims) (*Strains, error) {
var vals []interface{}
@ -81,10 +90,10 @@ func ListStrains(opt helpers.ListOptions, claims *types.Claims) (*Strains, error
LEFT OUTER JOIN measurements m ON m.strain_id=st.id`
vals = append(vals, opt.Genus)
if len(opt.Ids) != 0 {
if len(opt.IDs) != 0 {
var conds []string
s := "st.id IN ("
for i, id := range opt.Ids {
for i, id := range opt.IDs {
s = s + fmt.Sprintf("$%v,", i+2) // start param index at 2
vals = append(vals, id)
}
@ -108,6 +117,7 @@ func ListStrains(opt helpers.ListOptions, claims *types.Claims) (*Strains, error
return &strains, nil
}
// GetStrain returns a particular strain.
func GetStrain(id int64, genus string, claims *types.Claims) (*Strain, error) {
var strain Strain
q := `SELECT st.*, array_agg(DISTINCT m.id) AS measurements,
@ -121,7 +131,7 @@ func GetStrain(id int64, genus string, claims *types.Claims) (*Strain, error) {
GROUP BY st.id;`
if err := DBH.SelectOne(&strain, q, genus, id); err != nil {
if err == sql.ErrNoRows {
return nil, errors.StrainNotFound
return nil, errors.ErrStrainNotFound
}
return nil, err
}
@ -131,49 +141,53 @@ func GetStrain(id int64, genus string, claims *types.Claims) (*Strain, error) {
return &strain, nil
}
// SpeciesOptsFromStrains returns the options for finding all related species for a
// set of strains.
func SpeciesOptsFromStrains(opt helpers.ListOptions) (*helpers.ListOptions, error) {
relatedSpeciesIds := make([]int64, 0)
var relatedSpeciesIDs []int64
if opt.Ids == nil || len(opt.Ids) == 0 {
if opt.IDs == nil || len(opt.IDs) == 0 {
q := `SELECT DISTINCT st.species_id
FROM strains st
INNER JOIN species sp ON sp.id=st.species_id
INNER JOIN genera g ON g.id=sp.genus_id AND LOWER(g.genus_name)=LOWER($1);`
if err := DBH.Select(&relatedSpeciesIds, q, opt.Genus); err != nil {
if err := DBH.Select(&relatedSpeciesIDs, q, opt.Genus); err != nil {
return nil, err
}
} else {
var vals []interface{}
var count int64 = 1
q := fmt.Sprintf("SELECT DISTINCT species_id FROM strains WHERE %s;", helpers.ValsIn("id", opt.Ids, &vals, &count))
if err := DBH.Select(&relatedSpeciesIds, q, vals...); err != nil {
q := fmt.Sprintf("SELECT DISTINCT species_id FROM strains WHERE %s;", helpers.ValsIn("id", opt.IDs, &vals, &count))
if err := DBH.Select(&relatedSpeciesIDs, q, vals...); err != nil {
return nil, err
}
}
return &helpers.ListOptions{Genus: opt.Genus, Ids: relatedSpeciesIds}, nil
return &helpers.ListOptions{Genus: opt.Genus, IDs: relatedSpeciesIDs}, nil
}
// CharacteristicsOptsFromStrains returns the options for finding all related
// characteristics for a set of strains.
func CharacteristicsOptsFromStrains(opt helpers.ListOptions) (*helpers.ListOptions, error) {
relatedCharacteristicsIds := make([]int64, 0)
var relatedCharacteristicsIDs []int64
if opt.Ids == nil || len(opt.Ids) == 0 {
if opt.IDs == nil || len(opt.IDs) == 0 {
q := `SELECT DISTINCT m.characteristic_id
FROM measurements m
INNER JOIN strains st ON st.id=m.strain_id
INNER JOIN species sp ON sp.id=st.species_id
INNER JOIN genera g ON g.id=sp.genus_id AND LOWER(g.genus_name)=LOWER($1);`
if err := DBH.Select(&relatedCharacteristicsIds, q, opt.Genus); err != nil {
if err := DBH.Select(&relatedCharacteristicsIDs, q, opt.Genus); err != nil {
return nil, err
}
} else {
var vals []interface{}
var count int64 = 1
q := fmt.Sprintf("SELECT DISTINCT characteristic_id FROM measurements WHERE %s;", helpers.ValsIn("strain_id", opt.Ids, &vals, &count))
if err := DBH.Select(&relatedCharacteristicsIds, q, vals...); err != nil {
q := fmt.Sprintf("SELECT DISTINCT characteristic_id FROM measurements WHERE %s;", helpers.ValsIn("strain_id", opt.IDs, &vals, &count))
if err := DBH.Select(&relatedCharacteristicsIDs, q, vals...); err != nil {
return nil, err
}
}
return &helpers.ListOptions{Genus: opt.Genus, Ids: relatedCharacteristicsIds}, nil
return &helpers.ListOptions{Genus: opt.Genus, IDs: relatedCharacteristicsIDs}, nil
}

View file

@ -12,11 +12,12 @@ import (
)
func init() {
DB.AddTableWithName(UserBase{}, "users").SetKeys(true, "Id")
DB.AddTableWithName(UserBase{}, "users").SetKeys(true, "ID")
}
// UserBase is what the DB expects to see for write operations.
type UserBase struct {
Id int64 `json:"id,omitempty"`
ID int64 `json:"id,omitempty"`
Email string `db:"email" json:"email"`
Password string `db:"password" json:"password,omitempty"`
Name string `db:"name" json:"name"`
@ -27,11 +28,14 @@ type UserBase struct {
DeletedAt types.NullTime `db:"deleted_at" json:"deletedAt"`
}
// User is what the DB expects to see for read operations, and is what the API
// expects to return to the requester.
type User struct {
*UserBase
CanEdit bool `db:"-" json:"canEdit"`
}
// UserValidation handles validation of a user record.
type UserValidation struct {
Email []string `json:"email,omitempty"`
Password []string `json:"password,omitempty"`
@ -39,6 +43,7 @@ type UserValidation struct {
Role []string `json:"role,omitempty"`
}
// Error returns the JSON-encoded error response for any validation errors.
func (uv UserValidation) Error() string {
errs, err := json.Marshal(struct {
UserValidation `json:"errors"`
@ -49,24 +54,15 @@ func (uv UserValidation) Error() string {
return string(errs)
}
// Users are multiple user entities.
type Users []*User
type UserJSON struct {
User *User `json:"user"`
}
type UsersJSON struct {
Users *Users `json:"users"`
}
// UserMeta stashes some metadata related to the entity.
type UserMeta struct {
CanAdd bool `json:"canAdd"`
}
func (u *Users) Marshal() ([]byte, error) {
return json.Marshal(&UsersJSON{Users: u})
}
// Validate validates a user record.
func (u *User) Validate() error {
var uv UserValidation
validationError := false
@ -98,7 +94,8 @@ func (u *User) Validate() error {
return nil
}
// for thermokarst/jwt: authentication callback
// DbAuthenticate authenticates a user.
// For thermokarst/jwt: authentication callback
func DbAuthenticate(email string, password string) error {
var user User
q := `SELECT *
@ -107,15 +104,16 @@ func DbAuthenticate(email string, password string) error {
AND verified IS TRUE
AND deleted_at IS NULL;`
if err := DBH.SelectOne(&user, q, email); err != nil {
return errors.InvalidEmailOrPassword
return errors.ErrInvalidEmailOrPassword
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
return errors.InvalidEmailOrPassword
return errors.ErrInvalidEmailOrPassword
}
return nil
}
func DbGetUserById(id int64) (*User, error) {
// DbGetUserByID returns a specific user record by ID.
func DbGetUserByID(id int64) (*User, error) {
var user User
q := `SELECT *
FROM users
@ -124,14 +122,15 @@ func DbGetUserById(id int64) (*User, error) {
AND deleted_at IS NULL;`
if err := DBH.SelectOne(&user, q, id); err != nil {
if err == sql.ErrNoRows {
return nil, errors.UserNotFound
return nil, errors.ErrUserNotFound
}
return nil, err
}
return &user, nil
}
// for thermokarst/jwt: setting user in claims bundle
// DbGetUserByEmail returns a specific user record by email.
// For thermokarst/jwt: setting user in claims bundle
func DbGetUserByEmail(email string) (*User, error) {
var user User
q := `SELECT *
@ -141,7 +140,7 @@ func DbGetUserByEmail(email string) (*User, error) {
AND deleted_at IS NULL;`
if err := DBH.SelectOne(&user, q, email); err != nil {
if err == sql.ErrNoRows {
return nil, errors.UserNotFound
return nil, errors.ErrUserNotFound
}
return nil, err
}