basic internal structure

This commit is contained in:
samantha42
2026-03-24 11:17:08 +01:00
parent 29b3c2dd6c
commit a9d4f09b62
14 changed files with 407 additions and 3 deletions

View File

@@ -0,0 +1,48 @@
package service
import (
"Portifolio/internal/model"
"database/sql"
)
func InsertCompany(db *sql.DB, input model.CompanyInput) (int, error) {
res, err := db.Exec(
`INSERT INTO companies (name, shares_outstanding, price, currency_id) VALUES (?, ?, ?, ?)`,
input.Name, input.SharesOutstanding, input.Price, input.CurrencyID,
)
if err != nil {
return 0, err
}
id, err := res.LastInsertId()
return int(id), err
}
func GetAllCompanies(db *sql.DB) ([]model.Company, error) {
rows, err := db.Query(`
SELECT c.id, c.name, c.shares_outstanding, c.price,
cu.id, cu.code, cu.name
FROM companies c
JOIN currencies cu ON c.currency_id = cu.id
ORDER BY c.name
`)
if err != nil {
return nil, err
}
defer rows.Close()
var companies []model.Company
for rows.Next() {
var c model.Company
var cu model.Currency
if err := rows.Scan(
&c.ID, &c.Name, &c.SharesOutstanding, &c.Price,
&cu.ID, &cu.Code, &cu.Name,
); err != nil {
return nil, err
}
c.CurrencyID = cu.ID
c.Currency = &cu
companies = append(companies, c)
}
return companies, rows.Err()
}

View File

@@ -0,0 +1,47 @@
package service
import (
"Portifolio/internal/model"
"database/sql"
)
func InsertCurrency(db *sql.DB, input model.CurrencyInput) (int, error) {
res, err := db.Exec(
`INSERT INTO currencies (code, name) VALUES (?, ?)`,
input.Code, input.Name,
)
if err != nil {
return 0, err
}
id, err := res.LastInsertId()
return int(id), err
}
func GetCurrencyByCode(db *sql.DB, code string) (*model.Currency, error) {
c := &model.Currency{}
err := db.QueryRow(
`SELECT id, code, name FROM currencies WHERE code = ?`, code,
).Scan(&c.ID, &c.Code, &c.Name)
if err == sql.ErrNoRows {
return nil, nil
}
return c, err
}
func GetAllCurrencies(db *sql.DB) ([]model.Currency, error) {
rows, err := db.Query(`SELECT id, code, name FROM currencies ORDER BY code`)
if err != nil {
return nil, err
}
defer rows.Close()
var currencies []model.Currency
for rows.Next() {
var c model.Currency
if err := rows.Scan(&c.ID, &c.Code, &c.Name); err != nil {
return nil, err
}
currencies = append(currencies, c)
}
return currencies, rows.Err()
}

16
internal/service/main.go Normal file
View File

@@ -0,0 +1,16 @@
package service
import (
"Portifolio/internal/model"
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
func AddCompany(input model.CompanyInput, db *sql.DB) error {
_, err := db.Exec(
`INSERT INTO companies (name, shares_outstanding, price, currency_id) VALUES (?, ?, ?, ?)`,
input.Name, input.SharesOutstanding, input.Price, input.CurrencyID,
)
return err
}