@@ -1500,6 +1500,39 @@ func QuoteIdentifier(name string) string {
1500
1500
return `"` + strings .Replace (name , `"` , `""` , - 1 ) + `"`
1501
1501
}
1502
1502
1503
+ // QuoteLiteral quotes a 'literal' (e.g. a parameter, often used to pass literal
1504
+ // to DDL and other statements that do not accept parameters) to be used as part
1505
+ // of an SQL statement. For example:
1506
+ //
1507
+ // exp_date := pq.QuoteLiteral("2023-01-05 15:00:00Z")
1508
+ // err := db.Exec(fmt.Sprintf("CREATE ROLE my_user VALID UNTIL %s", exp_date))
1509
+ //
1510
+ // Any single quotes in name will be escaped. Any backslashes (i.e. "\") will be
1511
+ // replaced by two backslashes (i.e. "\\") and the C-style escape identifier
1512
+ // that PostgreSQL provides ('E') will be prepended to the string.
1513
+ func QuoteLiteral (literal string ) string {
1514
+ // This follows the PostgreSQL internal algorithm for handling quoted literals
1515
+ // from libpq, which can be found in the "PQEscapeStringInternal" function,
1516
+ // which is found in the libpq/fe-exec.c source file:
1517
+ // https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/interfaces/libpq/fe-exec.c
1518
+ //
1519
+ // substitute any single-quotes (') with two single-quotes ('')
1520
+ literal = strings .Replace (literal , `'` , `''` , - 1 )
1521
+ // determine if the string has any backslashes (\) in it.
1522
+ // if it does, replace any backslashes (\) with two backslashes (\\)
1523
+ // then, we need to wrap the entire string with a PostgreSQL
1524
+ // C-style escape. Per how "PQEscapeStringInternal" handles this case, we
1525
+ // also add a space before the "E"
1526
+ if strings .Contains (literal , `\` ) {
1527
+ literal = strings .Replace (literal , `\` , `\\` , - 1 )
1528
+ literal = ` E'` + literal + `'`
1529
+ } else {
1530
+ // otherwise, we can just wrap the literal with a pair of single quotes
1531
+ literal = `'` + literal + `'`
1532
+ }
1533
+ return literal
1534
+ }
1535
+
1503
1536
func md5s (s string ) string {
1504
1537
h := md5 .New ()
1505
1538
h .Write ([]byte (s ))
0 commit comments