Skip to content
Snippets Groups Projects
database_logs.go 2.11 KiB
Newer Older
Francé Wilke's avatar
Francé Wilke committed
package logs

import (
	"context"
	"github.com/samber/lo"
Francé Wilke's avatar
Francé Wilke committed
	"github.com/uptrace/bun"
Francé Wilke's avatar
Francé Wilke committed
	"strings"
	"time"
)

var ignoredTableInserts = []string{
	"sync_audit",
	"audit_events",
	"audit",
	"communication_logs",
	"sync_product_variants",
	"webhook_events",
	"notification_audit_events",
Johan de Klerk's avatar
Johan de Klerk committed
	"rollup_age_analysis",
	"rollup_transactions",
	"rollup_shipments_charges",
	"rollup_shipments_events",
Johan de Klerk's avatar
Johan de Klerk committed
	"rollup_tripsheet",
	"rollup_branches",
	"cron_shipment_updates",
Johan de Klerk's avatar
Johan de Klerk committed
	"cron_delayed_shipment_patch",
	"orders_rollup",
	"shipments_rollup",
	"revenue_rollup",
Francé Wilke's avatar
Francé Wilke committed
type QueryHook struct {
	IgnoredTableInserts []string
	Debug               bool
Francé Wilke's avatar
Francé Wilke committed
}

func (d QueryHook) BeforeQuery(ctx context.Context, _ *bun.QueryEvent) context.Context {
	return ctx
}

func (d QueryHook) AfterQuery(_ context.Context, event *bun.QueryEvent) {
	sqlQuery := event.Query

	queryDuration := time.Now().Sub(event.StartTime)

	queryPrefixesToIgnore := []string{"SELECT", "BEGIN", "COMMIT"}
	shouldLogQuery := !strings.Contains(sqlQuery, "api_key")

	// Don't log queries for certain tables
	ignoredTableInsertsCombined := append(ignoredTableInserts, d.IgnoredTableInserts...)
	tableName := TableNameForQuery(event)
	if lo.Contains(ignoredTableInsertsCombined, tableName) {
		shouldLogQuery = false
	}

Francé Wilke's avatar
Francé Wilke committed
	if shouldLogQuery {
		for _, prefixToIgnore := range queryPrefixesToIgnore {
			if strings.HasPrefix(sqlQuery, prefixToIgnore) {
				shouldLogQuery = false
				break
			}
		}
	}

	if d.Debug || shouldLogQuery {
Francé Wilke's avatar
Francé Wilke committed
		InfoWithFields(map[string]interface{}{"sql": sqlQuery, "t": queryDuration.String()}, "")
Francé Wilke's avatar
Francé Wilke committed
	}
	return
}

func TableNameForQuery(event *bun.QueryEvent) string {
Johan de Klerk's avatar
Johan de Klerk committed
	if event.Model == nil {
		return ""
	}

	model := event.Model.Value()
Johan de Klerk's avatar
Johan de Klerk committed
	if model == nil {
		return ""
	}

	var modelObject reflect.Type
	t := reflect.TypeOf(model)
	pointerToObject := t.Elem()

	if pointerToObject.Kind() == reflect.Slice {
		// Object is an array of objects. Get the struct type from the array
		sliceObject := pointerToObject.Elem()
		modelObject = sliceObject
	} else {
		// Object is a struct
		modelObject = pointerToObject
	}

	tableName := event.DB.Table(modelObject).Name