changes to model

This commit is contained in:
samantha42
2026-03-26 08:39:42 +01:00
parent ff7b41e2a8
commit 3f878c1dc0
15 changed files with 119 additions and 195 deletions

View File

@@ -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()
}