changes to model
This commit is contained in:
@@ -11,9 +11,9 @@ import (
|
||||
func GetCompanyByID(db *sql.DB, id int) (*model.Company, error) {
|
||||
var c model.Company
|
||||
err := db.QueryRow(
|
||||
`SELECT id, name, shares_outstanding, price, currency_id FROM companies WHERE id = ?`,
|
||||
`SELECT id, symbol, shares_outstanding, price, currency_id FROM companies WHERE id = ?`,
|
||||
id,
|
||||
).Scan(&c.ID, &c.Name, &c.SharesOutstanding, &c.Price, &c.CurrencyID)
|
||||
).Scan(&c.ID, &c.Symbol, &c.SharesOutstanding, &c.Price, &c.CurrencyID)
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
@@ -23,3 +23,49 @@ func GetCompanyByID(db *sql.DB, id int) (*model.Company, error) {
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func AddCompany(db *sql.DB, input model.CompanyInput) (int, error) {
|
||||
if input.CurrencyID == 0 {
|
||||
if input.CurrencyCode != "" {
|
||||
currency, err := GetCurrencyByCode(db, input.CurrencyCode)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("could not get currency: %s", err)
|
||||
}
|
||||
input.CurrencyID = currency.ID
|
||||
} else {
|
||||
return 0, fmt.Errorf("no currency reference")
|
||||
}
|
||||
}
|
||||
|
||||
res, err := db.Exec(
|
||||
`INSERT INTO companies (symbol, shares_outstanding, price, currency_id) VALUES (?, ?, ?, ?)`,
|
||||
input.Symbol, input.SharesOutstanding, input.Price, input.CurrencyID,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to insert: %s", err)
|
||||
}
|
||||
id, err := res.LastInsertId()
|
||||
return int(id), err
|
||||
}
|
||||
|
||||
func GetAllCompanies(db *sql.DB) ([]model.Company, error) {
|
||||
rows, err := db.Query(`
|
||||
SELECT id, symbol, shares_outstanding, price, currency_id FROM companies
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var companies []model.Company
|
||||
for rows.Next() {
|
||||
var c model.Company
|
||||
if err := rows.Scan(
|
||||
&c.ID, &c.Symbol, &c.SharesOutstanding, &c.Price, &c.CurrencyID,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
companies = append(companies, c)
|
||||
}
|
||||
return companies, rows.Err()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user