tiny-url-ex/service/shortener/model.go

65 lines
1.3 KiB
Go

package shortener
import (
"database/sql"
)
// tinyModel represents an actual tiny url entry in the database.
type tinyModel struct {
db *sql.DB
tiny string
long string
}
type repository struct {
db *sql.DB
}
// newRepo returns an initialized repository.
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)
receiver := &tinyModel{}
err := row.Scan(&receiver.tiny, &receiver.long)
if err != nil {
return err
}
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
}