Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement postgresql package #3

Merged
merged 7 commits into from
May 21, 2021
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,27 @@ This service communicates based on gRPC. You can refer to the proto files in [tk

## Quick Start

### Development environment
* Installed docker 20.x
* Running postgresql and Initilizing database.
```
docker run -p 5432:5432 --name postgres -e POSTGRES_PASSWORD=password -d postgres
docker cp scripts/script.sql postgres:/script.sql
docker exec -ti postgres psql -U postgres -a -f script.sql
```
### For go developers

```
go install -v ./...
contract-server -port 50051 -enable-mockup
server -port 9110
```
### For docker users
```
TAGS=$(curl --silent "https://api.github.com/repos/sktelecom/tks-contract/tags" | grep name | head -1 |cut -d '"' -f 4)
docker pull docker.pkg.github.com/sktelecom/tks-contract/tks-contract:$TAGS
docker run --name tks-contract -p 50051:50051 -d \
docker run --name tks-contract -p 9110:9110 -d \
docker.pkg.github.com/sktelecom/tks-contract/tks-contract:$TAGS \
contract-server \
# -enable-mockup \
# -port 50051
server \
# -port 9110
```

File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion cmd/contract-server/server.go → cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ func setFlags() {
}

func main() {
flag.Parse()
lis, err := net.Listen("tcp", ":"+strconv.Itoa(port))
log.Info("Starting to listen port ", port)
flag.Parse()
if err != nil {
log.Fatal("failed to listen:", err)
}
Expand Down
File renamed without changes.
4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@ module github.com/sktelecom/tks-contract
go 1.16

require (
github.com/DATA-DOG/go-sqlmock v1.5.0
github.com/google/uuid v1.2.0
github.com/lib/pq v1.10.2
github.com/sirupsen/logrus v1.8.1
github.com/sktelecom/tks-proto v0.0.4-0.20210419072147-cbafa000deab
github.com/stretchr/testify v1.7.0 // indirect
google.golang.org/grpc v1.36.1
google.golang.org/protobuf v1.26.0
)
Expand Down
14 changes: 10 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
Expand Down Expand Up @@ -32,19 +34,22 @@ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs=
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/lib/pq v1.10.2 h1:AqzbZs4ZoCBp+GtejcpCpcxM3zlSMx29dXbUSeVtJb8=
github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sktelecom/tks-proto v0.0.4-0.20210419050352-2299e8d5d653 h1:plu5huLviWEh5uJyyVf3AZoYl8sajUtn2KfzkU2+wFs=
github.com/sktelecom/tks-proto v0.0.4-0.20210419050352-2299e8d5d653/go.mod h1:5r0c5Sq4RhX5IuVIyD/aRunO7WUHmpymBOBz9LTCaRY=
github.com/sktelecom/tks-proto v0.0.4-0.20210419072147-cbafa000deab h1:Jqxkx4bq1uC6Y5BRaqo2eKE8eCdewluZ+1aTtDAk0d0=
github.com/sktelecom/tks-proto v0.0.4-0.20210419072147-cbafa000deab/go.mod h1:5r0c5Sq4RhX5IuVIyD/aRunO7WUHmpymBOBz9LTCaRY=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
Expand Down Expand Up @@ -97,7 +102,8 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0
google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
197 changes: 197 additions & 0 deletions pkg/postgresql/accessor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
package postgresql

import (
"database/sql"
"fmt"

"github.com/sktelecom/tks-contract/pkg/log"

_ "github.com/lib/pq"
)

// Accessor is an accessor for PostgresqlDB.
type Accessor struct {
db *sql.DB
}

// New returns a new Postgresql.
func New(db *sql.DB) *Accessor {
return &Accessor{
db: db,
}
}

// Close closes database session.
func (p *Accessor) Close() error {
p.db.Close()
return nil
}

// Get returns result of querying from DB.
// Support both non-transactional and transactional queries.
func (p *Accessor) Get(tx *sql.Tx, fields, table string, conditions map[string]interface{}) (*sql.Rows, error) {
var query string
if len(conditions) != 0 {
conditionSql := getVarSyntaxFromMaps(conditions)
query = fmt.Sprintf(`SELECT %s FROM %s WHERE %s`, fields, table, conditionSql[0])
} else {
query = fmt.Sprintf(`SELECT %s FROM %s`, fields, table)
}

if tx == nil {
return p.db.Query(query)
}

rows, err := tx.Query(query)
estherk0 marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
if errRollback := tx.Rollback(); errRollback != nil {
log.Fatal("failed to rollback transaction: ", errRollback)
return nil, errRollback
}
return nil, err
}
return rows, nil
}

// Insert inserts new column into table.
func (p *Accessor) Insert(tx *sql.Tx, table string, values ...interface{}) (int64, error) {
query := fmt.Sprintf(`INSERT INTO %s VALUES(%s)`, table, getVarSyntax(len(values)))
var (
res sql.Result
err error
)
if tx == nil {
if res, err = p.db.Exec(query, values...); err != nil {
return 0, err
}
return res.RowsAffected()
}

if res, err = tx.Exec(query, values...); err != nil {
if errRollback := tx.Rollback(); errRollback != nil {
log.Fatal("failed to rollback transaction: ", errRollback)
return 0, errRollback
}
return 0, err
}
return res.RowsAffected()
}

// Delete deletes a row which meets a condition in table.
func (p *Accessor) Delete(tx *sql.Tx, table string, conditions map[string]interface{}) (int64, error) {
var (
res sql.Result
err error
)
conditionKeySql := getVarSyntaxFromMaps(conditions)
conditionValues := getValueSliceFromMaps(conditions)

query := fmt.Sprintf(`DELETE FROM %s WHERE %s`, table, conditionKeySql[0])
if tx == nil {
if res, err = p.db.Exec(query, conditionValues...); err != nil {
log.Fatal(err)
return 0, err
}
return res.RowsAffected()
}

if res, err = tx.Exec(query, conditionValues...); err != nil {
if errRollback := tx.Rollback(); errRollback != nil {
log.Fatal("failed to rollback transaction: ", errRollback)
return 0, errRollback
}
return 0, err
}
return res.RowsAffected()
}

// Update updates values of specific row which meets a condition in table.
func (p *Accessor) Update(tx *sql.Tx, table string, values, conditions map[string]interface{}) (int64, error) {
var (
res sql.Result
err error
)
sqlArr := getVarSyntaxFromMaps(values, conditions)
args := getValueSliceFromMaps(values, conditions)
query := fmt.Sprintf(`UPDATE %s SET %s WHERE %s`, table, sqlArr[0], sqlArr[1])
if tx == nil {
if res, err = p.db.Exec(query, args...); err != nil {
log.Fatal(err)
return 0, err
}
return res.RowsAffected()
}
if res, err = tx.Exec(query, args...); err != nil {
if errRollback := tx.Rollback(); errRollback != nil {
log.Fatal("failed to rollback transaction: ", errRollback)
return 0, errRollback
}
return 0, err
}
return res.RowsAffected()
}

func (p *Accessor) Query(query string, args ...interface{}) (*sql.Rows, error) {
return p.db.Query(query, args...)
}

func (p *Accessor) BeginTx() (*sql.Tx, error) {
return p.db.Begin()
}

func (p *Accessor) CommitTx(tx *sql.Tx) error {
return tx.Commit()
}

// getVarSyntax makes "$1, $2, $3..." string for SQL query.
func getVarSyntax(count int) string {
var (
result string
idx int
start bool = true
)
for idx = 1; idx <= count; idx++ {
if !start {
result += ", "
}
result += fmt.Sprintf(`$%d`, idx)
start = false
}
return result
}

// getValuesSliceFromMaps returns one slice gathering all values from multiple maps.
func getValueSliceFromMaps(maps ...map[string]interface{}) []interface{} {
result := make([]interface{}, 0)
for i := range maps {
for _, v := range maps[i] {
result = append(result, v)
}
}
return result
}

// getVarSyntaxFromMaps returns multiple varSyntax "name=$1, id=$2 ..." from multiple maps.
// Index of varSyntax between multiple maps increases continously.
func getVarSyntaxFromMaps(maps ...map[string]interface{}) []string {
var (
idx int = 1
result []string
)
for i := range maps {
var (
temp string
start bool = true
)
for k := range maps[i] {
if !start {
temp += ", "
}
temp += fmt.Sprintf("%s=$%d", k, idx)
start = false
idx++
}
result = append(result, temp)
}
return result
}
Loading