...

Source file src/github.com/ory/x/sqlxx/sqlxx.go

Documentation: github.com/ory/x/sqlxx

     1  package sqlxx
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/fatih/structs"
     8  
     9  	"github.com/ory/x/stringslice"
    10  )
    11  
    12  func keys(t interface{}, exclude []string) []string {
    13  	s := structs.New(t)
    14  	var keys []string
    15  	for _, field := range s.Fields() {
    16  		key := strings.Split(field.Tag("db"), ",")[0]
    17  		if len(key) > 0 && key != "-" && !stringslice.Has(exclude, key) {
    18  			keys = append(keys, key)
    19  		}
    20  	}
    21  
    22  	return keys
    23  }
    24  
    25  // NamedInsertArguments returns columns and arguments for SQL INSERT statements based on a struct's tags. Does
    26  // not work with nested structs or maps!
    27  //
    28  // 	type st struct {
    29  // 		Foo string `db:"foo"`
    30  // 		Bar string `db:"bar,omitempty"`
    31  // 		Baz string `db:"-"`
    32  // 		Zab string
    33  // 	}
    34  //	columns, arguments := NamedInsertArguments(new(st))
    35  //	query := fmt.Sprintf("INSERT INTO foo (%s) VALUES (%s)", columns, arguments)
    36  //	// INSERT INTO foo (foo, bar) VALUES (:foo, :bar)
    37  func NamedInsertArguments(t interface{}, exclude ...string) (columns string, arguments string) {
    38  	keys := keys(t, exclude)
    39  	return strings.Join(keys, ", "),
    40  		":" + strings.Join(keys, ", :")
    41  }
    42  
    43  // NamedUpdateArguments returns columns and arguments for SQL UPDATE statements based on a struct's tags. Does
    44  // not work with nested structs or maps!
    45  //
    46  // 	type st struct {
    47  // 		Foo string `db:"foo"`
    48  // 		Bar string `db:"bar,omitempty"`
    49  // 		Baz string `db:"-"`
    50  // 		Zab string
    51  // 	}
    52  //	query := fmt.Sprintf("UPDATE foo SET %s", NamedUpdateArguments(new(st)))
    53  //	// UPDATE foo SET foo=:foo, bar=:bar
    54  func NamedUpdateArguments(t interface{}, exclude ...string) string {
    55  	keys := keys(t, exclude)
    56  	statements := make([]string, len(keys))
    57  
    58  	for k, key := range keys {
    59  		statements[k] = fmt.Sprintf("%s=:%s", key, key)
    60  	}
    61  
    62  	return strings.Join(statements, ", ")
    63  }
    64  

View as plain text