From 4cae7af3f93b47807cfc3b7bd17562873f31f030 Mon Sep 17 00:00:00 2001 From: supar Date: Fri, 17 Oct 2014 12:53:59 +0400 Subject: [PATCH] Add attribute DEFAULT '' to the CREAT, ALTER constructors --- orm/cmd_utils.go | 48 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/orm/cmd_utils.go b/orm/cmd_utils.go index 8304da6b..64f3f7c6 100644 --- a/orm/cmd_utils.go +++ b/orm/cmd_utils.go @@ -104,7 +104,11 @@ func getColumnAddQuery(al *alias, fi *fieldInfo) string { typ += " " + "NOT NULL" } - return fmt.Sprintf("ALTER TABLE %s%s%s ADD COLUMN %s%s%s %s", Q, fi.mi.table, Q, Q, fi.column, Q, typ) + return fmt.Sprintf("ALTER TABLE %s%s%s ADD COLUMN %s%s%s %s %s", + Q, fi.mi.table, Q, + Q, fi.column, Q, + typ, getColumnDefault(fi), + ) } // create database creation string. @@ -155,6 +159,9 @@ func getDbCreateSql(al *alias) (sqls []string, tableIndexes map[string][]dbIndex //if fi.initial.String() != "" { // column += " DEFAULT " + fi.initial.String() //} + + // Append attribute DEFAULT + column += getColumnDefault(fi) if fi.unique { column += " " + "UNIQUE" @@ -239,3 +246,42 @@ func getDbCreateSql(al *alias) (sqls []string, tableIndexes map[string][]dbIndex return } + + +// Get string value for the attribute "DEFAULT" for the CREATE, ALTER commands +func getColumnDefault(fi *fieldInfo) string { + var ( + v, t, d string + ) + + t = " DEFAULT '%s' " + + // These defaults will be useful if there no config value orm:"default" and NOT NULL is on + switch fieldType { + case TypeDateField: + d = "0000-00-00" + + case TypeDateTimeField: + d = "0000-00-00 00:00:00" + + case TypeBooleanField, TypeBitField, TypeSmallIntegerField, TypeIntegerField, + TypeBigIntegerField, TypePositiveBitField, TypePositiveSmallIntegerField, + TypePositiveIntegerField, TypePositiveBigIntegerField, TypeFloatField: + TypeDecimalField: + d = "0" + } + + if fi.colDefault { + if !fi.initial.Exist() { + v = fmt.Strintf(t, "") + } else { + v = fmt.Strintf(t, fi.initial.String()) + } + } else { + if !fi.null { + v = fmt.Strintf(t, d) + } + } + + return v +}