Skip to content

Commit

Permalink
Force nvchar/varbinary types to have a min length of 1.
Browse files Browse the repository at this point in the history
This allows for inserting empty strings into the database.

According to http://msdn.microsoft.com/en-us/library/ms186939.aspx,
these types may never have a length of 0, even if their contents
are actually length 0.
  • Loading branch information
thatguystone committed Jan 20, 2015
1 parent 550d514 commit b2a5891
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions executesql.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ func quote(in string) string {
return strings.Replace(in, "'", "''", -1)
}

func max(a int, b int) int {
if a > b {
return a
}

return b
}

func go2SqlDataType(value interface{}) (string, string) {
//TODO - bool value
strValue := fmt.Sprintf("%v", value)
Expand All @@ -92,13 +100,13 @@ func go2SqlDataType(value interface{}) (string, string) {
case []byte:
{
b, _ := value.([]byte)
return fmt.Sprintf("varbinary (%d)", len(b)),
return fmt.Sprintf("varbinary (%d)", max(1, len(b))),
fmt.Sprintf("0x%x", b)
}
default:
log.Printf("unknown dataType %t", t)
}
return fmt.Sprintf("nvarchar (%d)", len(strValue)),
return fmt.Sprintf("nvarchar (%d)", max(1, len(strValue))),
fmt.Sprintf("'%s'", quote(strValue))

}

0 comments on commit b2a5891

Please sign in to comment.