File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -44,16 +44,23 @@ func (b *SqlBuilder) SetIndent(indent string) *SqlBuilder {
4444}
4545
4646func (b * SqlBuilder ) Add (key string , args ... interface {}) * SqlBuilder {
47- if len (key ) > 0 {
48- b .fromBuff .WriteString (b .indent )
49- b .fromBuff .WriteString (key )
47+ if len (key ) == 0 {
48+ return b
5049 }
50+
51+ b .fromBuff .WriteString (b .indent )
52+ b .fromBuff .WriteString (key )
5153 if len (args ) > 0 {
5254 b .args = append (b .args , args ... )
5355 }
5456 return b
5557}
5658
59+ // recursive Add, only format the code when coding
60+ func (b * SqlBuilder ) AddTab (key string , args ... interface {}) * SqlBuilder {
61+ return b .Add (key , args ... )
62+ }
63+
5764func (b * SqlBuilder ) AddIf (ok bool , key string , args ... interface {}) * SqlBuilder {
5865 if ! ok {
5966 return b
Original file line number Diff line number Diff line change @@ -9,20 +9,21 @@ func TestSqlBuilder(t *testing.T) {
99 bd := NewSqlBuilder (DRV_NAME_POSTGRES )
1010 bd .Select ("count(*)" )
1111 bd .Add ("FROM" )
12- bd .Add ("tmp tb1" )
13- bd .Add ("INNER JOIN tmp1 tb2 ON tb2.id=tb2.tmp_id" )
12+ bd .AddTab ("tmp tb1" )
13+ bd .AddTab ("INNER JOIN tmp1 tb2 ON tb2.id=tb2.tmp_id" )
1414 bd .Add ("WHERE" )
15- bd .Add ("1=1" )
15+ bd .AddTab ("1=1" )
1616 bd .AddIf (true , "AND (1=?)" , 0 )
1717 bd .AddIf (true , "OR (tb1 IN (" + bd .In ([]interface {}{1 , 2 })+ "))" )
1818 bd .Add ("GROUP BY tb1.id" )
1919 bd .Add ("HAVING count(*)>?" , 1 )
2020 fmt .Println (bd )
2121
22- bd1 := bd .Copy (). Select ( "tb1.id" , "count(*)" )
22+ bd1 := bd .Copy ()
2323 bd1 .Add ("ORDER BY tb1.id DESC" )
2424 bd1 .Add ("OFFSET ?" , 1 )
2525 bd1 .Add ("LIMIT ?" , 1 )
26+ bd1 .Select ("tb1.id" , "count(*)" )
2627 fmt .Println (bd1 )
2728
2829 bd2 := NewSqlBuilder (DRV_NAME_POSTGRES )
You can’t perform that action at this time.
0 commit comments