Moving gorm ORM library for Golang database connections

Also creating the Create API for components
This commit is contained in:
Arpit Mohan 2019-02-26 23:22:37 +05:30
parent 13156380ce
commit acbb5a55e0
7 changed files with 42 additions and 60 deletions

View File

@ -1,18 +1,2 @@
// Package api contains all the handlers that the client will invoke on the middleware server
package api
import (
"fmt"
"net/http"
"github.com/julienschmidt/httprouter"
)
func IndexHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprintf(w, string("hello there"))
}
func TableHandler(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
tableName := params.ByName("name")
fmt.Fprintf(w, "hello %s", tableName)
}

View File

@ -5,7 +5,9 @@ package api
import (
"encoding/json"
"fmt"
"internal-tools-server/models"
"internal-tools-server/storage"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
@ -13,7 +15,8 @@ import (
// GetComponents fetches the list of components from the DB
func GetComponents(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
queryValues := r.URL.Query()
log.Println(queryValues["type"])
components, _ := storage.StorageEngine.ExecuteQuery("select * from components")
componentsJSON, _ := json.Marshal(components)
@ -23,3 +26,22 @@ func GetComponents(w http.ResponseWriter, r *http.Request, params httprouter.Par
w.WriteHeader(200)
fmt.Fprintf(w, "%s", componentsJSON)
}
// CreateComponents creates components in the DB
func CreateComponents(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
component := models.Component{}
err := json.NewDecoder(r.Body).Decode(&component)
if err != nil {
fmt.Errorf("Error caught while parsing component body")
}
datastore := storage.StorageEngine.GetDatastore()
datastore.Create(&component)
// TODO: Create the component in the DB here
// Write content-type, statuscode, payload
componentJSON, _ := json.Marshal(component)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "%s", componentJSON)
}

View File

@ -1,6 +1,8 @@
module internal-tools-server
require (
github.com/jinzhu/gorm v1.9.2
github.com/jinzhu/inflection v0.0.0-20180308033659-04140366298a // indirect
github.com/julienschmidt/httprouter v1.2.0
github.com/lib/pq v1.0.0
)

View File

@ -1,3 +1,7 @@
github.com/jinzhu/gorm v1.9.2 h1:lCvgEaqe/HVE+tjAR2mt4HbbHAZsQOv3XAZiEZV37iw=
github.com/jinzhu/gorm v1.9.2/go.mod h1:Vla75njaFJ8clLU1W44h34PjIkijhjHIYnZxMqCdxqo=
github.com/jinzhu/inflection v0.0.0-20180308033659-04140366298a h1:eeaG9XMUvRBYXJi4pg1ZKM7nxc5AfXfojeLLW7O5J3k=
github.com/jinzhu/inflection v0.0.0-20180308033659-04140366298a/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/julienschmidt/httprouter v1.2.0 h1:TDTW5Yz1mjftljbcKqRcrYhd4XeOoI98t+9HbQbYf7g=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/lib/pq v1.0.0 h1:X5PMW56eZitiTeO7tKzZxFCSpbFZJtkMMooicw2us9A=

View File

@ -23,6 +23,7 @@ func main() {
// Component CRUD Endpoints
router.GET("/api/v1/components", api.GetComponents)
router.POST("/api/v1/components", api.CreateComponents)
// Page CRUD Endpoints

View File

@ -5,6 +5,8 @@ import (
"fmt"
"internal-tools-server/models"
"log"
"github.com/jinzhu/gorm"
)
var db *sql.DB
@ -14,6 +16,7 @@ var StorageEngine DataStore
// DataStore defines the interface that all db implementations must implement.
type DataStore interface {
ExecuteQuery(query string) ([]models.Component, error)
GetDatastore() *gorm.DB
}
type DataStoreFactory func() (DataStore, error)

View File

@ -1,13 +1,13 @@
package storage
import (
"database/sql"
"fmt"
"internal-tools-server/models"
"log"
"os"
_ "github.com/lib/pq"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
type PostgresDataStore struct {
@ -17,7 +17,7 @@ type PostgresDataStore struct {
Dbpass string
Dbname string
MaxOpenConnections int
db *sql.DB
DB *gorm.DB
}
const (
@ -41,7 +41,7 @@ func InitPostgresDb() (datastore DataStore, err error) {
d.Dbhost, d.Dbport,
d.Dbuser, d.Dbpass, d.Dbname)
d.db, err = sql.Open("postgres", psqlInfo)
d.DB, err = gorm.Open("postgres", psqlInfo)
if err != nil {
return nil, err
@ -49,18 +49,14 @@ func InitPostgresDb() (datastore DataStore, err error) {
// Since the error returned from “Open” does not check if the datasource is valid calling
// Ping on the database is required
err = d.db.Ping()
err = d.DB.DB().Ping()
if err != nil {
log.Fatal("Error: Could not establish a connection with the database")
}
// Setup connection pool
d.db.SetMaxOpenConns(d.MaxOpenConnections)
d.DB.DB().SetMaxOpenConns(d.MaxOpenConnections)
err = d.db.Ping()
if err != nil {
return nil, err
}
fmt.Println("Successfully connected!")
// listTables()
return &d, nil
@ -93,7 +89,7 @@ func (d *PostgresDataStore) dbConfig() {
// ExecuteQuery executes the query on the DB
func (d *PostgresDataStore) ExecuteQuery(query string) ([]models.Component, error) {
rows, err := d.db.Query(query)
rows, err := d.DB.Raw(query).Rows()
if err != nil {
return nil, err
}
@ -113,36 +109,6 @@ func (d *PostgresDataStore) ExecuteQuery(query string) ([]models.Component, erro
return components, nil
}
type schemaSummary struct {
tableName string
}
// listTables first fetches the tables from the db
func listTables() error {
tables := []schemaSummary{}
rows, err := db.Query(`
SELECT table_name as tableName FROM information_schema.tables WHERE table_schema='public'; `)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
schema := schemaSummary{}
err = rows.Scan(
&schema.tableName,
)
fmt.Printf("Name: %s\n", schema.tableName)
if err != nil {
return err
}
tables = append(tables, schema)
}
err = rows.Err()
if err != nil {
return err
}
fmt.Printf("\nTables: %x\n", tables)
return nil
func (d *PostgresDataStore) GetDatastore() *gorm.DB {
return d.DB
}