| package clickhouse |
|
|
| import ( |
| "fmt" |
| "strings" |
|
|
| "github.com/huandu/go-sqlbuilder" |
|
|
| "github.com/openmeterio/openmeter/openmeter/streaming" |
| ) |
|
|
| const subjectToCustomerIDDictionary = "subject_to_customer_id" |
|
|
| |
| func selectCustomerIdColumn(eventsTableName string, customers []streaming.Customer, query *sqlbuilder.SelectBuilder) *sqlbuilder.SelectBuilder { |
| |
| if len(customers) == 0 { |
| return query.SelectMore("'' AS customer_id") |
| } |
|
|
| |
| getColumn := columnFactory(eventsTableName) |
| subjectColumn := getColumn("subject") |
|
|
| |
| var values []string |
|
|
| |
| for _, customer := range customers { |
| customerIDSQL := fmt.Sprintf("'%s'", sqlbuilder.Escape(customer.GetUsageAttribution().ID)) |
|
|
| |
| if customer.GetUsageAttribution().Key != nil { |
| customerKeySQL := fmt.Sprintf("'%s'", sqlbuilder.Escape(*customer.GetUsageAttribution().Key)) |
| values = append(values, customerKeySQL, customerIDSQL) |
| } |
|
|
| |
| for _, subjectKey := range customer.GetUsageAttribution().SubjectKeys { |
| subjectSQL := fmt.Sprintf("'%s'", sqlbuilder.Escape(subjectKey)) |
|
|
| values = append(values, subjectSQL, customerIDSQL) |
| } |
| } |
|
|
| |
| |
| if len(values) == 0 { |
| return query.SelectMore("'' AS customer_id") |
| } |
|
|
| |
|
|
| mapSQL := fmt.Sprintf("WITH map(%s) as %s", strings.Join(values, ", "), subjectToCustomerIDDictionary) |
|
|
| |
| mapQuery := sqlbuilder.ClickHouse.NewCTEBuilder().SQL(mapSQL) |
| query = query.With(mapQuery) |
|
|
| |
| query = query.SelectMore(fmt.Sprintf("%s[%s] AS customer_id", subjectToCustomerIDDictionary, subjectColumn)) |
|
|
| return query |
| } |
|
|
| |
| func customersWhere(eventsTableName string, customers []streaming.Customer, query *sqlbuilder.SelectBuilder) *sqlbuilder.SelectBuilder { |
| |
| if len(customers) == 0 { |
| return query |
| } |
|
|
| |
| getColumn := columnFactory(eventsTableName) |
| subjectColumn := getColumn("subject") |
|
|
| var subjects []string |
|
|
| |
| for _, customer := range customers { |
| subjects = append(subjects, customer.GetUsageAttribution().GetValues()...) |
| } |
|
|
| |
| |
| if len(subjects) == 0 { |
| return query |
| } |
|
|
| return query.Where(query.In(subjectColumn, subjects)) |
| } |
|
|
| |
| func subjectWhere( |
| eventsTableName string, |
| subjects []string, |
| query *sqlbuilder.SelectBuilder, |
| ) *sqlbuilder.SelectBuilder { |
| |
| getColumn := columnFactory(eventsTableName) |
| subjectColumn := getColumn("subject") |
|
|
| |
| |
| |
| if len(subjects) > 0 { |
| query = query.Where(query.In(subjectColumn, subjects)) |
| } |
|
|
| return query |
| } |
|
|
| func columnFactory(alias string) func(string) string { |
| return func(column string) string { |
| return fmt.Sprintf("%s.%s", alias, column) |
| } |
| } |
|
|