dialect.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package database
  2. import "fmt"
  3. // TrafficMax caps every traffic counter safely below math.MaxInt64 (~9.22e18)
  4. // so that one more delta can never overflow int64. SQLite silently promotes an
  5. // overflowing INTEGER to REAL, after which the column no longer scans into the
  6. // Go int64 field and every reader of the table fails (#5762).
  7. const TrafficMax = int64(9_000_000_000_000_000_000)
  8. func ClampedAddExpr(col string) string {
  9. if IsPostgres() {
  10. return fmt.Sprintf("LEAST(%s + ?, %d)", col, TrafficMax)
  11. }
  12. return fmt.Sprintf("MIN(%s + ?, %d)", col, TrafficMax)
  13. }
  14. func JSONClientsFromInbound() string {
  15. if IsPostgres() {
  16. return "FROM inbounds, jsonb_array_elements(inbounds.settings::jsonb -> 'clients') AS client(value)"
  17. }
  18. return "FROM inbounds, JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client"
  19. }
  20. func JSONFieldText(expr, key string) string {
  21. if IsPostgres() {
  22. return fmt.Sprintf("(%s ->> '%s')", expr, key)
  23. }
  24. return fmt.Sprintf("TRIM(JSON_EXTRACT(%s, '$.%s'), '\"')", expr, key)
  25. }
  26. func GreatestExpr(a, b string) string {
  27. if IsPostgres() {
  28. return fmt.Sprintf("GREATEST(%s::bigint, %s::bigint)", a, b)
  29. }
  30. return fmt.Sprintf("MAX(%s, %s)", a, b)
  31. }
  32. func ClientTrafficEnableMergeExpr() string {
  33. if IsPostgres() {
  34. return "CASE WHEN ?::boolean THEN enable::boolean ELSE false END"
  35. }
  36. return "CASE WHEN ? THEN enable ELSE 0 END"
  37. }