github.com/ecodeclub/eorm@v0.0.2-0.20231001112437-dae71da914d0/expression_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 (
    18  	"fmt"
    19  	"testing"
    20  
    21  	"github.com/stretchr/testify/assert"
    22  )
    23  
    24  func TestRawExpr_AsPredicate(t *testing.T) {
    25  	db := memoryDB()
    26  	testCases := []CommonTestCase{
    27  		{
    28  			name:     "simple",
    29  			builder:  NewSelector[TestModel](db).Where(Raw("`id`<?", 12).AsPredicate()),
    30  			wantSql:  "SELECT `id`,`first_name`,`age`,`last_name` FROM `test_model` WHERE `id`<?;",
    31  			wantArgs: []interface{}{12},
    32  		},
    33  		{
    34  			name: "and",
    35  			builder: NewSelector[TestModel](db).Where(Raw("`id`<?", 12).AsPredicate().
    36  				And(Raw("`age`<?", 18).AsPredicate())),
    37  			wantSql:  "SELECT `id`,`first_name`,`age`,`last_name` FROM `test_model` WHERE (`id`<?) AND (`age`<?);",
    38  			wantArgs: []interface{}{12, 18},
    39  		},
    40  		{
    41  			name: "Or",
    42  			builder: NewSelector[TestModel](db).Where(Raw("`id`<?", 12).AsPredicate().
    43  				Or(Raw("`age`<?", 18).AsPredicate())),
    44  			wantSql:  "SELECT `id`,`first_name`,`age`,`last_name` FROM `test_model` WHERE (`id`<?) OR (`age`<?);",
    45  			wantArgs: []interface{}{12, 18},
    46  		},
    47  	}
    48  
    49  	for _, tc := range testCases {
    50  		c := tc
    51  		t.Run(c.name, func(t *testing.T) {
    52  			query, err := c.builder.Build()
    53  			assert.Equal(t, c.wantErr, err)
    54  			if err != nil {
    55  				return
    56  			}
    57  			assert.Equal(t, c.wantSql, query.SQL)
    58  			assert.Equal(t, c.wantArgs, query.Args)
    59  		})
    60  	}
    61  }
    62  
    63  func ExampleRawExpr_AsPredicate() {
    64  	db := memoryDB()
    65  	pred := Raw("`id`<?", 12).AsPredicate()
    66  	query, _ := NewSelector[TestModel](db).Where(pred).Build()
    67  	fmt.Println(query.String())
    68  	// Output:
    69  	// SQL: SELECT `id`,`first_name`,`age`,`last_name` FROM `test_model` WHERE `id`<?;
    70  	// Args: []interface {}{12}
    71  }