github.com/wfusion/gofusion@v1.1.14/common/utils/sqlparser/ast.go (about)

     1  package sqlparser
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"strings"
     7  )
     8  
     9  type Node interface {
    10  	node()
    11  	fmt.Stringer
    12  }
    13  
    14  func (*Assignment) node()      {}
    15  func (*BinaryExpr) node()      {}
    16  func (*BindExpr) node()        {}
    17  func (*BlobLit) node()         {}
    18  func (*BoolLit) node()         {}
    19  func (*Call) node()            {}
    20  func (*CaseBlock) node()       {}
    21  func (*CaseExpr) node()        {}
    22  func (*DeleteStatement) node() {}
    23  func (*Exists) node()          {}
    24  func (*Exprs) node()           {}
    25  func (*FilterClause) node()    {}
    26  func (*Hint) node()            {}
    27  func (*Ident) node()           {}
    28  func (*IndexedColumn) node()   {}
    29  func (*InsertStatement) node() {}
    30  func (*JoinClause) node()      {}
    31  func (*JoinOperator) node()    {}
    32  func (*NullLit) node()         {}
    33  func (*NumberLit) node()       {}
    34  func (*OnConstraint) node()    {}
    35  func (*OrderingTerm) node()    {}
    36  func (*ParenExpr) node()       {}
    37  func (*ParenSource) node()     {}
    38  func (*QualifiedRef) node()    {}
    39  func (*Range) node()           {}
    40  func (*OutputNames) node()     {}
    41  func (*ResultColumn) node()    {}
    42  func (*SelectStatement) node() {}
    43  func (*StringLit) node()       {}
    44  func (*TableName) node()       {}
    45  func (*Type) node()            {}
    46  func (*UnaryExpr) node()       {}
    47  func (*UpdateStatement) node() {}
    48  func (*UpsertClause) node()    {}
    49  func (*UsingConstraint) node() {}
    50  
    51  type Statement interface {
    52  	Node
    53  	stmt()
    54  }
    55  
    56  func (*DeleteStatement) stmt() {}
    57  func (*InsertStatement) stmt() {}
    58  func (*SelectStatement) stmt() {}
    59  func (*UpdateStatement) stmt() {}
    60  
    61  // StatementSource returns the root statement for a statement.
    62  func StatementSource(stmt Statement) Source {
    63  	switch stmt := stmt.(type) {
    64  	case *SelectStatement:
    65  		return stmt.FromItems
    66  	case *UpdateStatement:
    67  		return stmt.TableName
    68  	case *DeleteStatement:
    69  		return stmt.TableName
    70  	default:
    71  		return nil
    72  	}
    73  }
    74  
    75  type Expr interface {
    76  	Node
    77  	expr()
    78  }
    79  
    80  func (*BinaryExpr) expr()   {}
    81  func (*BindExpr) expr()     {}
    82  func (*BlobLit) expr()      {}
    83  func (*BoolLit) expr()      {}
    84  func (*Call) expr()         {}
    85  func (*CaseExpr) expr()     {}
    86  func (*Exists) expr()       {}
    87  func (*Exprs) expr()        {}
    88  func (*Ident) expr()        {}
    89  func (*NullLit) expr()      {}
    90  func (*NumberLit) expr()    {}
    91  func (*ParenExpr) expr()    {}
    92  func (*QualifiedRef) expr() {}
    93  func (*Range) expr()        {}
    94  func (*StringLit) expr()    {}
    95  func (*UnaryExpr) expr()    {}
    96  
    97  // ExprString returns the string representation of expr.
    98  // Returns a blank string if expr is nil.
    99  func ExprString(expr Expr) string {
   100  	if expr == nil {
   101  		return ""
   102  	}
   103  	return expr.String()
   104  }
   105  
   106  // SplitExprTree splits apart expr so it is a list of all AND joined expressions.
   107  // For example, the expression "A AND B AND (C OR (D AND E))" would be split into
   108  // a list of "A", "B", "C OR (D AND E)".
   109  func SplitExprTree(expr Expr) []Expr {
   110  	if expr == nil {
   111  		return nil
   112  	}
   113  
   114  	var a []Expr
   115  	splitExprTree(expr, &a)
   116  	return a
   117  }
   118  
   119  func splitExprTree(expr Expr, a *[]Expr) {
   120  	switch expr := expr.(type) {
   121  	case *BinaryExpr:
   122  		if expr.Op != AND {
   123  			*a = append(*a, expr)
   124  			return
   125  		}
   126  		splitExprTree(expr.X, a)
   127  		splitExprTree(expr.Y, a)
   128  	case *ParenExpr:
   129  		splitExprTree(expr.X, a)
   130  	default:
   131  		*a = append(*a, expr)
   132  	}
   133  }
   134  
   135  // Scope represents a context for name resolution.
   136  // Names can be resolved at the current source or in parent scopes.
   137  type Scope struct {
   138  	Parent *Scope
   139  	Source Source
   140  }
   141  
   142  // Source represents a table or subquery.
   143  type Source interface {
   144  	Node
   145  	source()
   146  }
   147  
   148  func (*JoinClause) source()      {}
   149  func (*ParenSource) source()     {}
   150  func (*TableName) source()       {}
   151  func (*SelectStatement) source() {}
   152  
   153  // SourceName returns the name of the source.
   154  // Only returns for TableName & ParenSource.
   155  func SourceName(src Source) string {
   156  	switch src := src.(type) {
   157  	case *JoinClause, *SelectStatement:
   158  		return ""
   159  	case *ParenSource:
   160  		return IdentName(src.Alias)
   161  	case *TableName:
   162  		return src.TableName()
   163  	default:
   164  		return ""
   165  	}
   166  }
   167  
   168  // SourceList returns a list of scopes in the current scope.
   169  func SourceList(src Source) []Source {
   170  	var a []Source
   171  	ForEachSource(src, func(s Source) bool {
   172  		a = append(a, s)
   173  		return true
   174  	})
   175  	return a
   176  }
   177  
   178  // ForEachSource calls fn for every source within the current scope.
   179  // Stops iteration if fn returns false.
   180  func ForEachSource(src Source, fn func(Source) bool) {
   181  	forEachSource(src, fn)
   182  }
   183  
   184  func forEachSource(src Source, fn func(Source) bool) bool {
   185  	if !fn(src) {
   186  		return false
   187  	}
   188  
   189  	switch src := src.(type) {
   190  	case *JoinClause:
   191  		if !forEachSource(src.X, fn) {
   192  			return false
   193  		} else if !forEachSource(src.Y, fn) {
   194  			return false
   195  		}
   196  	case *SelectStatement:
   197  		if !forEachSource(src.FromItems, fn) {
   198  			return false
   199  		}
   200  	}
   201  	return true
   202  }
   203  
   204  // ResolveSource returns a source with the given name.
   205  // This can either be the table name or the alias for a source.
   206  func ResolveSource(root Source, name string) Source {
   207  	var ret Source
   208  	ForEachSource(root, func(src Source) bool {
   209  		switch src := src.(type) {
   210  		case *ParenSource:
   211  			if IdentName(src.Alias) == name {
   212  				ret = src
   213  			}
   214  		case *TableName:
   215  			if src.TableName() == name {
   216  				ret = src
   217  			}
   218  		}
   219  		return ret == nil // continue until we find the matching source
   220  	})
   221  	return ret
   222  }
   223  
   224  // JoinConstraint represents either an ON or USING join constraint.
   225  type JoinConstraint interface {
   226  	Node
   227  	joinConstraint()
   228  }
   229  
   230  func (*OnConstraint) joinConstraint()    {}
   231  func (*UsingConstraint) joinConstraint() {}
   232  
   233  type Constraint interface {
   234  	Node
   235  	constraint()
   236  }
   237  
   238  type Ident struct {
   239  	Name      string // identifier name
   240  	Quoted    bool   // true if double quoted
   241  	QuoteChar string // " for postgresql, ` for mysql, etc
   242  }
   243  
   244  // String returns the string representation of the expression.
   245  func (i *Ident) String() string {
   246  	if i.Quoted {
   247  		if i.QuoteChar == `"` {
   248  			return i.QuoteChar + strings.ReplaceAll(i.Name, `"`, `""`) + i.QuoteChar
   249  		}
   250  		return i.QuoteChar + i.Name + i.QuoteChar
   251  	}
   252  	return i.Name
   253  }
   254  
   255  // IdentName returns the name of ident. Returns a blank string if ident is nil.
   256  func IdentName(ident *Ident) string {
   257  	if ident == nil {
   258  		return ""
   259  	}
   260  	return ident.Name
   261  }
   262  
   263  type Type struct {
   264  	Name      *Ident     // type name
   265  	Lparen    Pos        // position of left paren (optional)
   266  	Precision *NumberLit // precision (optional)
   267  	Scale     *NumberLit // scale (optional)
   268  	Rparen    Pos        // position of right paren (optional)
   269  }
   270  
   271  // String returns the string representation of the type.
   272  func (t *Type) String() string {
   273  	if t.Precision != nil && t.Scale != nil {
   274  		return fmt.Sprintf("%s(%s,%s)", t.Name.Name, t.Precision.String(), t.Scale.String())
   275  	} else if t.Precision != nil {
   276  		return fmt.Sprintf("%s(%s)", t.Name.Name, t.Precision.String())
   277  	}
   278  	return t.Name.Name
   279  }
   280  
   281  type StringLit struct {
   282  	Value string // literal value (without quotes)
   283  }
   284  
   285  // String returns the string representation of the expression.
   286  func (lit *StringLit) String() string {
   287  	return `'` + strings.Replace(lit.Value, `'`, `''`, -1) + `'`
   288  }
   289  
   290  type Hint struct {
   291  	Value string
   292  }
   293  
   294  // String returns the string representation of the expression.
   295  func (h *Hint) String() string {
   296  	return `/* ` + h.Value + ` */`
   297  }
   298  
   299  type BlobLit struct {
   300  	Value string // literal value
   301  }
   302  
   303  // String returns the string representation of the expression.
   304  func (lit *BlobLit) String() string {
   305  	return `x'` + lit.Value + `'`
   306  }
   307  
   308  type NumberLit struct {
   309  	Value string // literal value
   310  }
   311  
   312  // String returns the string representation of the expression.
   313  func (lit *NumberLit) String() string {
   314  	return lit.Value
   315  }
   316  
   317  type NullLit struct {
   318  }
   319  
   320  // String returns the string representation of the expression.
   321  func (lit *NullLit) String() string {
   322  	return "NULL"
   323  }
   324  
   325  type BoolLit struct {
   326  	Value bool // literal value
   327  }
   328  
   329  // String returns the string representation of the expression.
   330  func (lit *BoolLit) String() string {
   331  	if lit.Value {
   332  		return "TRUE"
   333  	}
   334  	return "FALSE"
   335  }
   336  
   337  type BindExpr struct {
   338  	Name string // binding name
   339  	Pos  int    // binding position
   340  }
   341  
   342  // String returns the string representation of the expression.
   343  func (expr *BindExpr) String() string {
   344  	// TODO(BBJ): Support all bind characters.
   345  	return expr.Name
   346  }
   347  
   348  type UnaryExpr struct {
   349  	Op Token // operation
   350  	X  Expr  // target expression
   351  }
   352  
   353  // String returns the string representation of the expression.
   354  func (expr *UnaryExpr) String() string {
   355  	switch expr.Op {
   356  	case PLUS:
   357  		return "+" + expr.X.String()
   358  	case MINUS:
   359  		return "-" + expr.X.String()
   360  	default:
   361  		panic(fmt.Sprintf("sqlparser.UnaryExpr.String(): invalid op %s", expr.Op))
   362  	}
   363  }
   364  
   365  type BinaryExpr struct {
   366  	X  Expr  // lhs
   367  	Op Token // operator
   368  	Y  Expr  // rhs
   369  }
   370  
   371  // String returns the string representation of the expression.
   372  func (expr *BinaryExpr) String() string {
   373  	switch expr.Op {
   374  	case PLUS:
   375  		return expr.X.String() + " + " + expr.Y.String()
   376  	case MINUS:
   377  		return expr.X.String() + " - " + expr.Y.String()
   378  	case STAR:
   379  		return expr.X.String() + " * " + expr.Y.String()
   380  	case SLASH:
   381  		return expr.X.String() + " / " + expr.Y.String()
   382  	case REM:
   383  		return expr.X.String() + " % " + expr.Y.String()
   384  	case CONCAT:
   385  		return expr.X.String() + " || " + expr.Y.String()
   386  	case BETWEEN:
   387  		return expr.X.String() + " BETWEEN " + expr.Y.String()
   388  	case NOTBETWEEN:
   389  		return expr.X.String() + " NOT BETWEEN " + expr.Y.String()
   390  	case LSHIFT:
   391  		return expr.X.String() + " << " + expr.Y.String()
   392  	case RSHIFT:
   393  		return expr.X.String() + " >> " + expr.Y.String()
   394  	case BITAND:
   395  		return expr.X.String() + " & " + expr.Y.String()
   396  	case BITOR:
   397  		return expr.X.String() + " | " + expr.Y.String()
   398  	case LT:
   399  		return expr.X.String() + " < " + expr.Y.String()
   400  	case LG:
   401  		return expr.X.String() + " <> " + expr.Y.String()
   402  	case LE:
   403  		return expr.X.String() + " <= " + expr.Y.String()
   404  	case GT:
   405  		return expr.X.String() + " > " + expr.Y.String()
   406  	case GE:
   407  		return expr.X.String() + " >= " + expr.Y.String()
   408  	case EQ:
   409  		return expr.X.String() + " = " + expr.Y.String()
   410  	case NE:
   411  		return expr.X.String() + " != " + expr.Y.String()
   412  	case IS:
   413  		return expr.X.String() + " IS " + expr.Y.String()
   414  	case ISNOT:
   415  		return expr.X.String() + " IS NOT " + expr.Y.String()
   416  	case IN:
   417  		return expr.X.String() + " IN " + expr.Y.String()
   418  	case NOTIN:
   419  		return expr.X.String() + " NOT IN " + expr.Y.String()
   420  	case LIKE:
   421  		return expr.X.String() + " LIKE " + expr.Y.String()
   422  	case NOTLIKE:
   423  		return expr.X.String() + " NOT LIKE " + expr.Y.String()
   424  	case GLOB:
   425  		return expr.X.String() + " GLOB " + expr.Y.String()
   426  	case NOTGLOB:
   427  		return expr.X.String() + " NOT GLOB " + expr.Y.String()
   428  	case MATCH:
   429  		return expr.X.String() + " MATCH " + expr.Y.String()
   430  	case NOTMATCH:
   431  		return expr.X.String() + " NOT MATCH " + expr.Y.String()
   432  	case REGEXP:
   433  		return expr.X.String() + " REGEXP " + expr.Y.String()
   434  	case NOTREGEXP:
   435  		return expr.X.String() + " NOT REGEXP " + expr.Y.String()
   436  	case AND:
   437  		return expr.X.String() + " AND " + expr.Y.String()
   438  	case OR:
   439  		return expr.X.String() + " OR " + expr.Y.String()
   440  	default:
   441  		panic(fmt.Sprintf("sqlparser.BinaryExpr.String(): invalid op %s", expr.Op))
   442  	}
   443  }
   444  
   445  type CaseExpr struct {
   446  	Operand  Expr         // optional condition after the CASE keyword
   447  	Blocks   []*CaseBlock // list of WHEN/THEN pairs
   448  	ElseExpr Expr         // expression used by default case
   449  }
   450  
   451  // String returns the string representation of the expression.
   452  func (expr *CaseExpr) String() string {
   453  	var buf bytes.Buffer
   454  	buf.WriteString("CASE")
   455  	if expr.Operand != nil {
   456  		buf.WriteString(" ")
   457  		buf.WriteString(expr.Operand.String())
   458  	}
   459  	for _, blk := range expr.Blocks {
   460  		buf.WriteString(" ")
   461  		buf.WriteString(blk.String())
   462  	}
   463  	if expr.ElseExpr != nil {
   464  		buf.WriteString(" ELSE ")
   465  		buf.WriteString(expr.ElseExpr.String())
   466  	}
   467  	buf.WriteString(" END")
   468  	return buf.String()
   469  }
   470  
   471  type CaseBlock struct {
   472  	Condition Expr // block condition
   473  	Body      Expr // result expression
   474  }
   475  
   476  // String returns the string representation of the block.
   477  func (b *CaseBlock) String() string {
   478  	return fmt.Sprintf("WHEN %s THEN %s", b.Condition.String(), b.Body.String())
   479  }
   480  
   481  type Exists struct {
   482  	Not    bool
   483  	Select *SelectStatement // select statement
   484  }
   485  
   486  // String returns the string representation of the expression.
   487  func (expr *Exists) String() string {
   488  	if expr.Not {
   489  		return fmt.Sprintf("NOT EXISTS (%s)", expr.Select.String())
   490  	}
   491  	return fmt.Sprintf("EXISTS (%s)", expr.Select.String())
   492  }
   493  
   494  type Exprs struct {
   495  	Exprs []Expr // list of expressions
   496  }
   497  
   498  // String returns the string representation of the expression.
   499  func (l *Exprs) String() string {
   500  	var buf bytes.Buffer
   501  	buf.WriteString("(")
   502  	for i, expr := range l.Exprs {
   503  		if i != 0 {
   504  			buf.WriteString(", ")
   505  		}
   506  		buf.WriteString(expr.String())
   507  	}
   508  	buf.WriteString(")")
   509  	return buf.String()
   510  }
   511  
   512  type Range struct {
   513  	X Expr // lhs expression
   514  	Y Expr // rhs expression
   515  }
   516  
   517  // String returns the string representation of the expression.
   518  func (r *Range) String() string {
   519  	return fmt.Sprintf("%s AND %s", r.X.String(), r.Y.String())
   520  }
   521  
   522  type QualifiedRef struct {
   523  	Table  *Ident // table name
   524  	Star   bool
   525  	Column *Ident // column name
   526  }
   527  
   528  // String returns the string representation of the expression.
   529  func (r *QualifiedRef) String() string {
   530  	if r.Star {
   531  		return fmt.Sprintf("%s.*", r.Table.String())
   532  	}
   533  	return fmt.Sprintf("%s.%s", r.Table.String(), r.Column.String())
   534  }
   535  
   536  type Call struct {
   537  	Name     *Ident // function name
   538  	Star     bool
   539  	Distinct bool
   540  	Args     []Expr        // argument list
   541  	Filter   *FilterClause // filter clause
   542  }
   543  
   544  // String returns the string representation of the expression.
   545  func (c *Call) String() string {
   546  	var buf bytes.Buffer
   547  	buf.WriteString(c.Name.Name)
   548  	buf.WriteString("(")
   549  	if c.Star {
   550  		buf.WriteString("*")
   551  	} else {
   552  		if c.Distinct {
   553  			buf.WriteString("DISTINCT")
   554  			if len(c.Args) != 0 {
   555  				buf.WriteString(" ")
   556  			}
   557  		}
   558  		for i, arg := range c.Args {
   559  			if i != 0 {
   560  				buf.WriteString(", ")
   561  			}
   562  			buf.WriteString(arg.String())
   563  		}
   564  	}
   565  	buf.WriteString(")")
   566  
   567  	if c.Filter != nil {
   568  		buf.WriteString(" ")
   569  		buf.WriteString(c.Filter.String())
   570  	}
   571  
   572  	return buf.String()
   573  }
   574  
   575  type FilterClause struct {
   576  	X Expr // filter expression
   577  }
   578  
   579  // String returns the string representation of the clause.
   580  func (c *FilterClause) String() string {
   581  	return fmt.Sprintf("FILTER (WHERE %s)", c.X.String())
   582  }
   583  
   584  type OrderingTerm struct {
   585  	X Expr // ordering expression
   586  
   587  	Asc  bool
   588  	Desc bool
   589  
   590  	NullsFirst bool
   591  	NullsLast  bool
   592  }
   593  
   594  // String returns the string representation of the term.
   595  func (t *OrderingTerm) String() string {
   596  	var buf bytes.Buffer
   597  	buf.WriteString(t.X.String())
   598  
   599  	if t.Asc {
   600  		buf.WriteString(" ASC")
   601  	} else if t.Desc {
   602  		buf.WriteString(" DESC")
   603  	}
   604  
   605  	if t.NullsFirst {
   606  		buf.WriteString(" NULLS FIRST")
   607  	} else if t.NullsLast {
   608  		buf.WriteString(" NULLS LAST")
   609  	}
   610  
   611  	return buf.String()
   612  }
   613  
   614  type ColumnArg interface {
   615  	Node
   616  	columnArg()
   617  }
   618  
   619  // InsertStatement see http://www.postgres.cn/docs/12/sql-insert.html
   620  type InsertStatement struct {
   621  	TableName *TableName
   622  
   623  	ColumnNames []*Ident
   624  	Overriding  string
   625  
   626  	DefaultValues bool
   627  	Expressions   []*Exprs
   628  	Query         *SelectStatement
   629  
   630  	UpsertClause *UpsertClause
   631  
   632  	OutputExpressions *OutputNames
   633  }
   634  
   635  // String returns the string representation of the statement.
   636  func (s *InsertStatement) String() string {
   637  	var buf bytes.Buffer
   638  
   639  	buf.WriteString("INSERT")
   640  
   641  	fmt.Fprintf(&buf, " INTO %s", s.TableName.String())
   642  
   643  	if len(s.ColumnNames) != 0 {
   644  		buf.WriteString(" (")
   645  		for i, col := range s.ColumnNames {
   646  			if i != 0 {
   647  				buf.WriteString(", ")
   648  			}
   649  			buf.WriteString(col.String())
   650  		}
   651  		buf.WriteString(")")
   652  	}
   653  
   654  	if s.DefaultValues {
   655  		buf.WriteString(" DEFAULT VALUES")
   656  	} else if s.Query != nil {
   657  		fmt.Fprintf(&buf, " %s", s.Query.String())
   658  	} else {
   659  		buf.WriteString(" VALUES")
   660  		for i := range s.Expressions {
   661  			if i != 0 {
   662  				buf.WriteString(",")
   663  			}
   664  			buf.WriteString(" (")
   665  			for j, expr := range s.Expressions[i].Exprs {
   666  				if j != 0 {
   667  					buf.WriteString(", ")
   668  				}
   669  				buf.WriteString(expr.String())
   670  			}
   671  			buf.WriteString(")")
   672  		}
   673  	}
   674  
   675  	if s.UpsertClause != nil {
   676  		fmt.Fprintf(&buf, " %s", s.UpsertClause.String())
   677  	}
   678  
   679  	if s.OutputExpressions != nil {
   680  		fmt.Fprintf(&buf, " RETURNING %s", s.OutputExpressions.String())
   681  	}
   682  
   683  	return buf.String()
   684  }
   685  
   686  type UpsertClause struct {
   687  	Columns   []*IndexedColumn // optional indexed column list
   688  	WhereExpr Expr             // optional conditional expression
   689  
   690  	DoNothing       bool          // position of NOTHING keyword after DO
   691  	DoUpdate        bool          // position of UPDATE keyword after DO
   692  	Assignments     []*Assignment // list of column assignments
   693  	UpdateWhereExpr Expr          // optional conditional expression for DO UPDATE SET
   694  }
   695  
   696  // String returns the string representation of the clause.
   697  func (c *UpsertClause) String() string {
   698  	var buf bytes.Buffer
   699  	buf.WriteString("ON CONFLICT")
   700  
   701  	if len(c.Columns) != 0 {
   702  		buf.WriteString(" (")
   703  		for i, col := range c.Columns {
   704  			if i != 0 {
   705  				buf.WriteString(", ")
   706  			}
   707  			buf.WriteString(col.String())
   708  		}
   709  		buf.WriteString(")")
   710  
   711  		if c.WhereExpr != nil {
   712  			fmt.Fprintf(&buf, " WHERE %s", c.WhereExpr.String())
   713  		}
   714  	}
   715  
   716  	buf.WriteString(" DO")
   717  	if c.DoNothing {
   718  		buf.WriteString(" NOTHING")
   719  	} else {
   720  		buf.WriteString(" UPDATE SET ")
   721  		for i := range c.Assignments {
   722  			if i != 0 {
   723  				buf.WriteString(", ")
   724  			}
   725  			buf.WriteString(c.Assignments[i].String())
   726  		}
   727  
   728  		if c.UpdateWhereExpr != nil {
   729  			fmt.Fprintf(&buf, " WHERE %s", c.UpdateWhereExpr.String())
   730  		}
   731  	}
   732  
   733  	return buf.String()
   734  }
   735  
   736  // UpdateStatement see http://www.postgres.cn/docs/12/sql-update.html
   737  type UpdateStatement struct {
   738  	Only      bool
   739  	TableName *TableName
   740  	TableStar bool
   741  	Alias     *Ident
   742  
   743  	Assignments []*Assignment
   744  
   745  	FromList []*TableName
   746  
   747  	Condition  Expr
   748  	CursorName *Ident
   749  
   750  	OutputExpressions *OutputNames
   751  }
   752  
   753  // String returns the string representation of the clause.
   754  func (s *UpdateStatement) String() string {
   755  	var buf bytes.Buffer
   756  
   757  	buf.WriteString("UPDATE ")
   758  	if s.Only {
   759  		buf.WriteString("ONLY ")
   760  	}
   761  	fmt.Fprintf(&buf, "%s", s.TableName.String())
   762  	if s.TableStar {
   763  		buf.WriteString(" *")
   764  	}
   765  	if s.Alias != nil {
   766  		fmt.Fprintf(&buf, " AS %s", s.Alias.String())
   767  	}
   768  
   769  	buf.WriteString(" SET ")
   770  	for i := range s.Assignments {
   771  		if i != 0 {
   772  			buf.WriteString(", ")
   773  		}
   774  		buf.WriteString(s.Assignments[i].String())
   775  	}
   776  
   777  	if len(s.FromList) > 0 {
   778  		buf.WriteString(" From ")
   779  		for i, name := range s.FromList {
   780  			if i > 0 {
   781  				buf.WriteString(", ")
   782  			}
   783  			buf.WriteString(name.String())
   784  		}
   785  	}
   786  
   787  	if s.Condition != nil {
   788  		fmt.Fprintf(&buf, " WHERE %s", s.Condition.String())
   789  	} else if s.CursorName != nil {
   790  		fmt.Fprintf(&buf, " WHERE CURRENT OF %s", s.CursorName.String())
   791  	}
   792  
   793  	if s.OutputExpressions != nil {
   794  		fmt.Fprintf(&buf, " RETURNING %s", s.OutputExpressions.String())
   795  	}
   796  
   797  	return buf.String()
   798  }
   799  
   800  // DeleteStatement see http://www.postgres.cn/docs/12/sql-delete.html
   801  type DeleteStatement struct {
   802  	Only      bool
   803  	TableName *TableName
   804  	TableStar bool
   805  	Alias     *Ident
   806  
   807  	UsingList []*TableName
   808  
   809  	Condition  Expr
   810  	CursorName *Ident
   811  
   812  	OutputExpressions *OutputNames
   813  }
   814  
   815  // String returns the string representation of the clause.
   816  func (s *DeleteStatement) String() string {
   817  	var buf bytes.Buffer
   818  
   819  	buf.WriteString("DELETE FROM ")
   820  	if s.Only {
   821  		buf.WriteString("ONLY ")
   822  	}
   823  	fmt.Fprintf(&buf, "%s", s.TableName.String())
   824  	if s.TableStar {
   825  		buf.WriteString(" *")
   826  	}
   827  	if s.Alias != nil {
   828  		fmt.Fprintf(&buf, " AS %s", s.Alias.String())
   829  	}
   830  
   831  	if len(s.UsingList) > 0 {
   832  		buf.WriteString(" USING ")
   833  		for i, name := range s.UsingList {
   834  			if i > 0 {
   835  				buf.WriteString(", ")
   836  			}
   837  			buf.WriteString(name.String())
   838  		}
   839  	}
   840  
   841  	if s.Condition != nil {
   842  		fmt.Fprintf(&buf, " WHERE %s", s.Condition.String())
   843  	} else if s.CursorName != nil {
   844  		fmt.Fprintf(&buf, " WHERE CURRENT OF %s", s.CursorName.String())
   845  	}
   846  
   847  	if s.OutputExpressions != nil {
   848  		fmt.Fprintf(&buf, " RETURNING %s", s.OutputExpressions.String())
   849  	}
   850  
   851  	return buf.String()
   852  }
   853  
   854  // Assignment is used within the UPDATE statement & upsert clause.
   855  // It is similiar to an expression except that it must be an equality.
   856  type Assignment struct {
   857  	Columns []*Ident // column list
   858  	Expr    Expr     // assigned expression
   859  }
   860  
   861  // String returns the string representation of the clause.
   862  func (a *Assignment) String() string {
   863  	var buf bytes.Buffer
   864  	if len(a.Columns) == 1 {
   865  		buf.WriteString(a.Columns[0].String())
   866  	} else if len(a.Columns) > 1 {
   867  		buf.WriteString("(")
   868  		for i, col := range a.Columns {
   869  			if i != 0 {
   870  				buf.WriteString(", ")
   871  			}
   872  			buf.WriteString(col.String())
   873  		}
   874  		buf.WriteString(")")
   875  	}
   876  
   877  	fmt.Fprintf(&buf, " = %s", a.Expr.String())
   878  	return buf.String()
   879  }
   880  
   881  type IndexedColumn struct {
   882  	X    Expr // column expression
   883  	Asc  bool
   884  	Desc bool
   885  }
   886  
   887  // String returns the string representation of the column.
   888  func (c *IndexedColumn) String() string {
   889  	if c.Asc {
   890  		return fmt.Sprintf("%s ASC", c.X.String())
   891  	} else if c.Desc {
   892  		return fmt.Sprintf("%s DESC", c.X.String())
   893  	}
   894  	return c.X.String()
   895  }
   896  
   897  // SelectStatement see http://www.postgres.cn/docs/12/sql-select.html
   898  type SelectStatement struct {
   899  	All      bool
   900  	Distinct bool
   901  	Columns  *OutputNames // list of result columns in the SELECT clause
   902  
   903  	FromItems Source
   904  
   905  	Condition Expr
   906  
   907  	GroupingElements []Expr
   908  	HavingCondition  Expr
   909  
   910  	Union     bool
   911  	UnionAll  bool
   912  	Intersect bool
   913  	Except    bool
   914  	Compound  *SelectStatement // compounded SELECT statement
   915  
   916  	OrderBy []*OrderingTerm // terms of ORDER BY clause
   917  
   918  	Limit  Expr
   919  	Fetch  Expr
   920  	Offset Expr // offset expression
   921  
   922  	Hint *Hint
   923  }
   924  
   925  // String returns the string representation of the statement.
   926  func (s *SelectStatement) String() string {
   927  	var buf bytes.Buffer
   928  
   929  	buf.WriteString("SELECT ")
   930  	if s.Hint != nil {
   931  		fmt.Fprintf(&buf, "%s ", s.Hint.String())
   932  	}
   933  
   934  	if s.All {
   935  		buf.WriteString("ALL ")
   936  	} else if s.Distinct {
   937  		buf.WriteString("DISTINCT ")
   938  	}
   939  
   940  	buf.WriteString(s.Columns.String())
   941  
   942  	if s.FromItems != nil {
   943  		fmt.Fprintf(&buf, " FROM %s", s.FromItems.String())
   944  	}
   945  
   946  	if s.Condition != nil {
   947  		fmt.Fprintf(&buf, " WHERE %s", s.Condition.String())
   948  	}
   949  
   950  	if len(s.GroupingElements) != 0 {
   951  		buf.WriteString(" GROUP BY ")
   952  		for i, expr := range s.GroupingElements {
   953  			if i != 0 {
   954  				buf.WriteString(", ")
   955  			}
   956  			buf.WriteString(expr.String())
   957  		}
   958  
   959  		if s.HavingCondition != nil {
   960  			fmt.Fprintf(&buf, " HAVING %s", s.HavingCondition.String())
   961  		}
   962  	}
   963  
   964  	// Write compound operator.
   965  	if s.Compound != nil {
   966  		switch {
   967  		case s.Union:
   968  			buf.WriteString(" UNION")
   969  			if s.UnionAll {
   970  				buf.WriteString(" ALL")
   971  			}
   972  		case s.Intersect:
   973  			buf.WriteString(" INTERSECT")
   974  		case s.Except:
   975  			buf.WriteString(" EXCEPT")
   976  		}
   977  
   978  		fmt.Fprintf(&buf, " %s", s.Compound.String())
   979  	}
   980  
   981  	if len(s.OrderBy) != 0 {
   982  		buf.WriteString(" ORDER BY ")
   983  		for i, term := range s.OrderBy {
   984  			if i != 0 {
   985  				buf.WriteString(", ")
   986  			}
   987  			buf.WriteString(term.String())
   988  		}
   989  	}
   990  
   991  	if s.Limit != nil {
   992  		fmt.Fprintf(&buf, " LIMIT %s", s.Limit.String())
   993  		if s.Offset != nil {
   994  			fmt.Fprintf(&buf, " OFFSET %s", s.Offset.String())
   995  		}
   996  	}
   997  	if s.Limit == nil && s.Offset != nil {
   998  		fmt.Fprintf(&buf, " OFFSET %s ROWS", s.Offset.String())
   999  		if s.Fetch != nil {
  1000  			fmt.Fprintf(&buf, " FETCH NEXT %s ROWS ONLY", s.Fetch.String())
  1001  		}
  1002  	}
  1003  
  1004  	return buf.String()
  1005  }
  1006  
  1007  type OutputNames []*ResultColumn
  1008  
  1009  func (on OutputNames) String() string {
  1010  	var buf bytes.Buffer
  1011  	for i, name := range on {
  1012  		if i != 0 {
  1013  			buf.WriteString(", ")
  1014  		}
  1015  		buf.WriteString(name.String())
  1016  	}
  1017  
  1018  	return buf.String()
  1019  }
  1020  
  1021  type ResultColumn struct {
  1022  	Star  bool
  1023  	Expr  Expr   // column expression (may be "tbl.*")
  1024  	Alias *Ident // alias name
  1025  }
  1026  
  1027  // String returns the string representation of the column.
  1028  func (c *ResultColumn) String() string {
  1029  	if c.Star {
  1030  		return "*"
  1031  	} else if c.Alias != nil {
  1032  		return fmt.Sprintf("%s AS %s", c.Expr.String(), c.Alias.String())
  1033  	}
  1034  	return c.Expr.String()
  1035  }
  1036  
  1037  type TableName struct {
  1038  	Name  *Ident // table name
  1039  	Alias *Ident // optional table alias
  1040  }
  1041  
  1042  // TableName returns the name used to identify n.
  1043  // Returns the alias, if one is specified. Otherwise returns the name.
  1044  func (n *TableName) TableName() string {
  1045  	if s := IdentName(n.Alias); s != "" {
  1046  		return s
  1047  	}
  1048  	return IdentName(n.Name)
  1049  }
  1050  
  1051  // String returns the string representation of the table name.
  1052  func (n *TableName) String() string {
  1053  	var buf bytes.Buffer
  1054  	buf.WriteString(n.Name.String())
  1055  	if n.Alias != nil {
  1056  		fmt.Fprintf(&buf, " AS %s", n.Alias.String())
  1057  	}
  1058  	return buf.String()
  1059  }
  1060  
  1061  type ParenSource struct {
  1062  	X     Source // nested source
  1063  	Alias *Ident // optional table alias (select source only)
  1064  }
  1065  
  1066  // String returns the string representation of the source.
  1067  func (s *ParenSource) String() string {
  1068  	if s.Alias != nil {
  1069  		return fmt.Sprintf("(%s) AS %s", s.X.String(), s.Alias.String())
  1070  	}
  1071  	return fmt.Sprintf("(%s)", s.X.String())
  1072  }
  1073  
  1074  type JoinClause struct {
  1075  	X          Source         // lhs source
  1076  	Operator   *JoinOperator  // join operator
  1077  	Y          Source         // rhs source
  1078  	Constraint JoinConstraint // join constraint
  1079  }
  1080  
  1081  // String returns the string representation of the clause.
  1082  func (c *JoinClause) String() string {
  1083  	var buf bytes.Buffer
  1084  	fmt.Fprintf(&buf, "%s%s%s", c.X.String(), c.Operator.String(), c.Y.String())
  1085  	if c.Constraint != nil {
  1086  		fmt.Fprintf(&buf, " %s", c.Constraint.String())
  1087  	}
  1088  	return buf.String()
  1089  }
  1090  
  1091  type JoinOperator struct {
  1092  	Comma   bool
  1093  	Natural bool
  1094  	Left    bool
  1095  	Outer   bool
  1096  	Inner   bool
  1097  	Cross   bool
  1098  }
  1099  
  1100  // String returns the string representation of the operator.
  1101  func (op *JoinOperator) String() string {
  1102  	if op.Comma {
  1103  		return ", "
  1104  	}
  1105  
  1106  	var buf bytes.Buffer
  1107  	if op.Natural {
  1108  		buf.WriteString(" NATURAL")
  1109  	}
  1110  	if op.Left {
  1111  		buf.WriteString(" LEFT")
  1112  		if op.Outer {
  1113  			buf.WriteString(" OUTER")
  1114  		}
  1115  	} else if op.Inner {
  1116  		buf.WriteString(" INNER")
  1117  	} else if op.Cross {
  1118  		buf.WriteString(" CROSS")
  1119  	}
  1120  	buf.WriteString(" JOIN ")
  1121  
  1122  	return buf.String()
  1123  }
  1124  
  1125  type OnConstraint struct {
  1126  	X Expr // constraint expression
  1127  }
  1128  
  1129  // String returns the string representation of the constraint.
  1130  func (c *OnConstraint) String() string {
  1131  	return "ON " + c.X.String()
  1132  }
  1133  
  1134  type UsingConstraint struct {
  1135  	Columns []*Ident // column list
  1136  }
  1137  
  1138  // String returns the string representation of the constraint.
  1139  func (c *UsingConstraint) String() string {
  1140  	var buf bytes.Buffer
  1141  	buf.WriteString("USING (")
  1142  	for i, col := range c.Columns {
  1143  		if i != 0 {
  1144  			buf.WriteString(", ")
  1145  		}
  1146  		buf.WriteString(col.String())
  1147  	}
  1148  	buf.WriteString(")")
  1149  	return buf.String()
  1150  }
  1151  
  1152  type ParenExpr struct {
  1153  	X Expr // parenthesized expression
  1154  }
  1155  
  1156  // String returns the string representation of the expression.
  1157  func (expr *ParenExpr) String() string {
  1158  	return fmt.Sprintf("(%s)", expr.X.String())
  1159  }