1
0

dialect.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. // ClientTrafficEnableMergeExpr: placeholders nodeEnable, nodeExpiry, nodeTotal,
  33. // now, deltaUp, deltaDown. Mirrors nodeDisableIsStale (#6228 / #4917).
  34. func ClientTrafficEnableMergeExpr() string {
  35. if IsPostgres() {
  36. return `CASE
  37. WHEN ?::boolean THEN enable::boolean
  38. WHEN (expiry_time <> CAST(? AS BIGINT) OR total <> CAST(? AS BIGINT))
  39. AND (expiry_time <= 0 OR expiry_time > CAST(? AS BIGINT))
  40. AND (total <= 0 OR up + ? + down + ? < total) THEN enable::boolean
  41. ELSE false
  42. END`
  43. }
  44. return `CASE
  45. WHEN ? THEN enable
  46. WHEN (expiry_time <> CAST(? AS BIGINT) OR total <> CAST(? AS BIGINT))
  47. AND (expiry_time <= 0 OR expiry_time > CAST(? AS BIGINT))
  48. AND (total <= 0 OR up + ? + down + ? < total) THEN enable
  49. ELSE 0
  50. END`
  51. }
  52. // ClientTrafficExpiryMergeExpr: placeholder nodeExpiry once. Master absolute is
  53. // kept; CAST avoids Postgres int4 inference on ms timestamps.
  54. func ClientTrafficExpiryMergeExpr() string {
  55. return `CASE
  56. WHEN expiry_time > 0 THEN expiry_time
  57. ELSE CAST(? AS BIGINT)
  58. END`
  59. }