articles-api/service/shortener/model.go

65 lines
1.3 KiB
Go
Raw Normal View History

package shortener
import (
"database/sql"
)
// tinyModel represents an actual tiny url entry in the database.
2019-05-02 18:50:58 +00:00
type tinyModel struct {
db *sql.DB
tiny string
long string
}
type repository struct {
db *sql.DB
}
// newRepo returns an initialized repository.
2019-05-02 18:50:58 +00:00
func newRepo(db *sql.DB) (*repository, error) {
_, err := db.Exec(`CREATE TABLE if not exists tiny(
tiny varchar(30) PRIMARY KEY,
long varchar(300) NOT NULL
);`)
return &repository{db}, err
}
func (repo *repository) NewModel(tiny string, long string) *tinyModel {
return &tinyModel{
db: repo.db,
tiny: tiny,
long: long,
}
}
func (mod *tinyModel) Search() error {
row := mod.db.QueryRow(`SELECT tiny,long FROM tiny WHERE tiny = $1 LIMIT 1;`, mod.tiny)
2019-05-02 18:50:58 +00:00
receiver := &tinyModel{}
err := row.Scan(&receiver.tiny, &receiver.long)
if err != nil {
2019-05-02 18:50:58 +00:00
return err
}
2019-05-02 18:50:58 +00:00
mod.tiny = receiver.tiny
mod.long = receiver.long
return nil
}
func (mod *tinyModel) Create() error {
_, err := mod.db.Exec(`INSERT INTO tiny(tiny,long) VALUES($1,$2);`, mod.tiny, mod.long)
return err
}
func (mod *tinyModel) Update() error {
_, err := mod.db.Exec(`UPDATE tiny SET long = $1 WHERE tiny = $2;`, mod.long, mod.tiny)
return err
}
func (mod *tinyModel) Delete() error {
_, err := mod.db.Exec(`DELETE FROM tiny WHERE tiny = $1;`, mod.tiny)
return err
}