Commit 837bd946 authored by Faizal Aziz's avatar Faizal Aziz

dev adding create table

parent dfe0840b
...@@ -2,6 +2,9 @@ package dbcon ...@@ -2,6 +2,9 @@ package dbcon
import ( import (
"context" "context"
"fmt"
"reflect"
"strings"
"time" "time"
"gorm.io/driver/postgres" "gorm.io/driver/postgres"
...@@ -12,6 +15,12 @@ import ( ...@@ -12,6 +15,12 @@ import (
log "gitlab.ursabyte.com/faizal.aziz/ulfssar-go/logger" log "gitlab.ursabyte.com/faizal.aziz/ulfssar-go/logger"
) )
var Keys = map[string]string{
"Primary Key": "pk",
"Foregin Key": "fk",
"Unique": "unique",
}
type ( type (
postgresqldb struct { postgresqldb struct {
db *gorm.DB db *gorm.DB
...@@ -167,6 +176,10 @@ func (d *postgresqldb) Create(args interface{}) error { ...@@ -167,6 +176,10 @@ func (d *postgresqldb) Create(args interface{}) error {
return d.db.Create(args).Error return d.db.Create(args).Error
} }
func (d *postgresqldb) CreateTable(tableName string, structs interface{}) error {
return d.db.Create(generateSQLFromStorage(tableName, structs)).Error
}
func (d *postgresqldb) Update(args interface{}) error { func (d *postgresqldb) Update(args interface{}) error {
return d.db.Updates(args).Error return d.db.Updates(args).Error
} }
...@@ -303,3 +316,41 @@ func NewPostgreSql(option *PostgreSqlOption) (ORM, error) { ...@@ -303,3 +316,41 @@ func NewPostgreSql(option *PostgreSqlOption) (ORM, error) {
return &postgresqldb{db: db}, nil return &postgresqldb{db: db}, nil
} }
func generateSQLFromStorage(tableName string, columnAndValues interface{}) string {
st := reflect.TypeOf(columnAndValues)
var columnNames strings.Builder
for i := 0; i < st.NumField(); i++ {
field := st.Field(i)
columnName := field.Tag.Get("sql-column")
if columnName == "" {
columnName = field.Name
}
typeName := field.Tag.Get("sql-type")
if typeName == "" {
typeName = "text"
}
argName := field.Tag.Get("sql-constraint")
keysName := field.Tag.Get("sql-keys")
if keysName == "" {
keysName = ""
} else {
if keysName != "" && argName == "" {
for key, val := range Keys {
if strings.Contains(keysName, key) || strings.Contains(keysName, strings.ToUpper(key)) || strings.Contains(keysName, strings.ToLower(key)) {
argName = val
}
}
argName = fmt.Sprintf("%s_%s", keysName, argName)
}
}
columnNames.WriteString(fmt.Sprintf("%s %s %s %s ,", columnNames, typeName, argName, keysName))
}
columnNamesStr := strings.TrimRight(columnNames.String(), ",")
return fmt.Sprintf("CREATE TABLE %s '(%s)'", tableName, columnNamesStr)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment