github.com/octohelm/storage@v0.0.0-20240516030302-1ac2cc1ea347/pkg/sqlbuilder/addition_on_conflict.go (about)

     1  package sqlbuilder
     2  
     3  import (
     4  	"context"
     5  )
     6  
     7  type OnConflictAddition interface {
     8  	Addition
     9  	DoNothing() OnConflictAddition
    10  	DoUpdateSet(assignments ...Assignment) OnConflictAddition
    11  }
    12  
    13  func OnConflict(columns ColumnCollection) OnConflictAddition {
    14  	return &onConflict{
    15  		columns: columns,
    16  	}
    17  }
    18  
    19  type onConflict struct {
    20  	columns     ColumnCollection
    21  	doNothing   bool
    22  	assignments []Assignment
    23  }
    24  
    25  func (onConflict) AdditionType() AdditionType {
    26  	return AdditionOnConflict
    27  }
    28  
    29  func (o onConflict) DoNothing() OnConflictAddition {
    30  	o.doNothing = true
    31  	return &o
    32  }
    33  
    34  func (o onConflict) DoUpdateSet(assignments ...Assignment) OnConflictAddition {
    35  	o.assignments = assignments
    36  	return &o
    37  }
    38  
    39  func (o *onConflict) IsNil() bool {
    40  	return o == nil || IsNilExpr(o.columns) || (!o.doNothing && len(o.assignments) == 0)
    41  }
    42  
    43  func (o *onConflict) Ex(ctx context.Context) *Ex {
    44  	e := Expr("ON CONFLICT ")
    45  
    46  	e.WriteGroup(func(e *Ex) {
    47  		e.WriteExpr(o.columns)
    48  	})
    49  
    50  	e.WriteQuery(" DO ")
    51  
    52  	if o.doNothing {
    53  		e.WriteQuery("NOTHING")
    54  	} else {
    55  		e.WriteQuery("UPDATE SET ")
    56  		for i := range o.assignments {
    57  			if i > 0 {
    58  				e.WriteQuery(", ")
    59  			}
    60  			e.WriteExpr(o.assignments[i])
    61  		}
    62  	}
    63  
    64  	return e.Ex(ctx)
    65  }