Skip to content

Instantly share code, notes, and snippets.

@kemokemo
Last active November 4, 2019 02:15
Show Gist options
  • Save kemokemo/c58d06201814c30def3613447a7405ac to your computer and use it in GitHub Desktop.
Save kemokemo/c58d06201814c30def3613447a7405ac to your computer and use it in GitHub Desktop.
A sample to insert a comment into the Postgre database using gorp.
package main
import (
"database/sql"
"log"
"os"
"time"
"github.com/go-gorp/gorp"
_ "github.com/lib/pq"
)
type exitcode int
const (
exitOK exitcode = iota
exitFailOpenDB
exitFailCreateDB
exitFailPingDB
exitFailQuery
)
func main() {
os.Exit(int(run()))
}
// Comment is a comment for the db.
type Comment struct {
ID int64 `db:"id,primarykey,autoincrement"`
Name string `db:"name,notnull,default:'No Name',size:200"`
Text string `db:"text,notnull,size:400"`
Created time.Time `db:"created,notnull"`
Updated time.Time `db:"updated,notnull"`
}
// PreInsert is a function to be executed before insert.
func (c *Comment) PreInsert(s gorp.SqlExecutor) error {
c.Created = time.Now()
c.Updated = c.Created
return nil
}
func run() exitcode {
dsn := os.Getenv("DSN")
db, err := sql.Open("postgres", dsn)
if err != nil {
log.Printf("failed to open db: %v", err)
return exitFailOpenDB
}
defer db.Close()
// Create table
dbmap := &gorp.DbMap{Db: db, Dialect: gorp.PostgresDialect{}}
dbmap.AddTableWithName(Comment{}, "comments").SetKeys(true, "id")
err = dbmap.CreateTablesIfNotExists()
if err != nil {
log.Printf("failed to create commnet db: %v", err)
return exitFailCreateDB
}
// Pre-check with ping
err = db.Ping()
if err != nil {
log.Printf("failed to ping db: %v", err)
return exitFailPingDB
}
// Query
err = dbmap.Insert(&Comment{Name: "bob", Text: "Hello"})
if err != nil {
log.Printf("failed to insert a Comment to db: %v", err)
return exitFailQuery
}
return exitOK
}
@kemokemo
Copy link
Author

kemokemo commented Nov 4, 2019

This sample is inspired by the mattn/echo-example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment