From 540a7ffc4e66ab36fa16487584fce2387efb7785 Mon Sep 17 00:00:00 2001
From: Sercan Yesildal <sercan.yesildal@gmail.com>
Date: Sun, 9 Jul 2023 21:51:01 +0200
Subject: [PATCH] wip db

---
 docker-compose.yml                   |   9 +-
 service/planner/Dockerfile           |  13 ++
 service/planner/db/db.go             |  27 ++++
 service/planner/docker-entrypoint.sh |  10 ++
 service/planner/go.mod               |  12 +-
 service/planner/go.sum               |  11 ++
 service/planner/main.go              |   6 +
 service/planner/model/group.go       |   7 +-
 service/planner/model/meal.go        |  10 +-
 service/planner/model/shopping.go    |   6 +-
 service/planner/model/user.go        |  12 +-
 service/planner/wait-for-it.sh       | 182 +++++++++++++++++++++++++++
 12 files changed, 289 insertions(+), 16 deletions(-)
 create mode 100644 service/planner/Dockerfile
 create mode 100644 service/planner/db/db.go
 create mode 100644 service/planner/docker-entrypoint.sh
 create mode 100644 service/planner/wait-for-it.sh

diff --git a/docker-compose.yml b/docker-compose.yml
index 9fa2073..c6d27d2 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -6,4 +6,11 @@ services:
   planner:
     build: ./service/planner
     ports:
-      - "8000:8000"
\ No newline at end of file
+      - "8000:8000"
+    environment:
+      - DB_CONNECT=mariadb:3306
+  mariadb:
+    image: mariadb:10.5
+    environment:
+      - MYSQL_ROOT_PASSWORD=root
+      - MYSQL_DATABASE=planner
diff --git a/service/planner/Dockerfile b/service/planner/Dockerfile
new file mode 100644
index 0000000..3f6b594
--- /dev/null
+++ b/service/planner/Dockerfile
@@ -0,0 +1,13 @@
+FROM golang:1.20-buster
+
+WORKDIR /go/src/app
+COPY . /go/src/app
+
+RUN go mod download
+RUN go install
+
+RUN chmod +x ./wait-for-it.sh ./docker-entrypoint.sh
+ENTRYPOINT ["./docker-entrypoint.sh"]
+
+CMD ["planner"]
+EXPOSE 8000
\ No newline at end of file
diff --git a/service/planner/db/db.go b/service/planner/db/db.go
new file mode 100644
index 0000000..46a20fd
--- /dev/null
+++ b/service/planner/db/db.go
@@ -0,0 +1,27 @@
+package db
+
+import (
+	"fmt"
+	"os"
+
+	"gitlab.reutlingen-university.de/yesildas/mealplanner2go/service/planner/model"
+	"gorm.io/driver/mysql"
+	"gorm.io/gorm"
+)
+
+var DB *gorm.DB
+
+func Init() {
+	dsn := fmt.Sprintf("root:root@tcp(%s)/planner?charset=utf8&parseTime=True&loc=Local", os.Getenv("DB_CONNECT"))
+	var err error
+	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
+	if err != nil {
+		panic("failed to connect to database")
+	}
+	if err := DB.Debug().AutoMigrate(&model.Group{}); err != nil {
+		panic(err)
+	}
+	if err := DB.Debug().AutoMigrate(&model.User{}); err != nil {
+		panic(err)
+	}
+}
diff --git a/service/planner/docker-entrypoint.sh b/service/planner/docker-entrypoint.sh
new file mode 100644
index 0000000..eb974cd
--- /dev/null
+++ b/service/planner/docker-entrypoint.sh
@@ -0,0 +1,10 @@
+#!/bin/sh
+
+# Abort on any error (including if wait-for-it fails).
+set -e
+# Wait for DB
+if [ -n "$DB_CONNECT" ]; then
+    /go/src/app/wait-for-it.sh "$DB_CONNECT" -t 60
+fi
+# Run the main container command.
+exec "$@"
diff --git a/service/planner/go.mod b/service/planner/go.mod
index 5f0565d..b654ef7 100644
--- a/service/planner/go.mod
+++ b/service/planner/go.mod
@@ -2,4 +2,14 @@ module gitlab.reutlingen-university.de/yesildas/mealplanner2go/service/planner
 
 go 1.20
 
-require github.com/gorilla/mux v1.8.0
+require (
+	github.com/gorilla/mux v1.8.0
+	gorm.io/driver/mysql v1.5.1
+	gorm.io/gorm v1.25.2
+)
+
+require (
+	github.com/go-sql-driver/mysql v1.7.0 // indirect
+	github.com/jinzhu/inflection v1.0.0 // indirect
+	github.com/jinzhu/now v1.1.5 // indirect
+)
diff --git a/service/planner/go.sum b/service/planner/go.sum
index 5350288..c0a2264 100644
--- a/service/planner/go.sum
+++ b/service/planner/go.sum
@@ -1,2 +1,13 @@
+github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
+github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
 github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
 github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
+github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
+github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
+github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
+github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
+gorm.io/driver/mysql v1.5.1 h1:WUEH5VF9obL/lTtzjmML/5e6VfFR/788coz2uaVCAZw=
+gorm.io/driver/mysql v1.5.1/go.mod h1:Jo3Xu7mMhCyj8dlrb3WoCaRd1FhsVh+yMXb1jUInf5o=
+gorm.io/gorm v1.25.1/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
+gorm.io/gorm v1.25.2 h1:gs1o6Vsa+oVKG/a9ElL3XgyGfghFfkKA2SInQaCyMho=
+gorm.io/gorm v1.25.2/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
diff --git a/service/planner/main.go b/service/planner/main.go
index 476fe4f..adac101 100644
--- a/service/planner/main.go
+++ b/service/planner/main.go
@@ -6,8 +6,14 @@ import (
 	"net/http"
 
 	"github.com/gorilla/mux"
+	"gitlab.reutlingen-university.de/yesildas/mealplanner2go/service/planner/db"
 )
 
