Implement DISTINCT clause

This commit is contained in:
Pijus Kamandulis
2024-02-27 21:10:03 +02:00
parent f3f3966dd5
commit 5ff923ce2c
6 changed files with 1017 additions and 913 deletions

View File

@@ -35,6 +35,18 @@ func Execute(query parsers.SelectStmt, data []RowType) []RowType {
ctx.orderBy(query.OrderExpressions, result)
}
// Apply select
selectedData := make([]RowType, 0)
for _, row := range result {
selectedData = append(selectedData, ctx.selectRow(query.SelectItems, row))
}
result = selectedData
// Apply distinct
if query.Distinct {
result = deduplicate(result)
}
// Apply result limit
if query.Count > 0 {
count := func() int {
@@ -46,13 +58,7 @@ func Execute(query parsers.SelectStmt, data []RowType) []RowType {
result = result[:count]
}
// Apply select
selectedData := make([]RowType, 0)
for _, row := range result {
selectedData = append(selectedData, ctx.selectRow(query.SelectItems, row))
}
return selectedData
return result
}
func (c memoryExecutorContext) selectRow(selectItems []parsers.SelectItem, row RowType) interface{} {
@@ -349,3 +355,23 @@ func compareValues(val1, val2 interface{}) int {
return 1
}
}
func deduplicate(slice []RowType) []RowType {
var result []RowType
for i := 0; i < len(slice); i++ {
unique := true
for j := 0; j < len(result); j++ {
if compareValues(slice[i], result[j]) == 0 {
unique = false
break
}
}
if unique {
result = append(result, slice[i])
}
}
return result
}

View File

@@ -35,6 +35,24 @@ func Test_Execute_Select(t *testing.T) {
)
})
t.Run("Should execute SELECT DISTINCT", func(t *testing.T) {
testQueryExecute(
t,
parsers.SelectStmt{
SelectItems: []parsers.SelectItem{
{Path: []string{"c", "pk"}},
},
Table: parsers.Table{Value: "c"},
Distinct: true,
},
mockData,
[]memoryexecutor.RowType{
map[string]interface{}{"pk": 123},
map[string]interface{}{"pk": 456},
},
)
})
t.Run("Should execute SELECT TOP", func(t *testing.T) {
testQueryExecute(
t,