223 Commits

Author SHA1 Message Date
f34127c449 Query Service: Fix Time Bug (#108337) 2025-07-18 18:14:44 +00:00
3fad863fd1 Query Service: Combine SSE handling in single tenant and multi tenant paths (#108041)
* parse via sse

I need to figure out how to handle the pipeline.execute with our own
client. I think this is important for MT reasons, just like using our
own cache (via legacy) is important.

parsing is done though!

* WIP nonsense

* horrible code but i think it works

* Add support for sql expressions config settings

* Cleanup:
- remove spew from nodes.go
- uncomment out plugin context and use in single tenant flow
- make code more readable and add comments

* Cleanup:
- create separate file for mt ds client builder
- ensure error handling is the same for both expressions and regular queries
- other cleanup

* not working but good thoughts

* WIP, vector not working for non sse

* super hacky but i think vectors work now

* delete delete delete

* Comments for future ref

* break out query handling and start test

* add prom debugger

* clean up: remove comments and commented out bits

* fix query_test

* add prom debugger

* create table-driven tests with testsdata files

* Fix test

* Add test

* go mod??

* idk

* Remove comment

* go enterprise issue maybe

* Fix codeowners

* Delete

* Remove test data

* Clean up

* logger

* Remove go changes hopefully

* idk go man

* sad

* idk i ran go mod tidy and this is what it wants

* Fix readme, with much help from adam

* some linting and testing errors

* lint

* fix lint

* fix lint register.go

* another lint

* address lint in test

* fix dead code and linters for query_test

* Go mod?

* Struggling with go mod

* Fix test

* Fix another test

* Revert headers change

* Its difficult to test this in OSS as it depends on functionality defined in enterprise, let's bring these tests back in some form in enterprise

* Fix codeowners

---------

Co-authored-by: Adam Simpson <adam@adamsimpson.net>
2025-07-17 17:22:55 -04:00
8b6329a224 SQL Expressions: Fixes for Prometheus Metric Instrumentation (#106722)
* capture errors on metrics
* rename seconds to sql_command_duration_milliseconds to match unit that has been captured, and update buckets
* rename sql_command_errors_total to sql_command_count
2025-06-17 09:23:56 -04:00
1be9e60667 SQL Expressions: Exclude CTEs from required Tables (#106479)
Fixes #105030

---------

Co-authored-by: Sam Jewell <2903904+samjewell@users.noreply.github.com>
2025-06-11 10:36:28 -04:00
7f1a286ffb SQL Expressions: Always convert on type first (#106083)
fixes #103124
2025-05-28 12:00:37 -04:00
005f390df4 SSE: Update execution order to move DS queries first (#105686)
This is part of getting SSE more consistent when run from the query service vs part of grafana-server. 
fixes #105680
2025-05-27 09:34:40 -04:00
23ecb9d904 i18n: Use grafana/i18n to init the locale and manage the regionalFormat (#105281) 2025-05-19 13:24:33 +02:00
467b88eec5 Test: Make timeout 1ns to minimise flakiness (#105437) 2025-05-15 14:18:09 +02:00
5e056c2a3f SQL Expressions: Add sql expression specific timeout and output limit (#104834)
Adds settings for SQL expressions:
 sql_expression_cell_output_limit

Set the maximum number of cells that can be returned from a SQL expression. Default is 100000.

sql_expression_timeout

The duration a SQL expression will run before being cancelled. The default is 10s.
2025-05-13 15:22:20 -04:00
6a6ba723a9 SQL Expressions: Add internal GMS traces (#104836)
get trace from inside GMS
2025-05-09 14:48:47 -04:00
109267ab03 Alerting: Remove feature toggle for custom recovery threshold (#104455) 2025-04-24 11:58:17 -04:00
af59c4eb3e Chore: bump grafana-plugin-sdk-go from v0.275.0 to v0.277.0 (#103971)
Co-authored-by: Ryan McKinley <ryantxu@gmail.com>
2025-04-17 00:32:25 +03:00
5c418196f9 SQL Expressions: Add STDDEV(), VARIANCE() and aliases (#103851)
* SQL Expressions: Bump GMS for STDDEV(), VARIANCE()

Bump Go MySQL Server to the latest version, to get support for STDDEV()
and VARIANCE() functions, and their aliases.

See https://github.com/dolthub/go-mysql-server/pull/2928

* Update app-code to comply with latest GMS version

* Run `go mod tidy`

* Update test which had depended on STDDEV being missing

* Run `make update-workspace`
2025-04-15 10:48:19 +01:00
4aa7d67edd Server-side expressions: Improve error message (#103968)
This error message is more correct
2025-04-14 21:14:03 +00:00
fd6fd91115 Prometheus: Add support for cloud partners Prometheus data sources (#103482)
* wip

* Add prom flavor support for data source variables and export/import dashboards (#103321)

* add dashboard and data source var selection

* use match plugin id instead

* use updated matchpluginid

* formatting

* cleanup

* regex anchor

* update error msg

* Alerting: Clean up prometheus-flavored types and functions (#103703)

* clean up types and utility functions for dealing with
prometheus-flavored data sources

* Refactor alerting datasource types to use constants as source of truth

* Alerting: Clean up prometheus-flavored types and functions on the bac… (#103716)

Alerting: Clean up prometheus-flavored types and functions on the backend

* add matchPluginId tests

* Update matchPluginId func to bidirectional (#103746)

* update matchpluginid func to bidirectional

* lint

* formatting

* use actual isSupportedExternalRulesSourceType in test

* add tests in datasource_srv

* betterer

* remove type assertion

* remove unnecessary case

* use satisifies to not have to convert tuple to an array of string

* add prometheus_flavor test

---------

Co-authored-by: Andrew Hackmann <5140848+bossinc@users.noreply.github.com>
Co-authored-by: Gilles De Mey <gilles.de.mey@gmail.com>
Co-authored-by: Alexander Akhmetov <me@alx.cx>
2025-04-10 12:49:11 -07:00
acd843303e SQL Expression: Add instrumentation for sql expressions (#103758) 2025-04-10 19:51:44 +01:00
757be6365a CI: Bump golangci-lint to 2.0.2 (#103572) 2025-04-10 14:42:23 +02:00
aea8f27c59 Sql Expressions - remove references to poc database (#103618)
Sql Expressions - remove DuckDB references
2025-04-08 10:59:19 -04:00
f8a72214cf SQL Expressions: Add more functions to the allowlist (#103546)
* SQL Expressions: Allow many more functions and nodes

* Also allow the `REGEXP_SUBSTR` function

* Add window functions

* add more JSON support, remove now and current time (for now)

---------

Co-authored-by: Kyle Brandt <kyle@grafana.com>
2025-04-07 21:23:39 +03:00
b1490a10e8 SQL Expressions / Alerting: Do not allow duplicates (#103394) 2025-04-04 10:00:30 -04:00
4a0ec27e5d SQL Expressions: Query Service Support (#101955)
---------

Co-authored-by: Adam Simpson <adam@adamsimpson.net>
Co-authored-by: Sarah Zinger <sarah.zinger@grafana.com>
2025-04-03 09:36:02 -04:00
c6e52c4766 SQL Expressions: Make SQL Expressions work with Alerting (#101820)
Initial support for alerting with SQL expressions

- When `format` is set to `alerting`, SQL expressions output in a format suitable for alerting evaluation.
- Outstanding TODOs:
  - Deduplicate output rows
  - Add more tests
  - Fix broken alerting UI rendering (likely due to shape change to undocumented full-long format)
- Basic usage:
  - SQL must return one numeric column and one or more string columns.
  - Each row may become an alert.
  - The alert fires if the numeric value is non-zero.
  - String columns are treated as labels.

---------

Co-authored-by: Konrad Lalik <konradlalik@gmail.com>
Co-authored-by: Tom Ratcliffe <tom.ratcliffe@grafana.com>
Co-authored-by: Sam Jewell <sam.jewell@grafana.com>
2025-04-02 09:39:36 -04:00
856dcfd6fe SQL Expressions: Permit range conditions (between) in queries (#103238) 2025-04-02 15:13:17 +03:00
af08a9fae2 SQL Expressions: Add JSON support (#103157)
- Support bi-directional mapping of frame JSON fields and GMS (go-mysql-server) columns 
- Permit GMS json functions

Co-authored-by: Kyle Brandt <kyle@grafana.com>
2025-04-01 07:45:01 -04:00
e6480a050c SQL Expressions: Allow substring_index func (#103021) 2025-03-27 16:49:21 -04:00
c9e929e2e6 SQL Expressions: Allow more MySQL AST node-types (#102973)
* SQL Expressions: Add Null-literal node

* Retain some order in the code - put NullVal with BoolVal

* Add support for `IN` keyword

* Add GROUP_CONCAT keyword

* Add COLLATE keyword

From Claude:

The test case demonstrates a simple use of COLLATE with a string
literal, but in real MySQL queries, COLLATE is often used in more
complex scenarios like:

1. String comparisons:
   `SELECT * FROM table WHERE name COLLATE utf8mb4_bin = 'John'`
2. Sorting:
   `SELECT * FROM table ORDER BY name COLLATE utf8mb4_unicode_ci`
3. JOINs:
   `SELECT * FROM table1 JOIN table2 ON table1.name COLLATE utf8mb4_bin = table2.name`

The COLLATE clause is particularly useful when you need case-sensitive
comparisons (utf8mb4_bin) or specific language-aware sorting rules.
2025-03-27 11:32:48 +00:00
6be7829acf SQL Expressions: Allow IS keyword (#102841) 2025-03-26 09:05:42 +00:00
0f6aff2057 SQL Expressions: allow ParenSelect in queries (#102807)
sql_expressions: allow ParenSelect
2025-03-25 16:19:52 +00:00
f4849eabc7 SQL Expressions: Change metric conversion to full long (#102728)
When querying metric data (non-table data) with SQL Expressions, we need to convert the data to table format. This is alternative format which does not have the same issues with sparse data.

There is now a __metric_name__ column and one __value__ column. Also a __display_name__ column if there is DisplayNameFromDS metadata.

---------

Co-authored-by: Adam Simpson <adam@adamsimpson.net>
2025-03-24 22:04:43 +02:00
1b1f626edd SQL Expressions: Fix error handling (#102650) 2025-03-21 18:47:00 -04:00
3f2ef07872 SSE: Fix goroutine leak in math operation expression parsing (#102380)
---------

Co-authored-by: Sam Jewell <sam.jewell@grafana.com>
2025-03-19 08:34:49 -04:00
d7aeebe5e3 Sql Expressions: State when error is from GMS (#102112) 2025-03-18 22:41:42 +00:00
21b9d45ca6 SQL Expressions: Add CASE/WHEN nodes and fixes (and test) for functions just added to allowlist (#102040)
* SQL Expressions: Add CASE/WHEN SQL nodes to allowlist

* Fixed and test for functions added in #102011

* Add remaining functions to the test-case

These are mostly aliases, so the LLM chose to omit them originally.
But adding now for completeness

* Fix ordering of allowed nodes
2025-03-12 15:57:50 +00:00
4bd5f29e05 SQL Expressions: Allow more functions (#102011)
I used Cursor and Claude 3.7 thinking to expand the list of functions
we allow. Specifically I needed `abs`.

TODO: Check each of these in the official MySQL docs to ensure they
are all safe:
eg. this doc: https://dev.mysql.com/doc/refman/8.4/en/flow-control-functions.html#operator_case
2025-03-12 11:39:48 +00:00
7a3415148e SQL Expressions: Add cell-limit for input dataframes (#101700)
* expr: Add row limit to SQL expressions

Adds a configurable row limit to SQL expressions to prevent memory issues with large
result sets. The limit is configured via the `sql_expression_row_limit` setting in
the `[expressions]` section of grafana.ini, with a default of 100,000 rows.

The limit is enforced by checking the total number of rows across all input tables
before executing the SQL query. If the total exceeds the limit, the query fails
with an error message indicating the limit was exceeded.

* revert addition of newline

* Switch to table-driven tests

* Remove single-frame test-cases.

We only need to test for the multi frame case. Single frame is a subset
of the multi-frame case

* Add helper function

Simplify the way tests are set up and written

* Support convention, that limit: 0 is no limit

* Set the row-limit in one place only

* Update default limit to 20k rows

As per some discussion here:
https://raintank-corp.slack.com/archives/C071A5XCFST/p1741611647001369?thread_ts=1740047619.804869&cid=C071A5XCFST

* Test row-limit is applied from config

Make sure we protect this from regressions

This is perhaps a brittle test, somewhat coupled to the code here. But
it's good enough to prevent regressions at least.

* Add public documentation for the limit

* Limit total number of cells instead of rows

* Use named-return for totalRows

As @kylebrandt requested during review of #101700

* Leave DF cells as zero values during limits tests

When testing the cell limit we don't interact with the cell values at
all, so we leave them at their zero values both to speed up tests, and
to simplify and clarify that their values aren't used.

* Set SQLCmd limit at object creation - don't mutate

* Test that SQL node receives limit when built

And that it receives it from the Grafana config

* Improve TODO message for new Expression Parser

* Fix failing test by always creating config on the Service
2025-03-11 17:14:33 +00:00
0eafd0641f SQL Expressions: Simplify test code (#101718)
Simplify, by retaining quotes when escaping query

We also don't need to convert to string when passing to fmt.Sprintf
a slice of Bytes is accepted by Sprintf instead.
2025-03-06 17:02:31 +00:00
3539764008 Hackaton: Add more unit tests, take 3 (#101525)
* serviceaccounts/secretscan: test Service more thoroughly

* middleware/cookies: add tests for CookieOptions

* anonymous/anonimpl: cover a couple more methods

* components/imguploader: Implement WebDAV integration tests

* components/apikeygen: also check IsValid method

* bus: cover invalid callback signature cases

* cloudmigration/objectstorage: add basic unit tests

* login/social/connectors: add test case for GitHub OAuth fetch emails+orgs

* expr/classic: cover more evaluator types in tests
2025-03-05 08:00:12 +01:00
2d2e595555 Alerting: Add multiple threshold operators (#99516)
The following operators are being added:
- Equal
- Not Equal
- Greater or Equal
- Less or Equal
- Within Range Inclusive
- Outside Range Inclusive
2025-02-21 19:11:16 +02:00
4d7b9a3c77 SQL Expressions: Improve response to frame conversion handling (#100625)
- use types.Convert to get a more normalized type returned from GMS. After syncing with GMS maintainers, the underlying type of the row could be different things (e.g. int when unit32, so this calls the Convert method from the GMS types library to normalize the interface.
- Clean up fieldValFromRow more
- Use IsText to capture different string types
- Add more types to test, also update test to use same cmp.Diff method as others

---------

Co-authored-by: Sam Jewell <2903904+samjewell@users.noreply.github.com>
2025-02-14 17:21:08 +02:00
c291ec7ba9 SQL Expressions: Include SQL Parser/Syntax error in the public message (#100725)
fixes #100721
2025-02-14 09:09:21 -05:00
f7588376df SQL Expressions: (Chore) Update code for latest plugin-sdk data pkg (#100425)
Use new NilAt and SetRefId methods
2025-02-11 15:15:54 +00:00
6dc98dbbcc SQL Expressions: Add str_to_date function and unskip test (#100226) 2025-02-07 11:51:55 +02:00
d196b789e2 SQL Expressions: Add more SQLNodes and funcs to allow list (#100227)
sql_expr: Add more Nodes and funcs to allow list
2025-02-07 09:44:17 +00:00
d64f41afdc SQL Expressions: Re-implement feature using go-mysql-server (#99521)
* Under feature flag `sqlExpressions` and is experimental
* Excluded from arm32
* Will not work with the Query Service yet
* Does not have limits in place yet
* Does not working with alerting yet
* Currently requires "prepare time series" Transform for time series viz
 
---------

Co-authored-by: Sam Jewell <sam.jewell@grafana.com>
2025-02-06 07:27:28 -05:00
76f052e8de Requester: Remove duplicated function (#97038)
* Remove duplicated function

* Remove GetDisplayName from interface

* Use GetName
2024-11-26 15:29:31 +01:00
1915efbc95 SQL Expressions: Simplify where code is being stubbed out (#96227)
* Rename from DuckDB

* Remove unused function
2024-11-18 12:05:08 +00:00
ea71201ddc ServerSideExpressions: Disable SQL Expressions to prevent RCE and LFI vulnerability (#94942)
* disable sql expressions

remove duckdb ref

* Run `make update-workspace`

---------

Co-authored-by: Scott Lepper <scott.lepper@gmail.com>
2024-10-18 11:28:26 +01:00
cbe1e7d63f expr: add explicit strict-mode const (#94838)
expr: add explicit strict-mode value
2024-10-18 10:46:27 +02:00
34bb959835 expr: improved test (#94837) 2024-10-18 10:31:58 +02:00
2cea7af2f5 datasources: querier: handle reducer-settings-mode correctly (#94595)
* datasources: querier: handle reducer-settings-mode correctly

* Try to fix linting error

"unnecessary leading newline (whitespace)"

---------

Co-authored-by: Sam Jewell <sam.jewell@grafana.com>
2024-10-17 08:38:14 +02:00