github.com/Ali-iotechsys/sqlboiler/v4@v4.0.0-20221208124957-6aec9a5f1f71/drivers/sqlboiler-mysql/driver/override/test/upsert.go.tpl (about)

     1  {{- $alias := .Aliases.Table .Table.Name}}
     2  func test{{$alias.UpPlural}}Upsert(t *testing.T) {
     3  	t.Parallel()
     4  
     5  	if len({{$alias.DownSingular}}AllColumns) == len({{$alias.DownSingular}}PrimaryKeyColumns) {
     6  		t.Skip("Skipping table with only primary key columns")
     7  	}
     8  	if len(mySQL{{$alias.UpSingular}}UniqueColumns) == 0 {
     9  		t.Skip("Skipping table with no unique columns to conflict on")
    10  	}
    11  
    12  	seed := randomize.NewSeed()
    13  	var err error
    14  	// Attempt the INSERT side of an UPSERT
    15  	o := {{$alias.UpSingular}}{}
    16  	if err = randomize.Struct(seed, &o, {{$alias.DownSingular}}DBTypes, false); err != nil {
    17  		t.Errorf("Unable to randomize {{$alias.UpSingular}} struct: %s", err)
    18  	}
    19  
    20  	{{if not .NoContext}}ctx := context.Background(){{end}}
    21  	tx := MustTx({{if .NoContext}}{{if .NoContext}}boil.Begin(){{else}}boil.BeginTx(ctx, nil){{end}}{{else}}boil.BeginTx(ctx, nil){{end}})
    22  	defer func() { _ = tx.Rollback() }()
    23  	if err = o.Upsert({{if not .NoContext}}ctx, {{end -}} tx, boil.Infer(), boil.Infer()); err != nil {
    24  		t.Errorf("Unable to upsert {{$alias.UpSingular}}: %s", err)
    25  	}
    26  
    27  	count, err := {{$alias.UpPlural}}().Count({{if not .NoContext}}ctx, {{end -}} tx)
    28  	if err != nil {
    29  		t.Error(err)
    30  	}
    31  	if count != 1 {
    32  		t.Error("want one record, got:", count)
    33  	}
    34  
    35  	// Attempt the UPDATE side of an UPSERT
    36  	if err = randomize.Struct(seed, &o, {{$alias.DownSingular}}DBTypes, false, {{$alias.DownSingular}}PrimaryKeyColumns...); err != nil {
    37  		t.Errorf("Unable to randomize {{$alias.UpSingular}} struct: %s", err)
    38  	}
    39  
    40  	if err = o.Upsert({{if not .NoContext}}ctx, {{end -}} tx, boil.Infer(), boil.Infer()); err != nil {
    41  		t.Errorf("Unable to upsert {{$alias.UpSingular}}: %s", err)
    42  	}
    43  
    44  	count, err = {{$alias.UpPlural}}().Count({{if not .NoContext}}ctx, {{end -}} tx)
    45  	if err != nil {
    46  		t.Error(err)
    47  	}
    48  	if count != 1 {
    49  		t.Error("want one record, got:", count)
    50  	}
    51  }