gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

sqlfmt.go (2062B)


      1 package schema
      2 
      3 import (
      4 	"strings"
      5 
      6 	"github.com/uptrace/bun/internal"
      7 )
      8 
      9 type QueryAppender interface {
     10 	AppendQuery(fmter Formatter, b []byte) ([]byte, error)
     11 }
     12 
     13 type ColumnsAppender interface {
     14 	AppendColumns(fmter Formatter, b []byte) ([]byte, error)
     15 }
     16 
     17 //------------------------------------------------------------------------------
     18 
     19 // Safe represents a safe SQL query.
     20 type Safe string
     21 
     22 var _ QueryAppender = (*Safe)(nil)
     23 
     24 func (s Safe) AppendQuery(fmter Formatter, b []byte) ([]byte, error) {
     25 	return append(b, s...), nil
     26 }
     27 
     28 //------------------------------------------------------------------------------
     29 
     30 // Ident represents a SQL identifier, for example, table or column name.
     31 type Ident string
     32 
     33 var _ QueryAppender = (*Ident)(nil)
     34 
     35 func (s Ident) AppendQuery(fmter Formatter, b []byte) ([]byte, error) {
     36 	return fmter.AppendIdent(b, string(s)), nil
     37 }
     38 
     39 //------------------------------------------------------------------------------
     40 
     41 type QueryWithArgs struct {
     42 	Query string
     43 	Args  []interface{}
     44 }
     45 
     46 var _ QueryAppender = QueryWithArgs{}
     47 
     48 func SafeQuery(query string, args []interface{}) QueryWithArgs {
     49 	if args == nil {
     50 		args = make([]interface{}, 0)
     51 	} else if len(query) > 0 && strings.IndexByte(query, '?') == -1 {
     52 		internal.Warn.Printf("query %q has %v args, but no placeholders", query, args)
     53 	}
     54 	return QueryWithArgs{
     55 		Query: query,
     56 		Args:  args,
     57 	}
     58 }
     59 
     60 func UnsafeIdent(ident string) QueryWithArgs {
     61 	return QueryWithArgs{Query: ident}
     62 }
     63 
     64 func (q QueryWithArgs) IsZero() bool {
     65 	return q.Query == "" && q.Args == nil
     66 }
     67 
     68 func (q QueryWithArgs) AppendQuery(fmter Formatter, b []byte) ([]byte, error) {
     69 	if q.Args == nil {
     70 		return fmter.AppendIdent(b, q.Query), nil
     71 	}
     72 	return fmter.AppendQuery(b, q.Query, q.Args...), nil
     73 }
     74 
     75 //------------------------------------------------------------------------------
     76 
     77 type QueryWithSep struct {
     78 	QueryWithArgs
     79 	Sep string
     80 }
     81 
     82 func SafeQueryWithSep(query string, args []interface{}, sep string) QueryWithSep {
     83 	return QueryWithSep{
     84 		QueryWithArgs: SafeQuery(query, args),
     85 		Sep:           sep,
     86 	}
     87 }