dialect.go 1.1 KB

1234567891011121314151617181920212223242526
  1. package database
  2. import "fmt"
  3. // JSONClientsFromInbound returns the FROM clause that yields one row per element
  4. // of inbounds.settings -> clients, with a column named `client.value` whose text
  5. // fields can be read with JSONFieldText("client.value", "<key>").
  6. func JSONClientsFromInbound() string {
  7. if IsPostgres() {
  8. return "FROM inbounds, jsonb_array_elements(inbounds.settings::jsonb -> 'clients') AS client(value)"
  9. }
  10. return "FROM inbounds, JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client"
  11. }
  12. // JSONFieldText returns a SQL expression that extracts the textual value of <key>
  13. // from a JSON expression. On both backends the result is the raw (unquoted) string,
  14. // so callers do NOT need to trim surrounding quotes.
  15. func JSONFieldText(expr, key string) string {
  16. if IsPostgres() {
  17. return fmt.Sprintf("(%s ->> '%s')", expr, key)
  18. }
  19. // SQLite's JSON_EXTRACT on a text value returns the JSON-encoded form
  20. // (with surrounding quotes). Wrap it in json_extract(json_quote(...)) trick
  21. // is fragile; simpler: unwrap quotes with TRIM(BOTH '"').
  22. return fmt.Sprintf("TRIM(JSON_EXTRACT(%s, '$.%s'), '\"')", expr, key)
  23. }