Timepicker.js - how to send a query to a datasource while not editing any panel?

api

#1

Problem.
What would be a minimal working example of sending a query to a datasource without having any specific associated panel?
In the timepicker panel I’ve added an editor to submit a user-provided query which would be used to query the database for the most recent data time.
The panel is looking like this at the moment:

I enable the persistence of the stored query by adding it to the panel as $scope.ctrl.panel.storedQuery in app/features/dashboard/timepicker/timepicker.ts.

Question.

  • How do I go about submitting the actual query to Grafana so that it then sends it to the MySQL server?

I was trying to implement this in a database-agnostic way.
So far I have the following function which is called when my “Save Query” button is clicked, but I’m unsure where to add the query string itself:

saveTimeCheckQuery() {
    this.$scope.ctrl.rawSql = $('code-editor .ace_content .ace_text-layer')
      .children()
      .eq(0)
      .text();
    this.$scope.ctrl.storedQuery = this.$scope.ctrl.rawSql;

    this.$scope.ctrl.panel.storedQuery = this.$scope.ctrl.storedQuery;
    const rangeRaw = {
      from: 'now-6h',
      to: 'now',
    };

    const range = {
      from: '2016-10-31T06:33:44.866Z',
      to: '2045-10-31T12:33:44.866Z',
      raw: rangeRaw,
    };

    const metricsQuery = {
      //timezone: this.dashboard.getTimezone(),
      //panelId: this.panel.id,
      //dashboardId: this.$scope.ctrl.dashboard.id,
      range: range,
      rangeRaw: range.raw,
      interval: '5s',
      //intervalMs: 60000,
      //{ "refId": "B", "target": "upper_75" }
      //targets: 
      //targets: [this.currentDatasource.queryModel.target],
  
      maxDataPoints: 2495,
      //scopedVars: {},
      cacheTimeout: null,
      format: 'json',
    };

    this.$scope.ctrl.panel.mostRecentDataTime = this.$scope.ctrl.currentDatasource.query(metricsQuery);
}

Other questions:

  • This JSON sample was based on https://github.com/grafana/simple-json-datasource but I don’t understand how to add the query itself. The JSON looks like it would be the result of parsing a user query. How would I do this here?
  • Because I’m implementing this on the TimePickerCtrl, as far as I know, it is a panel without an ID, so I don’t think I’ll be adding it in this metricsQuery JSON. I imagine the dashboard variables can be used to query the database without being associated to a specific panel - how to achieve the same result here?

Reason.
I’m looking at Grafana’s source to implement a way for the user to define for each dashboard a domain-specific query to get the most recent time of the data.
One may have different tables in a database and need to implement some custom logic to define what is the most recent time range.