Executing SQL commands through custom plugin

I am developing a plugin to get familar with the platform and make some proof of concepts. I am trying to execute SQL commands to a local postgres database directly in my plugin through a button component.

Currently I am trying to run the command using, getDataSourceSrv to grab the user defined datasource from Grafana. Then I am using the query() to try and execute the command. Within this query I am setting my target as my query which is a SQL command. I have established that I am connecting to my database however I either receieve a Bad Request or dont seem to recieve any response.

Here is an example of my current implementation.

      const datasource = await getDataSourceSrv().get('PostgreSQL')
      console.log(datasource)
        const response = await datasource.query({ 
        requestId: 'A',
        interval: '30s',
        intervalMs: 30000,
        maxDataPoints: 1000,
        range: {
          from: dateTime().subtract(1, 'h'),
          to: dateTime(),
          raw: {
            from: 'now-1h',
            to: 'now',
          },
        },
        scopedVars: {},
        targets: [query],
        timezone: 'browser',
        app: 'dashboard',
        startTime: Date.now()
        })

where query is

const query = "SELECT * FROM placeholder"

Implement a try catch to see the error

The code you posted does not seem to tell the whole story

Where do you define the connection string, database name, server, etc?

you can also get some ideas by looking at other similar plugins:

2 Likes

I want to use the datasource that the user has defined through grafana.

Does fhe datasource also include the database name?

Yes the use case would be a grafana defined postgreSQL datasource. In setting the datasource the user sets the host, user, pass, and db name.

However when trying to access the datasource using the grafana api I just get the datasource UID, so I cant directly use the pg client or similar solution in my plugin code. I need a way to run SQL directly, so Im trying to use the grafana api to handle the functionality, but the only solution that I have found so far is a http request. However this wouldnt work for this use case as I cant have a backend server. So I need some other way to run SQL commands directly to the database.