-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvivom.go
115 lines (92 loc) · 2.13 KB
/
vivom.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Package vivom is a dead simple, tiny, but powerful ORM library.
package vivom
import (
"database/sql"
"errors"
)
func csv(values []string) string {
list := ""
for i, value := range values {
if i != (len(values) - 1) {
list += value + ", "
} else {
list += value
}
}
return list
}
func csQ(n int) string {
questions := make([]string, n)
for i := 0; i < n; i++ {
questions[i] = "?"
}
return csv(questions)
}
type Vivom struct {
db *sql.DB
}
func New(db *sql.DB) *Vivom {
return &Vivom{db}
}
func (v *Vivom) Insert(r InsertableRow) error {
if r.GetID() != 0 {
return errors.New("can't insert tag with id")
}
err := r.Validate()
if err != nil {
return err
}
query := "INSERT INTO " + r.Table() + " (" + csv(r.Columns()[1:]) + ") values (" + csQ(len(r.Columns())-1) + ")"
res, err := v.db.Exec(query, r.Values()...)
if err != nil {
return err
}
id, err := res.LastInsertId()
if err != nil {
return err
}
r.SetID(int(id))
return nil
}
func (v *Vivom) Update(r InsertableRow) error {
if r.GetID() == 0 {
return errors.New("doesn't have an ID")
}
err := r.Validate()
if err != nil {
return err
}
columns := r.Columns()[1:]
for i, column := range columns {
columns[i] = column + "=?"
}
query := "UPDATE " + r.Table() + " SET " + csv(columns) + " WHERE " + r.Columns()[0] + "=?"
_, err = v.db.Exec(query, append(r.Values(), r.GetID())...)
return err
}
func (v *Vivom) Select(r SelectableRow, id string) error {
row := v.db.QueryRow("SELECT "+csv(r.Columns())+" FROM "+r.Table()+" WHERE "+r.Columns()[0]+"=?", id)
return row.Scan(r.ScanValues()...)
}
func (v *Vivom) SelectAll(rs SelectableRows) error {
return v.SelectAllBy(rs, "", "")
}
func (v *Vivom) SelectAllBy(rs SelectableRows, column string, value string) error {
query := "SELECT " + csv(rs.Columns()) + " FROM " + rs.Table()
if column != "" && value != "" {
// TODO Make sure this line is safe
query += " WHERE " + column + "=" + value
}
rows, err := v.db.Query(query)
if err != nil {
return err
}
for rows.Next() {
r := rs.Next()
err := rows.Scan(r.ScanValues()...)
if err != nil {
return err
}
}
return nil
}