From 623a3d0f3a1cdfdf8a2d85a98671f6b3212dd3b1 Mon Sep 17 00:00:00 2001 From: Mikhail Klementyev Date: Sun, 24 Jul 2016 10:29:11 +0300 Subject: [PATCH] Use existing links --- main.go | 11 +++++++---- storage/storage.go | 14 +++++++++++++- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 7edcba8..7bb048f 100644 --- a/main.go +++ b/main.go @@ -28,7 +28,7 @@ import ( var ( arg_url = kingpin.Flag("url", "Url").String() - arg_link = kingpin.Flag("link", "Link").Int() + arg_link = kingpin.Flag("link", "Link").Int64() ) func cmd_url(db *sql.DB, url string) { @@ -81,9 +81,12 @@ func cmd_url(db *sql.DB, url string) { panic(err) } - linkNo, err := storage.AddLink(db, url.String()) + linkNo, err := storage.GetLinkID(db, url.String()) if err != nil { - panic(err) + linkNo, err = storage.AddLink(db, url.String()) + if err != nil { + panic(err) + } } for _, s := range []string{string(value), html.EscapeString(string(value))} { @@ -107,7 +110,7 @@ func cmd_url(db *sql.DB, url string) { fmt.Println(text) } -func cmd_link(db *sql.DB, linkID int) { +func cmd_link(db *sql.DB, linkID int64) { url, err := storage.GetLink(db, linkID) if err != nil { panic(err) diff --git a/storage/storage.go b/storage/storage.go index b8819df..a3b03ea 100644 --- a/storage/storage.go +++ b/storage/storage.go @@ -42,7 +42,7 @@ func AddLink(db *sql.DB, url string) (linkNo int64, err error) { return } -func GetLink(db *sql.DB, linkID int) (url string, err error) { +func GetLink(db *sql.DB, linkID int64) (url string, err error) { stmt, err := db.Prepare("SELECT `url` FROM `links` WHERE id=$1;") if err != nil { return @@ -53,3 +53,15 @@ func GetLink(db *sql.DB, linkID int) (url string, err error) { return } + +func GetLinkID(db *sql.DB, url string) (linkID int64, err error) { + stmt, err := db.Prepare("SELECT `id` FROM `links` WHERE url=$1;") + if err != nil { + return + } + defer stmt.Close() + + err = stmt.QueryRow(url).Scan(&linkID) + + return +}