github.com/tobgu/qframe@v0.4.0/internal/io/sql/stmt.go (about)

     1  package sql
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  )
     7  
     8  func escape(s string, char rune, buf *bytes.Buffer) {
     9  	if char == 0 {
    10  		buf.WriteString(s)
    11  		return
    12  	}
    13  	buf.WriteRune(char)
    14  	buf.WriteString(s)
    15  	buf.WriteRune(char)
    16  }
    17  
    18  // Insert generates a SQL insert statement
    19  // for each colName. There are several variations
    20  // of SQL that need to be produced for each driver.
    21  // This has been tested with the following:
    22  // PostgreSQL - github.com/lib/pq
    23  // MySQL/MariaDB - github.com/go-sql-driver/mysql
    24  // SQLite - github.com/mattn/go-sqlite3
    25  //
    26  // "Parameter markers" are used to specify placeholders
    27  // for values scanned by the implementing driver:
    28  // PostgreSQL accepts "incrementing" markers e.g. $1..$2
    29  // While MySQL/MariaDB and SQLite accept ?..?.
    30  func Insert(colNames []string, conf SQLConfig) string {
    31  	buf := bytes.NewBuffer(nil)
    32  	buf.WriteString("INSERT INTO ")
    33  	escape(conf.Table, conf.EscapeChar, buf)
    34  	buf.WriteString(" (")
    35  	for i, name := range colNames {
    36  		escape(name, conf.EscapeChar, buf)
    37  		if i+1 < len(colNames) {
    38  			buf.WriteString(",")
    39  		}
    40  	}
    41  	buf.WriteString(") VALUES (")
    42  	for i := range colNames {
    43  		if conf.Incrementing {
    44  			buf.WriteString(fmt.Sprintf("$%d", i+1))
    45  		} else {
    46  			buf.WriteString("?")
    47  		}
    48  		if i+1 < len(colNames) {
    49  			buf.WriteString(",")
    50  		}
    51  	}
    52  	buf.WriteString(");")
    53  	return buf.String()
    54  }