forked from short-d/short
-
Notifications
You must be signed in to change notification settings - Fork 0
/
url.go
119 lines (103 loc) · 2.34 KB
/
url.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
116
117
118
119
package db
import (
"database/sql"
"fmt"
"github.com/short-d/short/app/adapter/db/table"
"github.com/short-d/short/app/entity"
"github.com/short-d/short/app/usecase/repository"
)
var _ repository.URL = (*URLSql)(nil)
// URLSql accesses URL information in url table through SQL.
type URLSql struct {
db *sql.DB
}
// IsAliasExist checks whether a given alias exist in url table.
func (u URLSql) IsAliasExist(alias string) (bool, error) {
query := fmt.Sprintf(`
SELECT "%s"
FROM "%s"
WHERE "%s"=$1;`,
table.URL.ColumnAlias,
table.URL.TableName,
table.URL.ColumnAlias,
)
err := u.db.QueryRow(query, alias).Scan(&alias)
if err == sql.ErrNoRows {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
// Create inserts a new URL into url table.
func (u *URLSql) Create(url entity.URL) error {
statement := fmt.Sprintf(`
INSERT INTO "%s" ("%s","%s","%s","%s","%s")
VALUES ($1, $2, $3, $4, $5);`,
table.URL.TableName,
table.URL.ColumnAlias,
table.URL.ColumnOriginalURL,
table.URL.ColumnExpireAt,
table.URL.ColumnCreatedAt,
table.URL.ColumnUpdatedAt,
)
_, err := u.db.Exec(
statement,
url.Alias,
url.OriginalURL,
url.ExpireAt,
url.CreatedAt,
url.UpdatedAt,
)
return err
}
// GetByAlias finds an URL in url table given alias.
func (u URLSql) GetByAlias(alias string) (entity.URL, error) {
statement := fmt.Sprintf(`
SELECT "%s","%s","%s","%s","%s"
FROM "%s"
WHERE "%s"=$1;`,
table.URL.ColumnAlias,
table.URL.ColumnOriginalURL,
table.URL.ColumnExpireAt,
table.URL.ColumnCreatedAt,
table.URL.ColumnUpdatedAt,
table.URL.TableName,
table.URL.ColumnAlias,
)
row := u.db.QueryRow(statement, alias)
url := entity.URL{}
err := row.Scan(
&url.Alias,
&url.OriginalURL,
&url.ExpireAt,
&url.CreatedAt,
&url.UpdatedAt,
)
if err != nil {
return entity.URL{}, err
}
url.CreatedAt = utc(url.CreatedAt)
url.UpdatedAt = utc(url.UpdatedAt)
url.ExpireAt = utc(url.ExpireAt)
return url, nil
}
// GetByAliases finds URLs for a list of aliases
func (u URLSql) GetByAliases(aliases []string) ([]entity.URL, error) {
urls := make([]entity.URL, 0)
for _, alias := range aliases {
url, err := u.GetByAlias(alias)
if err != nil {
return urls, err
}
urls = append(urls, url)
}
return urls, nil
}
// NewURLSql creates URLSql
func NewURLSql(db *sql.DB) *URLSql {
return &URLSql{
db: db,
}
}