github.com/ecodeclub/eorm@v0.0.2-0.20231001112437-dae71da914d0/assignment_test.go (about)

     1  // Copyright 2021 ecodeclub
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  // http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package eorm
    16  
    17  import "fmt"
    18  
    19  func ExampleAssign() {
    20  	db := memoryDB()
    21  	tm := &TestModel{}
    22  	examples := []struct {
    23  		assign    Assignment
    24  		assignStr string
    25  		wantSQL   string
    26  		wantArgs  []interface{}
    27  	}{
    28  		{
    29  			assign:    Assign("Age", 18),
    30  			assignStr: `Assign("Age", 18)`,
    31  			wantSQL:   "UPDATE `test_model` SET `age`=?;",
    32  			wantArgs:  []interface{}{18},
    33  		},
    34  		{
    35  			assign:    Assign("Age", C("Id")),
    36  			assignStr: `Assign("Age", C("Id"))`,
    37  			wantSQL:   "UPDATE `test_model` SET `age`=`id`;",
    38  		},
    39  		{
    40  			assign:    Assign("Age", C("Age").Add(1)),
    41  			assignStr: `Assign("Age", C("Age").Add(1))`,
    42  			wantSQL:   "UPDATE `test_model` SET `age`=`age`+?;",
    43  			wantArgs:  []interface{}{1},
    44  		},
    45  		{
    46  			assign:    Assign("Age", Raw("`age`+`id`+1")),
    47  			assignStr: "Assign(\"Age\", Raw(\"`age`+`id`+1\"))",
    48  			wantSQL:   "UPDATE `test_model` SET `age`=`age`+`id`+1;",
    49  		},
    50  	}
    51  	for _, exp := range examples {
    52  		query, _ := NewUpdater[TestModel](db).Update(tm).Set(exp.assign).Build()
    53  		fmt.Printf(`
    54  Assignment: %s
    55  SQL: %s
    56  Args: %v
    57  `, exp.assignStr, query.SQL, query.Args)
    58  	}
    59  	// Output:
    60  	//
    61  	// Assignment: Assign("Age", 18)
    62  	// SQL: UPDATE `test_model` SET `age`=?;
    63  	// Args: [18]
    64  	//
    65  	// Assignment: Assign("Age", C("Id"))
    66  	// SQL: UPDATE `test_model` SET `age`=`id`;
    67  	// Args: []
    68  	//
    69  	// Assignment: Assign("Age", C("Age").Add(1))
    70  	// SQL: UPDATE `test_model` SET `age`=(`age`+?);
    71  	// Args: [1]
    72  	//
    73  	// Assignment: Assign("Age", Raw("`age`+`id`+1"))
    74  	// SQL: UPDATE `test_model` SET `age`=`age`+`id`+1;
    75  	// Args: []
    76  }