+func init() {
+	// init database
+	defer db.Init()
+}
+
 func main() {
 	port := 8000
 	router := mux.NewRouter()
diff --git a/service/planner/model/group.go b/service/planner/model/group.go
index e0eeb9e..f27562d 100644
--- a/service/planner/model/group.go
+++ b/service/planner/model/group.go
@@ -1,5 +1,10 @@
 package model
 
+import "gorm.io/gorm"
+
 type Group struct {
-	Users []*User
+	gorm.Model
+	ID      uint        `json:"id" gorm:"primaryKey"`
+	UserIDs []uint      `json:"userIds"`
+	Meals   []MealGroup `json:"meals" gorm:"foreignKey: GroupID; constraint:OnUpdate:CASCADE, OnDelete:CASCADE"`
 }
diff --git a/service/planner/model/meal.go b/service/planner/model/meal.go
index 0c8166e..2dc3214 100644
--- a/service/planner/model/meal.go
+++ b/service/planner/model/meal.go
@@ -1,18 +1,16 @@
 package model
 
-import "time"
-
 type Meal struct {
-	MealId int
-	Date   time.Time
+	MealID int    `json:"mealId" gorm:"notNull"`
+	Date   string `json:"date" gorm:"notNull"`
 }
 
 type MealUser struct {
+	UserID uint `json:"userId"`
 	Meal
-	User User
 }
 
 type MealGroup struct {
+	GroupID uint `json:"groupId"`
 	Meal
-	Group Group
 }
diff --git a/service/planner/model/shopping.go b/service/planner/model/shopping.go
index 3b843c9..9477fd8 100644
--- a/service/planner/model/shopping.go
+++ b/service/planner/model/shopping.go
@@ -1,8 +1,6 @@
 package model
 
-import "time"
-
 type ShoppingDate struct {
-	Date time.Time
-	User User
+	UserID uint   `json:"userId"`
+	Date   string `json:"date" gorm:"notNull"`
 }
diff --git a/service/planner/model/user.go b/service/planner/model/user.go
index 77ec23e..5648f4e 100644
--- a/service/planner/model/user.go
+++ b/service/planner/model/user.go
@@ -1,7 +1,13 @@
 package model
 
+import "gorm.io/gorm"
+
 type User struct {
-	Mail      string
-	FirstName string
-	LastName  string
+	gorm.Model
+	ID            uint           `json:"id" gorm:"primaryKey"`
+	Mail          string         `json:"mail" gorm:"notNull"`
+	FirstName     string         `json:"firstName" gorm:"notNull"`
+	LastName      string         `json:"lastName" gorm:"notNull"`
+	Meals         []MealUser     `json:"meals" gorm:"foreignKey: UserID; constraint:OnUpdate:CASCADE, OnDelete:CASCADE"`
+	ShoppingDates []ShoppingDate `json:"shoppingDates" gorm:"foreignKey: UserID; constraint:OnUpdate:CASCADE, OnDelete:CASCADE"`
 }
diff --git a/service/planner/wait-for-it.sh b/service/planner/wait-for-it.sh
new file mode 100644
index 0000000..d990e0d
--- /dev/null
+++ b/service/planner/wait-for-it.sh
@@ -0,0 +1,182 @@
+#!/usr/bin/env bash
+# Use this script to test if a given TCP host/port are available
+
+WAITFORIT_cmdname=${0##*/}
+
+echoerr() { if [[ $WAITFORIT_QUIET -ne 1 ]]; then echo "$@" 1>&2; fi }
+
+usage()
+{
+    cat << USAGE >&2
+Usage:
+    $WAITFORIT_cmdname host:port [-s] [-t timeout] [-- command args]
+    -h HOST | --host=HOST       Host or IP under test
+    -p PORT | --port=PORT       TCP port under test
+                                Alternatively, you specify the host and port as host:port
+    -s | --strict               Only execute subcommand if the test succeeds
+    -q | --quiet                Don't output any status messages
+    -t TIMEOUT | --timeout=TIMEOUT
+                                Timeout in seconds, zero for no timeout
+    -- COMMAND ARGS             Execute command with args after the test finishes
+USAGE
+    exit 1
+}
+
+wait_for()
+{
+    if [[ $WAITFORIT_TIMEOUT -gt 0 ]]; then
+        echoerr "$WAITFORIT_cmdname: waiting $WAITFORIT_TIMEOUT seconds for $WAITFORIT_HOST:$WAITFORIT_PORT"
+    else
+        echoerr "$WAITFORIT_cmdname: waiting for $WAITFORIT_HOST:$WAITFORIT_PORT without a timeout"
+    fi
+    WAITFORIT_start_ts=$(date +%s)
+    while :
+    do
+        if [[ $WAITFORIT_ISBUSY -eq 1 ]]; then
+            nc -z $WAITFORIT_HOST $WAITFORIT_PORT
+            WAITFORIT_result=$?
+        else
+            (echo -n > /dev/tcp/$WAITFORIT_HOST/$WAITFORIT_PORT) >/dev/null 2>&1
+            WAITFORIT_result=$?
+        fi
+        if [[ $WAITFORIT_result -eq 0 ]]; then
+            WAITFORIT_end_ts=$(date +%s)
+            echoerr "$WAITFORIT_cmdname: $WAITFORIT_HOST:$WAITFORIT_PORT is available after $((WAITFORIT_end_ts - WAITFORIT_start_ts)) seconds"
+            break
+        fi
+        sleep 1
+    done
+    return $WAITFORIT_result
+}
+
+wait_for_wrapper()
+{
+    # In order to support SIGINT during timeout: http://unix.stackexchange.com/a/57692
+    if [[ $WAITFORIT_QUIET -eq 1 ]]; then
+        timeout $WAITFORIT_BUSYTIMEFLAG $WAITFORIT_TIMEOUT $0 --quiet --child --host=$WAITFORIT_HOST --port=$WAITFORIT_PORT --timeout=$WAITFORIT_TIMEOUT &
+    else
+        timeout $WAITFORIT_BUSYTIMEFLAG $WAITFORIT_TIMEOUT $0 --child --host=$WAITFORIT_HOST --port=$WAITFORIT_PORT --timeout=$WAITFORIT_TIMEOUT &
+    fi
+    WAITFORIT_PID=$!
+    trap "kill -INT -$WAITFORIT_PID" INT
+    wait $WAITFORIT_PID
+    WAITFORIT_RESULT=$?
+    if [[ $WAITFORIT_RESULT -ne 0 ]]; then
+        echoerr "$WAITFORIT_cmdname: timeout occurred after waiting $WAITFORIT_TIMEOUT seconds for $WAITFORIT_HOST:$WAITFORIT_PORT"
+    fi
+    return $WAITFORIT_RESULT
+}
+
+# process arguments
+while [[ $# -gt 0 ]]
+do
+    case "$1" in
+        *:* )
+        WAITFORIT_hostport=(${1//:/ })
+        WAITFORIT_HOST=${WAITFORIT_hostport[0]}
+        WAITFORIT_PORT=${WAITFORIT_hostport[1]}
+        shift 1
+        ;;
+        --child)
+        WAITFORIT_CHILD=1
+        shift 1
+        ;;
+        -q | --quiet)
+        WAITFORIT_QUIET=1
+        shift 1
+        ;;
+        -s | --strict)
+        WAITFORIT_STRICT=1
+        shift 1
+        ;;
+        -h)
+        WAITFORIT_HOST="$2"
+        if [[ $WAITFORIT_HOST == "" ]]; then break; fi
+        shift 2
+        ;;
+        --host=*)
+        WAITFORIT_HOST="${1#*=}"
+        shift 1
+        ;;
+        -p)
+        WAITFORIT_PORT="$2"
+        if [[ $WAITFORIT_PORT == "" ]]; then break; fi
+        shift 2
+        ;;
+        --port=*)
+        WAITFORIT_PORT="${1#*=}"
+        shift 1
+        ;;
+        -t)
+        WAITFORIT_TIMEOUT="$2"
+        if [[ $WAITFORIT_TIMEOUT == "" ]]; then break; fi
+        shift 2
+        ;;
+        --timeout=*)
+        WAITFORIT_TIMEOUT="${1#*=}"
+        shift 1
+        ;;
+        --)
+        shift
+        WAITFORIT_CLI=("$@")
+        break
+        ;;
+        --help)
+        usage
+        ;;
+        *)
+        echoerr "Unknown argument: $1"
+        usage
+        ;;
+    esac
+done
+
+if [[ "$WAITFORIT_HOST" == "" || "$WAITFORIT_PORT" == "" ]]; then
+    echoerr "Error: you need to provide a host and port to test."
+    usage
+fi
+
+WAITFORIT_TIMEOUT=${WAITFORIT_TIMEOUT:-15}
+WAITFORIT_STRICT=${WAITFORIT_STRICT:-0}
+WAITFORIT_CHILD=${WAITFORIT_CHILD:-0}
+WAITFORIT_QUIET=${WAITFORIT_QUIET:-0}
+
+# Check to see if timeout is from busybox?
+WAITFORIT_TIMEOUT_PATH=$(type -p timeout)
+WAITFORIT_TIMEOUT_PATH=$(realpath $WAITFORIT_TIMEOUT_PATH 2>/dev/null || readlink -f $WAITFORIT_TIMEOUT_PATH)
+
+WAITFORIT_BUSYTIMEFLAG=""
+if [[ $WAITFORIT_TIMEOUT_PATH =~ "busybox" ]]; then
+    WAITFORIT_ISBUSY=1
+    # Check if busybox timeout uses -t flag
+    # (recent Alpine versions don't support -t anymore)
+    if timeout &>/dev/stdout | grep -q -e '-t '; then
+        WAITFORIT_BUSYTIMEFLAG="-t"
+    fi
+else
+    WAITFORIT_ISBUSY=0
+fi
+
+if [[ $WAITFORIT_CHILD -gt 0 ]]; then
+    wait_for
+    WAITFORIT_RESULT=$?
+    exit $WAITFORIT_RESULT
+else
+    if [[ $WAITFORIT_TIMEOUT -gt 0 ]]; then
+        wait_for_wrapper
+        WAITFORIT_RESULT=$?
+    else
+        wait_for
+        WAITFORIT_RESULT=$?
+    fi
+fi
+
+if [[ $WAITFORIT_CLI != "" ]]; then
+    if [[ $WAITFORIT_RESULT -ne 0 && $WAITFORIT_STRICT -eq 1 ]]; then
+        echoerr "$WAITFORIT_cmdname: strict mode, refusing to execute subprocess"
+        exit $WAITFORIT_RESULT
+    fi
+    exec "${WAITFORIT_CLI[@]}"
+else
+    exit $WAITFORIT_RESULT
+fi
-- 
GitLab