github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/sqlx/builder/builder_addition_onconflict.go (about)

     1  package builder
     2  
     3  import "context"
     4  
     5  type onconflict struct {
     6  	cols        *Columns
     7  	doNothing   bool
     8  	assignments []*Assignment
     9  	AdditionType
    10  }
    11  
    12  func OnConflict(cols *Columns) *onconflict {
    13  	return &onconflict{AdditionType: AdditionOnConflict, cols: cols}
    14  }
    15  
    16  func (a onconflict) DoNothing() *onconflict { a.doNothing = true; return &a }
    17  
    18  func (a onconflict) DoUpdateSet(ass ...*Assignment) *onconflict {
    19  	a.assignments = ass
    20  	return &a
    21  }
    22  
    23  func (a *onconflict) IsNil() bool {
    24  	return a == nil || IsNilExpr(a.cols) || (!a.doNothing && len(a.assignments) == 0)
    25  }
    26  
    27  func (a *onconflict) Ex(ctx context.Context) *Ex {
    28  	e := Expr("ON CONFLICT ")
    29  	e.WriteGroup(func(e *Ex) {
    30  		e.WriteExpr(a.cols)
    31  	})
    32  	e.WriteQuery(" DO ")
    33  
    34  	if a.doNothing {
    35  		e.WriteQuery("NOTHING")
    36  	} else {
    37  		e.WriteQuery("UPDATE SET ")
    38  		for i := range a.assignments {
    39  			if i > 0 {
    40  				e.WriteQuery(", ")
    41  			}
    42  			e.WriteExpr(a.assignments[i])
    43  		}
    44  	}
    45  	return e.Ex(ctx)
    46  }