yjp преди 1 година
родител
ревизия
683018881d
променени са 2 файла, в които са добавени 81 реда и са изтрити 9 реда
  1. 70 0
      framework/core/infrastructure/database/clause/condition_join.go
  2. 11 9
      test/database_clause_test.go

+ 70 - 0
framework/core/infrastructure/database/clause/condition_join.go

@@ -0,0 +1,70 @@
+package clause
+
+type ConditionJoin struct {
+	left  Clause
+	right Clause
+}
+
+func NewConditionJoin(left Clause, right Clause) *ConditionJoin {
+	return &ConditionJoin{
+		left:  left,
+		right: right,
+	}
+}
+
+func (clause *ConditionJoin) And() *AndJoin {
+	return &AndJoin{
+		conditionJoin: clause,
+	}
+}
+
+func (clause *ConditionJoin) Or() *OrJoin {
+	return &OrJoin{
+		conditionJoin: clause,
+	}
+}
+
+func (clause *ConditionJoin) formClause(conditionOperator string) (string, error) {
+	leftClause, err := clause.left.Clause()
+	if err != nil {
+		return "", err
+	}
+
+	rightClause, err := clause.right.Clause()
+	if err != nil {
+		return "", err
+	}
+
+	return "(" + leftClause + ") " + conditionOperator + " (" + rightClause + ")", nil
+}
+
+func (clause *ConditionJoin) formArgs() []any {
+	args := make([]any, 0)
+	args = append(args, clause.left.Args()...)
+	args = append(args, clause.right.Args()...)
+	return args
+}
+
+type AndJoin struct {
+	conditionJoin *ConditionJoin
+}
+
+func (clause *AndJoin) Clause() (string, error) {
+	return clause.conditionJoin.formClause("AND")
+}
+
+func (clause *AndJoin) Args() []any {
+	return clause.conditionJoin.formArgs()
+}
+
+type OrJoin struct {
+	conditionJoin *ConditionJoin
+}
+
+func (clause *OrJoin) Clause() (string, error) {
+	return clause.conditionJoin.formClause("OR")
+}
+
+func (clause *OrJoin) Args() []any {
+	return clause.conditionJoin.formArgs()
+}

+ 11 - 9
test/database_clause_test.go

@@ -16,7 +16,7 @@ FROM
   test.students
   JOIN test.classes ON classes.id = test.students.class_id
 WHERE
-  (name = ? AND hobby IN ?) AND (age = ? OR gender = ?)
+  (name = ? AND hobby IN ?) OR (age = ? OR gender = ?)
 ORDER BY name DESC
 LIMIT ? OFFSET ?`
 
@@ -28,14 +28,16 @@ LIMIT ? OFFSET ?`
 		}),
 		[]clause.Clause{
 			clause.NewWhere([]clause.Clause{
-				clause.NewConditions().
-					Equal("name", "test").
-					In("hobby", []string{"football", "basketball"}).
-					And(),
-				clause.NewConditions().
-					Equal("age", 18).
-					Equal("gender", "male").
-					Or(),
+				clause.NewConditionJoin(
+					clause.NewConditions().
+						Equal("name", "test").
+						In("hobby", []string{"football", "basketball"}).
+						And(),
+					clause.NewConditions().
+						Equal("age", 18).
+						Equal("gender", "male").
+						Or(),
+				).Or(),
 			}),
 			clause.NewOrderBy("name", false),
 			clause.NewLimit(1, 10),