From df398dab1ab09f478533346344c0766c16fef4b4 Mon Sep 17 00:00:00 2001 From: ycc Date: Tue, 17 May 2022 17:03:38 +0200 Subject: [PATCH] Null management --- .gitignore | 1 + pg.go | 37 ++++++++++++++++++------------------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/.gitignore b/.gitignore index 66fd13c..1a2efcb 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ # Dependency directories (remove the comment below to include it) # vendor/ +__debug_bin diff --git a/pg.go b/pg.go index b32b8ef..da402df 100755 --- a/pg.go +++ b/pg.go @@ -325,15 +325,8 @@ func (t *TableInfo) Insert(record AssRow) (int, error) { var id int for key, element := range record { - - if strings.Contains(t.Columns[key], "char") || strings.Contains(t.Columns[key], "date") { - columns += key + "," - values += fmt.Sprint(pq.QuoteLiteral(fmt.Sprintf("%v", element))) + "," - } else { - - columns += key + "," - values += fmt.Sprintf("%v", element) + "," - } + columns += key + "," + values += FormatForSQL(t.Columns[key], element) + "," } t.db.conn.QueryRow("INSERT INTO " + t.Name + "(" + removeLastChar(columns) + ") VALUES (" + removeLastChar(values) + ") RETURNING id").Scan(&id) @@ -352,18 +345,12 @@ func (t *TableInfo) Update(record AssRow) error { for key, element := range record { - if strings.Contains(t.Columns[key], "char") || strings.Contains(t.Columns[key], "date") { - - stack = stack + " " + key + " = " + pq.QuoteLiteral(fmt.Sprintf("%v", element)) + "," - + if key == "id" { + id = fmt.Sprintf("%v", element) } else { - - if key == "id" { - id = fmt.Sprintf("%v", element) - } else { - stack = stack + " " + key + " = " + fmt.Sprintf("%v", element) + "," - } + stack = stack + " " + key + " = " + FormatForSQL(t.Columns[key], element) + "," } + } stack = removeLastChar(stack) query := ("UPDATE " + t.Name + " SET " + stack + " WHERE id = " + id) @@ -530,3 +517,15 @@ func (db *Db) GenerateTableTemplates(templateFilename string, outputFolder strin } return nil } + +func FormatForSQL(datatype string, value interface{}) string { + strval := fmt.Sprintf("%v", value) + if !strings.Contains(datatype, "char") && len(strval) == 0 { + return "NULL" + } + if strings.Contains(datatype, "char") || strings.Contains(datatype, "date") { + return fmt.Sprint(pq.QuoteLiteral(strval)) + } + return fmt.Sprint(strval) + +}