query_ctrl.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import _ from 'lodash';
  2. import { QueryCtrl } from 'app/plugins/sdk';
  3. import queryPart from './query_part';
  4. import PostgresQuery from './postgres_query';
  5. export interface QueryMeta {
  6. sql: string;
  7. }
  8. const defaultQuery = `SELECT
  9. $__time(time_column),
  10. value1
  11. FROM
  12. metric_table
  13. WHERE
  14. $__timeFilter(time_column)
  15. `;
  16. export class PostgresQueryCtrl extends QueryCtrl {
  17. static templateUrl = 'partials/query.editor.html';
  18. showLastQuerySQL: boolean;
  19. formats: any[];
  20. queryModel: PostgresQuery;
  21. lastQueryMeta: QueryMeta;
  22. lastQueryError: string;
  23. showHelp: boolean;
  24. schemaSegment: any;
  25. tableSegment: any;
  26. timeColumnSegment: any;
  27. selectMenu: any;
  28. groupBySegment: any;
  29. /** @ngInject **/
  30. constructor($scope, $injector, private templateSrv, private $q, private uiSegmentSrv) {
  31. super($scope, $injector);
  32. this.target = this.target;
  33. this.queryModel = new PostgresQuery(this.target, templateSrv, this.panel.scopedVars);
  34. this.formats = [{ text: 'Time series', value: 'time_series' }, { text: 'Table', value: 'table' }];
  35. if (!this.target.rawSql) {
  36. // special handling when in table panel
  37. if (this.panelCtrl.panel.type === 'table') {
  38. this.target.format = 'table';
  39. this.target.rawSql = 'SELECT 1';
  40. } else {
  41. this.target.rawSql = defaultQuery;
  42. }
  43. }
  44. this.schemaSegment= uiSegmentSrv.newSegment(this.target.schema);
  45. if (!this.target.table) {
  46. this.tableSegment = uiSegmentSrv.newSegment({value: 'select table',fake: true});
  47. } else {
  48. this.tableSegment= uiSegmentSrv.newSegment(this.target.table);
  49. }
  50. this.timeColumnSegment = uiSegmentSrv.newSegment(this.target.timeColumn);
  51. this.buildSelectMenu();
  52. this.groupBySegment = this.uiSegmentSrv.newPlusButton();
  53. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  54. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  55. }
  56. buildSelectMenu() {
  57. var categories = queryPart.getCategories();
  58. this.selectMenu = _.reduce(
  59. categories,
  60. function(memo, cat, key) {
  61. var menu = {
  62. text: key,
  63. submenu: cat.map(item => {
  64. return { text: item.type, value: item.type };
  65. }),
  66. };
  67. memo.push(menu);
  68. return memo;
  69. },
  70. []
  71. );
  72. }
  73. toggleEditorMode() {
  74. try {
  75. // this.target.query = this.queryModel.render(false);
  76. } catch (err) {
  77. console.log('query render error');
  78. }
  79. this.target.rawQuery = !this.target.rawQuery;
  80. }
  81. getSchemaSegments() {
  82. var schemaQuery = "SELECT schema_name FROM information_schema.schemata WHERE";
  83. schemaQuery += " schema_name NOT LIKE 'pg_%' AND schema_name <> 'information_schema';";
  84. return this.datasource
  85. .metricFindQuery(schemaQuery)
  86. .then(this.transformToSegments(true))
  87. .catch(this.handleQueryError.bind(this));
  88. }
  89. getTableSegments() {
  90. var tableQuery = "SELECT table_name FROM information_schema.tables WHERE table_schema = '" + this.target.schema + "';";
  91. return this.datasource
  92. .metricFindQuery(tableQuery)
  93. .then(this.transformToSegments(true))
  94. .catch(this.handleQueryError.bind(this));
  95. }
  96. getTimeColumnSegments() {
  97. var columnQuery = "SELECT column_name FROM information_schema.columns WHERE ";
  98. columnQuery += " table_schema = '" + this.target.schema + "'";
  99. columnQuery += " AND table_name = '" + this.target.table + "'";
  100. columnQuery += " AND data_type IN ('timestamp without time zone','timestamp with time zone','bigint','integer','double precision','real');";
  101. return this.datasource
  102. .metricFindQuery(columnQuery)
  103. .then(this.transformToSegments(true))
  104. .catch(this.handleQueryError.bind(this));
  105. }
  106. getColumnSegments() {
  107. var columnQuery = "SELECT column_name FROM information_schema.columns WHERE ";
  108. columnQuery += " table_schema = '" + this.target.schema + "'";
  109. columnQuery += " AND table_name = '" + this.target.table + "'";
  110. columnQuery += " AND data_type IN ('bigint','integer','double precision','real');";
  111. return this.datasource
  112. .metricFindQuery(columnQuery)
  113. .then(this.transformToSegments(true))
  114. .catch(this.handleQueryError.bind(this));
  115. }
  116. tableChanged() {
  117. this.target.table = this.tableSegment.value;
  118. this.panelCtrl.refresh();
  119. }
  120. schemaChanged() {
  121. this.target.schema = this.schemaSegment.value;
  122. this.panelCtrl.refresh();
  123. }
  124. timeColumnChanged() {
  125. this.target.time = this.timeColumnSegment.value;
  126. this.panelCtrl.refresh();
  127. }
  128. onDataReceived(dataList) {
  129. this.lastQueryMeta = null;
  130. this.lastQueryError = null;
  131. let anySeriesFromQuery = _.find(dataList, { refId: this.target.refId });
  132. if (anySeriesFromQuery) {
  133. this.lastQueryMeta = anySeriesFromQuery.meta;
  134. }
  135. }
  136. onDataError(err) {
  137. if (err.data && err.data.results) {
  138. let queryRes = err.data.results[this.target.refId];
  139. if (queryRes) {
  140. this.lastQueryMeta = queryRes.meta;
  141. this.lastQueryError = queryRes.error;
  142. }
  143. }
  144. }
  145. transformToSegments(addTemplateVars) {
  146. return results => {
  147. var segments = _.map(results, segment => {
  148. return this.uiSegmentSrv.newSegment({
  149. value: segment.text,
  150. expandable: segment.expandable,
  151. });
  152. });
  153. if (addTemplateVars) {
  154. for (let variable of this.templateSrv.variables) {
  155. segments.unshift(
  156. this.uiSegmentSrv.newSegment({
  157. type: 'template',
  158. value: '/^$' + variable.name + '$/',
  159. expandable: true,
  160. })
  161. );
  162. }
  163. }
  164. return segments;
  165. };
  166. }
  167. addSelectPart(selectParts, cat, subitem) {
  168. this.queryModel.addSelectPart(selectParts, subitem.value);
  169. this.panelCtrl.refresh();
  170. }
  171. handleSelectPartEvent(selectParts, part, evt) {
  172. switch (evt.name) {
  173. case 'get-param-options': {
  174. var columnQuery = "SELECT column_name FROM information_schema.columns WHERE ";
  175. columnQuery += " table_schema = '" + this.target.schema + "'";
  176. columnQuery += " AND table_name = '" + this.target.table + "'";
  177. columnQuery += " AND data_type IN ('bigint','integer','double precision','real');";
  178. return this.datasource
  179. .metricFindQuery(columnQuery)
  180. .then(this.transformToSegments(true))
  181. .catch(this.handleQueryError.bind(this));
  182. }
  183. case 'part-param-changed': {
  184. this.panelCtrl.refresh();
  185. break;
  186. }
  187. case 'action': {
  188. this.queryModel.removeSelectPart(selectParts, part);
  189. this.panelCtrl.refresh();
  190. break;
  191. }
  192. case 'get-part-actions': {
  193. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  194. }
  195. }
  196. }
  197. handleGroupByPartEvent(part, index, evt) {
  198. switch (evt.name) {
  199. case 'get-param-options': {
  200. var columnQuery = "SELECT column_name FROM information_schema.columns WHERE ";
  201. columnQuery += " table_schema = '" + this.target.schema + "'";
  202. columnQuery += " AND table_name = '" + this.target.table + "'";
  203. return this.datasource
  204. .metricFindQuery(columnQuery)
  205. .then(this.transformToSegments(true))
  206. .catch(this.handleQueryError.bind(this));
  207. }
  208. case 'part-param-changed': {
  209. this.panelCtrl.refresh();
  210. break;
  211. }
  212. case 'action': {
  213. this.queryModel.removeGroupByPart(part, index);
  214. this.panelCtrl.refresh();
  215. break;
  216. }
  217. case 'get-part-actions': {
  218. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  219. }
  220. }
  221. }
  222. getGroupByOptions() {
  223. var columnQuery = "SELECT column_name FROM information_schema.columns WHERE ";
  224. columnQuery += " table_schema = '" + this.target.schema + "'";
  225. columnQuery += " AND table_name = '" + this.target.table + "'";
  226. return this.datasource
  227. .metricFindQuery(columnQuery)
  228. .then(tags => {
  229. var options = [];
  230. if (!this.queryModel.hasFill()) {
  231. options.push(this.uiSegmentSrv.newSegment({ value: 'fill(null)' }));
  232. }
  233. if (!this.target.limit) {
  234. options.push(this.uiSegmentSrv.newSegment({ value: 'LIMIT' }));
  235. }
  236. if (!this.target.slimit) {
  237. options.push(this.uiSegmentSrv.newSegment({ value: 'SLIMIT' }));
  238. }
  239. if (this.target.orderByTime === 'ASC') {
  240. options.push(this.uiSegmentSrv.newSegment({ value: 'ORDER BY time DESC' }));
  241. }
  242. if (!this.queryModel.hasGroupByTime()) {
  243. options.push(this.uiSegmentSrv.newSegment({ value: 'time($interval)' }));
  244. }
  245. for (let tag of tags) {
  246. options.push(this.uiSegmentSrv.newSegment({ value: 'tag(' + tag.text + ')' }));
  247. }
  248. return options;
  249. })
  250. .catch(this.handleQueryError.bind(this));
  251. }
  252. groupByAction() {
  253. switch (this.groupBySegment.value) {
  254. case 'LIMIT': {
  255. this.target.limit = 10;
  256. break;
  257. }
  258. case 'ORDER BY time DESC': {
  259. this.target.orderByTime = 'DESC';
  260. break;
  261. }
  262. default: {
  263. this.queryModel.addGroupBy(this.groupBySegment.value);
  264. }
  265. }
  266. var plusButton = this.uiSegmentSrv.newPlusButton();
  267. this.groupBySegment.value = plusButton.value;
  268. this.groupBySegment.html = plusButton.html;
  269. this.panelCtrl.refresh();
  270. }
  271. handleQueryError(err) {
  272. this.error = err.message || 'Failed to issue metric query';
  273. return [];
  274. }
  275. }