Null management

This commit is contained in:
ycc 2022-05-17 17:03:38 +02:00
parent c9614975a6
commit df398dab1a
2 changed files with 19 additions and 19 deletions

1
.gitignore vendored
View File

@ -13,3 +13,4 @@
# Dependency directories (remove the comment below to include it) # Dependency directories (remove the comment below to include it)
# vendor/ # vendor/
__debug_bin

37
pg.go
View File

@ -325,15 +325,8 @@ func (t *TableInfo) Insert(record AssRow) (int, error) {
var id int var id int
for key, element := range record { for key, element := range record {
columns += key + ","
if strings.Contains(t.Columns[key], "char") || strings.Contains(t.Columns[key], "date") { values += FormatForSQL(t.Columns[key], element) + ","
columns += key + ","
values += fmt.Sprint(pq.QuoteLiteral(fmt.Sprintf("%v", element))) + ","
} else {
columns += key + ","
values += fmt.Sprintf("%v", element) + ","
}
} }
t.db.conn.QueryRow("INSERT INTO " + t.Name + "(" + removeLastChar(columns) + ") VALUES (" + removeLastChar(values) + ") RETURNING id").Scan(&id) 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 { for key, element := range record {
if strings.Contains(t.Columns[key], "char") || strings.Contains(t.Columns[key], "date") { if key == "id" {
id = fmt.Sprintf("%v", element)
stack = stack + " " + key + " = " + pq.QuoteLiteral(fmt.Sprintf("%v", element)) + ","
} else { } else {
stack = stack + " " + key + " = " + FormatForSQL(t.Columns[key], element) + ","
if key == "id" {
id = fmt.Sprintf("%v", element)
} else {
stack = stack + " " + key + " = " + fmt.Sprintf("%v", element) + ","
}
} }
} }
stack = removeLastChar(stack) stack = removeLastChar(stack)
query := ("UPDATE " + t.Name + " SET " + stack + " WHERE id = " + id) query := ("UPDATE " + t.Name + " SET " + stack + " WHERE id = " + id)
@ -530,3 +517,15 @@ func (db *Db) GenerateTableTemplates(templateFilename string, outputFolder strin
} }
return nil 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)
}