Last active
August 29, 2015 13:55
-
-
Save brnstz/8701140 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "bytes" | |
// "Quote" a string in backticks so it can be safely used in a dynamic | |
// query as a field or table name. The returned string will be | |
// surrounded by backticks, and any backticks inside the string will | |
// escaped (by another backtick). | |
// | |
// For example, this won't work: | |
// db.Query("SELECT * FROM ?", "mytable") | |
// | |
// With this function, you can do: | |
// db.Query(fmt.Sprintf("SELECT * FROM %s", MySQLBacktick("mytable"))) | |
// | |
// Even if your table name has more backticks embededed in it. This will | |
// safely query from a table named asdf```. The query formatted string will | |
// look like: | |
// SELECT * FROM `asdf``````` | |
// db.Query(fmt.Sprintf("SELECT * FROM %s", MySQLBacktick("asdf```"))) | |
func MySQLBacktick(incoming string) string { | |
var buffer bytes.Buffer | |
buffer.WriteRune('`') | |
for _, c := range incoming { | |
switch c { | |
case '`': | |
// Backticks must be escaped by another backtick to ensure | |
// the string doesn't break out of the syntax. | |
buffer.WriteRune('`') | |
} | |
buffer.WriteRune(c) | |
} | |
buffer.WriteRune('`') | |
return string(buffer.Bytes()) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment