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BAAiB,UAClDtL,MAAMmH,IACL,MAAMX,EAAU,GACXzH,KAAK4I,WAAWhF,gBACnB6D,EAAQvF,KAAKlC,KAAK0N,aAAaQ,WAAW,CAAElL,KAAM,OAAQjD,MAAO,4BAEnE,IAAK,MAAMgG,KAAOqC,EAChBX,EAAQvF,KAAKlC,KAAK0N,aAAaQ,WAAW,CAAElL,KAAM,SAAUjD,MAAOgG,EAAIzE,QAEzE,OAAOmG,KAERgE,MAAMzL,KAAKkR,iBAAiB7N,KAAKrD,OAGtCwU,iBACExU,KAAKqT,SAASrT,KAAK4O,SAAS5L,KAAMhD,KAAK4O,SAAS7O,OAChDC,KAAK6Q,gBAAgB7Q,KAAK4O,UAC1B5O,KAAKsO,yBAGP4C,iBAAiB9F,GAEf,OADApL,KAAKqS,MAAQjH,EAAItB,SAAW,+BACrB,I,gEA1pBEyD,EAAAA,cACU,8BCRvB,MAAMkH,EAMJ9U,YAAYC,GACVI,KAAKkI,WAAatI,EAAOM,KAAKgI,WAC9BlI,KAAKkI,WAAW/E,SAAWnD,KAAKkI,WAAW/E,UAlBzB,kK,iCAWC,oC,EADjBsR,iB,EAAAA,G,sFAYC,MAAMC,EAAS,IAAIC,EAAAA,iBAAoDpM,GAC3EqM,aAAarH,GACbsH,cAAcnV,GACdoV,uBAAuBL","sources":["webpack://grafana/./public/app/plugins/datasource/postgres/config_ctrl.ts","webpack://grafana/./public/app/plugins/datasource/postgres/postgres_query_model.ts","webpack://grafana/./public/app/plugins/datasource/postgres/response_parser.ts","webpack://grafana/./public/app/plugins/datasource/postgres/datasource.ts","webpack://grafana/./public/app/plugins/datasource/postgres/meta_query.ts","webpack://grafana/./public/app/plugins/datasource/postgres/sql_part.ts","webpack://grafana/./public/app/plugins/datasource/postgres/query_ctrl.ts","webpack://grafana/./public/app/plugins/datasource/postgres/module.ts"],"sourcesContent":["import { find } from 'lodash';\n\nimport { DatasourceSrv } from 'app/features/plugins/datasource_srv';\n\nimport {\n createChangeHandler,\n createResetHandler,\n PasswordFieldEnum,\n} from '../../../features/datasources/utils/passwordHandlers';\n\nexport class PostgresConfigCtrl {\n static templateUrl = 'partials/config.html';\n\n // Set through angular bindings\n declare current: any;\n\n datasourceSrv: any;\n showTimescaleDBHelp: boolean;\n onPasswordReset: ReturnType<typeof createResetHandler>;\n onPasswordChange: ReturnType<typeof createChangeHandler>;\n\n /** @ngInject */\n constructor($scope: any, datasourceSrv: DatasourceSrv) {\n this.current = $scope.ctrl.current;\n this.datasourceSrv = datasourceSrv;\n this.current.jsonData.sslmode = this.current.jsonData.sslmode || 'verify-full';\n this.current.jsonData.tlsConfigurationMethod = this.current.jsonData.tlsConfigurationMethod || 'file-path';\n this.current.jsonData.postgresVersion = this.current.jsonData.postgresVersion || 903;\n this.showTimescaleDBHelp = false;\n this.autoDetectFeatures();\n this.onPasswordReset = createResetHandler(this, PasswordFieldEnum.Password);\n this.onPasswordChange = createChangeHandler(this, PasswordFieldEnum.Password);\n this.tlsModeMapping();\n }\n\n autoDetectFeatures() {\n if (!this.current.id) {\n return;\n }\n\n this.datasourceSrv.loadDatasource(this.current.name).then((ds: any) => {\n return ds.getVersion().then((version: any) => {\n version = Number(version[0].text);\n\n // timescaledb is only available for 9.6+\n if (version >= 906) {\n ds.getTimescaleDBVersion().then((version: any) => {\n if (version.length === 1) {\n this.current.jsonData.timescaledb = true;\n }\n });\n }\n\n const major = Math.trunc(version / 100);\n const minor = version % 100;\n let name = String(major);\n if (version < 1000) {\n name = String(major) + '.' + String(minor);\n }\n if (!find(this.postgresVersions, (p: any) => p.value === version)) {\n this.postgresVersions.push({ name: name, value: version });\n }\n this.current.jsonData.postgresVersion = version;\n });\n });\n }\n\n toggleTimescaleDBHelp() {\n this.showTimescaleDBHelp = !this.showTimescaleDBHelp;\n }\n\n tlsModeMapping() {\n if (this.current.jsonData.sslmode === 'disable') {\n this.current.jsonData.tlsAuth = false;\n this.current.jsonData.tlsAuthWithCACert = false;\n this.current.jsonData.tlsSkipVerify = true;\n } else {\n this.current.jsonData.tlsAuth = true;\n this.current.jsonData.tlsAuthWithCACert = true;\n this.current.jsonData.tlsSkipVerify = false;\n }\n }\n\n // the value portion is derived from postgres server_version_num/100\n postgresVersions = [\n { name: '9.3', value: 903 },\n { name: '9.4', value: 904 },\n { name: '9.5', value: 905 },\n { name: '9.6', value: 906 },\n { name: '10', value: 1000 },\n { name: '11', value: 1100 },\n { name: '12+', value: 1200 },\n ];\n}\n","import { find, map } from 'lodash';\n\nimport { ScopedVars } from '@grafana/data';\nimport { TemplateSrv } from '@grafana/runtime';\n\nexport default class PostgresQueryModel {\n target: any;\n templateSrv: any;\n scopedVars: any;\n\n /** @ngInject */\n constructor(target: any, templateSrv?: TemplateSrv, scopedVars?: ScopedVars) {\n this.target = target;\n this.templateSrv = templateSrv;\n this.scopedVars = scopedVars;\n\n target.format = target.format || 'time_series';\n target.timeColumn = target.timeColumn || 'time';\n target.metricColumn = target.metricColumn || 'none';\n\n target.group = target.group || [];\n target.where = target.where || [{ type: 'macro', name: '$__timeFilter', params: [] }];\n target.select = target.select || [[{ type: 'column', params: ['value'] }]];\n\n // handle pre query gui panels gracefully\n if (!('rawQuery' in this.target)) {\n if ('rawSql' in target) {\n // pre query gui panel\n target.rawQuery = true;\n } else {\n // new panel\n target.rawQuery = false;\n }\n }\n\n // give interpolateQueryStr access to this\n this.interpolateQueryStr = this.interpolateQueryStr.bind(this);\n }\n\n // remove identifier quoting from identifier to use in metadata queries\n unquoteIdentifier(value: string) {\n if (value[0] === '\"' && value[value.length - 1] === '\"') {\n return value.substring(1, value.length - 1).replace(/\"\"/g, '\"');\n } else {\n return value;\n }\n }\n\n quoteIdentifier(value: any) {\n return '\"' + String(value).replace(/\"/g, '\"\"') + '\"';\n }\n\n quoteLiteral(value: any) {\n return \"'\" + String(value).replace(/'/g, \"''\") + \"'\";\n }\n\n escapeLiteral(value: any) {\n return String(value).replace(/'/g, \"''\");\n }\n\n hasTimeGroup() {\n return find(this.target.group, (g: any) => g.type === 'time');\n }\n\n hasMetricColumn() {\n return this.target.metricColumn !== 'none';\n }\n\n interpolateQueryStr(value: any, variable: { multi: any; includeAll: any }, defaultFormatFn: any) {\n // if no multi or include all do not regexEscape\n if (!variable.multi && !variable.includeAll) {\n return this.escapeLiteral(value);\n }\n\n if (typeof value === 'string') {\n return this.quoteLiteral(value);\n }\n\n const escapedValues = map(value, this.quoteLiteral);\n return escapedValues.join(',');\n }\n\n render(interpolate?: any) {\n const target = this.target;\n\n // new query with no table set yet\n if (!this.target.rawQuery && !('table' in this.target)) {\n return '';\n }\n\n if (!target.rawQuery) {\n target.rawSql = this.buildQuery();\n }\n\n if (interpolate) {\n return this.templateSrv.replace(target.rawSql, this.scopedVars, this.interpolateQueryStr);\n } else {\n return target.rawSql;\n }\n }\n\n hasUnixEpochTimecolumn() {\n return ['int4', 'int8', 'float4', 'float8', 'numeric'].indexOf(this.target.timeColumnType) > -1;\n }\n\n buildTimeColumn(alias = true) {\n const timeGroup = this.hasTimeGroup();\n let query;\n let macro = '$__timeGroup';\n\n if (timeGroup) {\n let args;\n if (timeGroup.params.length > 1 && timeGroup.params[1] !== 'none') {\n args = timeGroup.params.join(',');\n } else {\n args = timeGroup.params[0];\n }\n if (this.hasUnixEpochTimecolumn()) {\n macro = '$__unixEpochGroup';\n }\n if (alias) {\n macro += 'Alias';\n }\n query = macro + '(' + this.target.timeColumn + ',' + args + ')';\n } else {\n query = this.target.timeColumn;\n if (alias) {\n query += ' AS \"time\"';\n }\n }\n\n return query;\n }\n\n buildMetricColumn() {\n if (this.hasMetricColumn()) {\n return this.target.metricColumn + ' AS metric';\n }\n\n return '';\n }\n\n buildValueColumns() {\n let query = '';\n for (const column of this.target.select) {\n query += ',\\n ' + this.buildValueColumn(column);\n }\n\n return query;\n }\n\n buildValueColumn(column: any) {\n let query = '';\n\n const columnName: any = find(column, (g: any) => g.type === 'column');\n query = columnName.params[0];\n\n const aggregate: any = find(column, (g: any) => g.type === 'aggregate' || g.type === 'percentile');\n const windows: any = find(column, (g: any) => g.type === 'window' || g.type === 'moving_window');\n\n if (aggregate) {\n const func = aggregate.params[0];\n switch (aggregate.type) {\n case 'aggregate':\n if (func === 'first' || func === 'last') {\n query = func + '(' + query + ',' + this.target.timeColumn + ')';\n } else {\n query = func + '(' + query + ')';\n }\n break;\n case 'percentile':\n query = func + '(' + aggregate.params[1] + ') WITHIN GROUP (ORDER BY ' + query + ')';\n break;\n }\n }\n\n if (windows) {\n const overParts = [];\n if (this.hasMetricColumn()) {\n overParts.push('PARTITION BY ' + this.target.metricColumn);\n }\n overParts.push('ORDER BY ' + this.buildTimeColumn(false));\n\n const over = overParts.join(' ');\n let curr: string;\n let prev: string;\n switch (windows.type) {\n case 'window':\n switch (windows.params[0]) {\n case 'delta':\n curr = query;\n prev = 'lag(' + curr + ') OVER (' + over + ')';\n query = curr + ' - ' + prev;\n break;\n case 'increase':\n curr = query;\n prev = 'lag(' + curr + ') OVER (' + over + ')';\n query = '(CASE WHEN ' + curr + ' >= ' + prev + ' THEN ' + curr + ' - ' + prev;\n query += ' WHEN ' + prev + ' IS NULL THEN NULL ELSE ' + curr + ' END)';\n break;\n case 'rate':\n let timeColumn = this.target.timeColumn;\n if (aggregate) {\n timeColumn = 'min(' + timeColumn + ')';\n }\n\n curr = query;\n prev = 'lag(' + curr + ') OVER (' + over + ')';\n query = '(CASE WHEN ' + curr + ' >= ' + prev + ' THEN ' + curr + ' - ' + prev;\n query += ' WHEN ' + prev + ' IS NULL THEN NULL ELSE ' + curr + ' END)';\n query += '/extract(epoch from ' + timeColumn + ' - lag(' + timeColumn + ') OVER (' + over + '))';\n break;\n default:\n query = windows.params[0] + '(' + query + ') OVER (' + over + ')';\n break;\n }\n break;\n case 'moving_window':\n query = windows.params[0] + '(' + query + ') OVER (' + over + ' ROWS ' + windows.params[1] + ' PRECEDING)';\n break;\n }\n }\n\n const alias: any = find(column, (g: any) => g.type === 'alias');\n if (alias) {\n query += ' AS ' + this.quoteIdentifier(alias.params[0]);\n }\n\n return query;\n }\n\n buildWhereClause() {\n let query = '';\n const conditions = map(this.target.where, (tag, index) => {\n switch (tag.type) {\n case 'macro':\n return tag.name + '(' + this.target.timeColumn + ')';\n break;\n case 'expression':\n return tag.params.join(' ');\n break;\n }\n });\n\n if (conditions.length > 0) {\n query = '\\nWHERE\\n ' + conditions.join(' AND\\n ');\n }\n\n return query;\n }\n\n buildGroupClause() {\n let query = '';\n let groupSection = '';\n\n for (let i = 0; i < this.target.group.length; i++) {\n const part = this.target.group[i];\n if (i > 0) {\n groupSection += ', ';\n }\n if (part.type === 'time') {\n groupSection += '1';\n } else {\n groupSection += part.params[0];\n }\n }\n\n if (groupSection.length) {\n query = '\\nGROUP BY ' + groupSection;\n if (this.hasMetricColumn()) {\n query += ',2';\n }\n }\n return query;\n }\n\n buildQuery() {\n let query = 'SELECT';\n\n query += '\\n ' + this.buildTimeColumn();\n if (this.hasMetricColumn()) {\n query += ',\\n ' + this.buildMetricColumn();\n }\n query += this.buildValueColumns();\n\n query += '\\nFROM ' + this.target.table;\n\n query += this.buildWhereClause();\n query += this.buildGroupClause();\n\n query += '\\nORDER BY 1';\n if (this.hasMetricColumn()) {\n query += ',2';\n }\n\n return query;\n }\n}\n","import { AnnotationEvent, DataFrame, MetricFindValue } from '@grafana/data';\nimport { BackendDataSourceResponse, FetchResponse, toDataQueryResponse } from '@grafana/runtime';\n\nexport default class ResponseParser {\n transformMetricFindResponse(raw: FetchResponse<BackendDataSourceResponse>): MetricFindValue[] {\n const frames = toDataQueryResponse(raw).data as DataFrame[];\n\n if (!frames || !frames.length) {\n return [];\n }\n\n const frame = frames[0];\n\n const values: MetricFindValue[] = [];\n const textField = frame.fields.find((f) => f.name === '__text');\n const valueField = frame.fields.find((f) => f.name === '__value');\n\n if (textField && valueField) {\n for (let i = 0; i < textField.values.length; i++) {\n values.push({ text: '' + textField.values.get(i), value: '' + valueField.values.get(i) });\n }\n } else {\n values.push(\n ...frame.fields\n .flatMap((f) => f.values.toArray())\n .map((v) => ({\n text: v,\n }))\n );\n }\n\n return Array.from(new Set(values.map((v) => v.text))).map((text) => ({\n text,\n value: values.find((v) => v.text === text)?.value,\n }));\n }\n\n async transformAnnotationResponse(options: any, data: BackendDataSourceResponse): Promise<AnnotationEvent[]> {\n const frames = toDataQueryResponse({ data: data }).data as DataFrame[];\n if (!frames || !frames.length) {\n return [];\n }\n const frame = frames[0];\n const timeField = frame.fields.find((f) => f.name === 'time');\n\n if (!timeField) {\n throw new Error('Missing mandatory time column (with time column alias) in annotation query');\n }\n\n const timeEndField = frame.fields.find((f) => f.name === 'timeend');\n const textField = frame.fields.find((f) => f.name === 'text');\n const tagsField = frame.fields.find((f) => f.name === 'tags');\n\n const list: AnnotationEvent[] = [];\n for (let i = 0; i < frame.length; i++) {\n const timeEnd = timeEndField && timeEndField.values.get(i) ? Math.floor(timeEndField.values.get(i)) : undefined;\n list.push({\n annotation: options.annotation,\n time: Math.floor(timeField.values.get(i)),\n timeEnd,\n text: textField && textField.values.get(i) ? textField.values.get(i) : '',\n tags:\n tagsField && tagsField.values.get(i)\n ? tagsField.values\n .get(i)\n .trim()\n .split(/\\s*,\\s*/)\n : [],\n });\n }\n\n return list;\n }\n}\n","import { map as _map } from 'lodash';\nimport { lastValueFrom, of } from 'rxjs';\nimport { map, catchError } from 'rxjs/operators';\n\nimport { AnnotationEvent, DataSourceInstanceSettings, MetricFindValue, ScopedVars, TimeRange } from '@grafana/data';\nimport { BackendDataSourceResponse, DataSourceWithBackend, FetchResponse, getBackendSrv } from '@grafana/runtime';\nimport { toTestingStatus } from '@grafana/runtime/src/utils/queryResponse';\nimport { getTemplateSrv, TemplateSrv } from 'app/features/templating/template_srv';\nimport PostgresQueryModel from 'app/plugins/datasource/postgres/postgres_query_model';\n\nimport { getSearchFilterScopedVar } from '../../../features/variables/utils';\n\nimport ResponseParser from './response_parser';\nimport { PostgresOptions, PostgresQuery, PostgresQueryForInterpolation } from './types';\n\nexport class PostgresDatasource extends DataSourceWithBackend<PostgresQuery, PostgresOptions> {\n id: any;\n name: any;\n jsonData: any;\n responseParser: ResponseParser;\n queryModel: PostgresQueryModel;\n interval: string;\n\n constructor(\n instanceSettings: DataSourceInstanceSettings<PostgresOptions>,\n private readonly templateSrv: TemplateSrv = getTemplateSrv()\n ) {\n super(instanceSettings);\n this.name = instanceSettings.name;\n this.id = instanceSettings.id;\n this.jsonData = instanceSettings.jsonData;\n this.responseParser = new ResponseParser();\n this.queryModel = new PostgresQueryModel({});\n const settingsData = instanceSettings.jsonData || ({} as PostgresOptions);\n this.interval = settingsData.timeInterval || '1m';\n }\n\n interpolateVariable = (value: string | string[], variable: { multi: any; includeAll: any }) => {\n if (typeof value === 'string') {\n if (variable.multi || variable.includeAll) {\n return this.queryModel.quoteLiteral(value);\n } else {\n return value;\n }\n }\n\n if (typeof value === 'number') {\n return value;\n }\n\n const quotedValues = _map(value, (v) => {\n return this.queryModel.quoteLiteral(v);\n });\n return quotedValues.join(',');\n };\n\n interpolateVariablesInQueries(\n queries: PostgresQueryForInterpolation[],\n scopedVars: ScopedVars\n ): PostgresQueryForInterpolation[] {\n let expandedQueries = queries;\n if (queries && queries.length > 0) {\n expandedQueries = queries.map((query) => {\n const expandedQuery = {\n ...query,\n datasource: this.getRef(),\n rawSql: this.templateSrv.replace(query.rawSql, scopedVars, this.interpolateVariable),\n rawQuery: true,\n };\n return expandedQuery;\n });\n }\n return expandedQueries;\n }\n\n filterQuery(query: PostgresQuery): boolean {\n return !query.hide;\n }\n\n applyTemplateVariables(target: PostgresQuery, scopedVars: ScopedVars): Record<string, any> {\n const queryModel = new PostgresQueryModel(target, this.templateSrv, scopedVars);\n return {\n refId: target.refId,\n datasource: this.getRef(),\n rawSql: queryModel.render(this.interpolateVariable as any),\n format: target.format,\n };\n }\n\n async annotationQuery(options: any): Promise<AnnotationEvent[]> {\n if (!options.annotation.rawQuery) {\n return Promise.reject({\n message: 'Query missing in annotation definition',\n });\n }\n\n const query = {\n refId: options.annotation.name,\n datasource: this.getRef(),\n rawSql: this.templateSrv.replace(options.annotation.rawQuery, options.scopedVars, this.interpolateVariable),\n format: 'table',\n };\n\n return lastValueFrom(\n getBackendSrv()\n .fetch<BackendDataSourceResponse>({\n url: '/api/ds/query',\n method: 'POST',\n data: {\n from: options.range.from.valueOf().toString(),\n to: options.range.to.valueOf().toString(),\n queries: [query],\n },\n requestId: options.annotation.name,\n })\n .pipe(\n map(\n async (res: FetchResponse<BackendDataSourceResponse>) =>\n await this.responseParser.transformAnnotationResponse(options, res.data)\n )\n )\n );\n }\n\n metricFindQuery(query: string, optionalOptions: any): Promise<MetricFindValue[]> {\n let refId = 'tempvar';\n if (optionalOptions && optionalOptions.variable && optionalOptions.variable.name) {\n refId = optionalOptions.variable.name;\n }\n\n const rawSql = this.templateSrv.replace(\n query,\n getSearchFilterScopedVar({ query, wildcardChar: '%', options: optionalOptions }),\n this.interpolateVariable\n );\n\n const interpolatedQuery = {\n refId: refId,\n datasource: this.getRef(),\n rawSql,\n format: 'table',\n };\n\n const range = optionalOptions?.range as TimeRange;\n\n return lastValueFrom(\n getBackendSrv()\n .fetch<BackendDataSourceResponse>({\n url: '/api/ds/query',\n method: 'POST',\n data: {\n from: range?.from?.valueOf()?.toString(),\n to: range?.to?.valueOf()?.toString(),\n queries: [interpolatedQuery],\n },\n requestId: refId,\n })\n .pipe(\n map((rsp) => {\n return this.responseParser.transformMetricFindResponse(rsp);\n }),\n catchError((err) => {\n return of([]);\n })\n )\n );\n }\n\n private _metaRequest(rawSql: string) {\n const refId = 'meta';\n const query = {\n refId: refId,\n datasource: this.getRef(),\n rawSql,\n format: 'table',\n };\n return getBackendSrv().fetch<BackendDataSourceResponse>({\n url: '/api/ds/query',\n method: 'POST',\n data: {\n queries: [query],\n },\n requestId: refId,\n });\n }\n\n getVersion(): Promise<any> {\n return lastValueFrom(this._metaRequest(\"SELECT current_setting('server_version_num')::int/100\"));\n }\n\n getTimescaleDBVersion(): Promise<any> {\n return lastValueFrom(this._metaRequest(\"SELECT extversion FROM pg_extension WHERE extname = 'timescaledb'\"));\n }\n\n testDatasource(): Promise<any> {\n return lastValueFrom(this._metaRequest('SELECT 1'))\n .then(() => {\n return { status: 'success', message: 'Database Connection OK' };\n })\n .catch((err: any) => {\n return toTestingStatus(err);\n });\n }\n\n targetContainsTemplate(target: any) {\n let rawSql = '';\n\n if (target.rawQuery) {\n rawSql = target.rawSql;\n } else {\n const query = new PostgresQueryModel(target);\n rawSql = query.buildQuery();\n }\n\n rawSql = rawSql.replace('$__', '');\n\n return this.templateSrv.containsTemplate(rawSql);\n }\n}\n","import QueryModel from './postgres_query_model';\n\nexport class PostgresMetaQuery {\n constructor(private target: { table: string; timeColumn: string }, private queryModel: QueryModel) {}\n\n getOperators(datatype: string) {\n switch (datatype) {\n case 'float4':\n case 'float8': {\n return ['=', '!=', '<', '<=', '>', '>='];\n }\n case 'text':\n case 'varchar':\n case 'char': {\n return ['=', '!=', '<', '<=', '>', '>=', 'IN', 'NOT IN', 'LIKE', 'NOT LIKE', '~', '~*', '!~', '!~*'];\n }\n default: {\n return ['=', '!=', '<', '<=', '>', '>=', 'IN', 'NOT IN'];\n }\n }\n }\n\n // quote identifier as literal to use in metadata queries\n quoteIdentAsLiteral(value: string) {\n return this.queryModel.quoteLiteral(this.queryModel.unquoteIdentifier(value));\n }\n\n findMetricTable() {\n // query that returns first table found that has a timestamp(tz) column and a float column\n let query = `\nSELECT\n\tquote_ident(table_name) as table_name,\n\t( SELECT\n\t quote_ident(column_name) as column_name\n\t FROM information_schema.columns c\n WHERE\n c.table_schema = t.table_schema AND\n c.table_name = t.table_name AND\n udt_name IN ('timestamptz','timestamp')\n ORDER BY ordinal_position LIMIT 1\n ) AS time_column,\n ( SELECT\n quote_ident(column_name) AS column_name\n FROM information_schema.columns c\n WHERE\n c.table_schema = t.table_schema AND\n c.table_name = t.table_name AND\n udt_name='float8'\n ORDER BY ordinal_position LIMIT 1\n ) AS value_column\nFROM information_schema.tables t\nWHERE `;\n query += this.buildSchemaConstraint();\n query += ` AND\n EXISTS\n ( SELECT 1\n FROM information_schema.columns c\n WHERE\n c.table_schema = t.table_schema AND\n c.table_name = t.table_name AND\n udt_name IN ('timestamptz','timestamp')\n ) AND\n EXISTS\n ( SELECT 1\n FROM information_schema.columns c\n WHERE\n c.table_schema = t.table_schema AND\n c.table_name = t.table_name AND\n udt_name='float8'\n )\nLIMIT 1\n;`;\n return query;\n }\n\n buildSchemaConstraint() {\n // quote_ident protects hyphenated schemes\n const query = `\nquote_ident(table_schema) IN (\n SELECT\n CASE WHEN trim(s[i]) = '\"$user\"' THEN user ELSE trim(s[i]) END\n FROM\n generate_series(\n array_lower(string_to_array(current_setting('search_path'),','),1),\n array_upper(string_to_array(current_setting('search_path'),','),1)\n ) as i,\n string_to_array(current_setting('search_path'),',') s\n)`;\n return query;\n }\n\n buildTableConstraint(table: string) {\n let query = '';\n\n // check for schema qualified table\n if (table.includes('.')) {\n const parts = table.split('.');\n query = 'table_schema = ' + this.quoteIdentAsLiteral(parts[0]);\n query += ' AND table_name = ' + this.quoteIdentAsLiteral(parts[1]);\n return query;\n } else {\n query = this.buildSchemaConstraint();\n query += ' AND table_name = ' + this.quoteIdentAsLiteral(table);\n\n return query;\n }\n }\n\n buildTableQuery() {\n let query = 'SELECT quote_ident(table_name) FROM information_schema.tables WHERE ';\n query += this.buildSchemaConstraint();\n query += ' ORDER BY table_name';\n return query;\n }\n\n buildColumnQuery(type?: string) {\n let query = 'SELECT quote_ident(column_name) FROM information_schema.columns WHERE ';\n query += this.buildTableConstraint(this.target.table);\n\n switch (type) {\n case 'time': {\n query +=\n \" AND data_type IN ('timestamp without time zone','timestamp with time zone','bigint','integer','double precision','real')\";\n break;\n }\n case 'metric': {\n query += \" AND data_type IN ('text','character','character varying')\";\n break;\n }\n case 'value': {\n query += \" AND data_type IN ('bigint','integer','double precision','real','numeric')\";\n query += ' AND column_name <> ' + this.quoteIdentAsLiteral(this.target.timeColumn);\n break;\n }\n case 'group': {\n query += \" AND data_type IN ('text','character','character varying','uuid')\";\n break;\n }\n }\n\n query += ' ORDER BY column_name';\n\n return query;\n }\n\n buildValueQuery(column: string) {\n let query = 'SELECT DISTINCT quote_literal(' + column + ')';\n query += ' FROM ' + this.target.table;\n query += ' WHERE $__timeFilter(' + this.target.timeColumn + ')';\n query += ' AND ' + column + ' IS NOT NULL';\n query += ' ORDER BY 1 LIMIT 100';\n return query;\n }\n\n buildDatatypeQuery(column: string) {\n let query = 'SELECT udt_name FROM information_schema.columns WHERE ';\n query += this.buildTableConstraint(this.target.table);\n query += ' AND column_name = ' + this.quoteIdentAsLiteral(column);\n return query;\n }\n\n buildAggregateQuery() {\n let query = 'SELECT DISTINCT proname FROM pg_aggregate ';\n query += 'INNER JOIN pg_proc ON pg_aggregate.aggfnoid = pg_proc.oid ';\n query += 'INNER JOIN pg_type ON pg_type.oid=pg_proc.prorettype ';\n query += \"WHERE pronargs=1 AND typname IN ('float8') AND aggkind='n' ORDER BY 1\";\n return query;\n }\n}\n","import { SqlPartDef, SqlPart } from 'app/angular/components/sql_part/sql_part';\n\nconst index: any[] = [];\n\nfunction createPart(part: any): any {\n const def = index[part.type];\n if (!def) {\n return null;\n }\n\n return new SqlPart(part, def);\n}\n\nfunction register(options: any) {\n index[options.type] = new SqlPartDef(options);\n}\n\nregister({\n type: 'column',\n style: 'label',\n params: [{ type: 'column', dynamicLookup: true }],\n defaultParams: ['value'],\n});\n\nregister({\n type: 'expression',\n style: 'expression',\n label: 'Expr:',\n params: [\n { name: 'left', type: 'string', dynamicLookup: true },\n { name: 'op', type: 'string', dynamicLookup: true },\n { name: 'right', type: 'string', dynamicLookup: true },\n ],\n defaultParams: ['value', '=', 'value'],\n});\n\nregister({\n type: 'macro',\n style: 'label',\n label: 'Macro:',\n params: [],\n defaultParams: [],\n});\n\nregister({\n type: 'aggregate',\n style: 'label',\n params: [\n {\n name: 'name',\n type: 'string',\n options: [],\n baseOptions: ['avg', 'count', 'min', 'max', 'sum', 'stddev', 'variance'],\n timescaleOptions: ['first', 'last'],\n },\n ],\n defaultParams: ['avg'],\n});\n\nregister({\n type: 'percentile',\n label: 'Aggregate:',\n style: 'label',\n params: [\n {\n name: 'name',\n type: 'string',\n options: ['percentile_cont', 'percentile_disc'],\n },\n {\n name: 'fraction',\n type: 'number',\n options: ['0.5', '0.75', '0.9', '0.95', '0.99'],\n },\n ],\n defaultParams: ['percentile_cont', '0.95'],\n});\n\nregister({\n type: 'alias',\n style: 'label',\n params: [{ name: 'name', type: 'string', quote: 'double' }],\n defaultParams: ['alias'],\n});\n\nregister({\n type: 'time',\n style: 'function',\n label: 'time',\n params: [\n {\n name: 'interval',\n type: 'interval',\n options: ['$__interval', '1s', '10s', '1m', '5m', '10m', '15m', '1h'],\n },\n {\n name: 'fill',\n type: 'string',\n options: ['none', 'NULL', 'previous', '0'],\n },\n ],\n defaultParams: ['$__interval', 'none'],\n});\n\nregister({\n type: 'window',\n style: 'label',\n params: [\n {\n name: 'function',\n type: 'string',\n options: ['delta', 'increase', 'rate', 'sum'],\n },\n ],\n defaultParams: ['increase'],\n});\n\nregister({\n type: 'moving_window',\n style: 'label',\n label: 'Moving Window:',\n params: [\n {\n name: 'function',\n type: 'string',\n options: ['avg'],\n },\n {\n name: 'window_size',\n type: 'number',\n options: ['3', '5', '7', '10', '20'],\n },\n ],\n defaultParams: ['avg', '5'],\n});\n\nexport default {\n create: createPart,\n};\n","import { auto } from 'angular';\nimport { clone, filter, find, findIndex, indexOf, map } from 'lodash';\n\nimport { PanelEvents, QueryResultMeta } from '@grafana/data';\nimport { TemplateSrv } from '@grafana/runtime';\nimport { SqlPart } from 'app/angular/components/sql_part/sql_part';\nimport appEvents from 'app/core/app_events';\nimport { VariableWithMultiSupport } from 'app/features/variables/types';\nimport { QueryCtrl } from 'app/plugins/sdk';\nimport { ShowConfirmModalEvent } from 'app/types/events';\n\nimport { PostgresMetaQuery } from './meta_query';\nimport PostgresQueryModel from './postgres_query_model';\nimport sqlPart from './sql_part';\n\nconst defaultQuery = `SELECT\n $__time(time_column),\n value1\nFROM\n metric_table\nWHERE\n $__timeFilter(time_column)\n`;\n\nexport class PostgresQueryCtrl extends QueryCtrl {\n static templateUrl = 'partials/query.editor.html';\n\n formats: any[];\n queryModel: PostgresQueryModel;\n metaBuilder: PostgresMetaQuery;\n lastQueryMeta?: QueryResultMeta;\n lastQueryError?: string;\n showHelp = false;\n tableSegment: any;\n whereAdd: any;\n timeColumnSegment: any;\n metricColumnSegment: any;\n selectMenu: any[] = [];\n selectParts: SqlPart[][] = [[]];\n groupParts: SqlPart[] = [];\n whereParts: SqlPart[] = [];\n groupAdd: any;\n\n /** @ngInject */\n constructor(\n $scope: any,\n $injector: auto.IInjectorService,\n private templateSrv: TemplateSrv,\n private uiSegmentSrv: any\n ) {\n super($scope, $injector);\n this.target = this.target;\n this.queryModel = new PostgresQueryModel(this.target, templateSrv, this.panel.scopedVars);\n this.metaBuilder = new PostgresMetaQuery(this.target, this.queryModel);\n this.updateProjection();\n\n this.formats = [\n { text: 'Time series', value: 'time_series' },\n { text: 'Table', value: 'table' },\n ];\n\n if (!this.target.rawSql) {\n // special handling when in table panel\n if (this.panelCtrl.panel.type === 'table') {\n this.target.format = 'table';\n this.target.rawSql = 'SELECT 1';\n this.target.rawQuery = true;\n } else {\n this.target.rawSql = defaultQuery;\n this.datasource.metricFindQuery(this.metaBuilder.findMetricTable()).then((result: any) => {\n if (result.length > 0) {\n this.target.table = result[0].text;\n let segment = this.uiSegmentSrv.newSegment(this.target.table);\n this.tableSegment.html = segment.html;\n this.tableSegment.value = segment.value;\n\n this.target.timeColumn = result[1].text;\n segment = this.uiSegmentSrv.newSegment(this.target.timeColumn);\n this.timeColumnSegment.html = segment.html;\n this.timeColumnSegment.value = segment.value;\n\n this.target.timeColumnType = 'timestamp';\n this.target.select = [[{ type: 'column', params: [result[2].text] }]];\n this.updateProjection();\n this.updateRawSqlAndRefresh();\n }\n });\n }\n }\n\n if (!this.target.table) {\n this.tableSegment = uiSegmentSrv.newSegment({ value: 'select table', fake: true });\n } else {\n this.tableSegment = uiSegmentSrv.newSegment(this.target.table);\n }\n\n this.timeColumnSegment = uiSegmentSrv.newSegment(this.target.timeColumn);\n this.metricColumnSegment = uiSegmentSrv.newSegment(this.target.metricColumn);\n\n this.buildSelectMenu();\n this.whereAdd = this.uiSegmentSrv.newPlusButton();\n this.groupAdd = this.uiSegmentSrv.newPlusButton();\n\n this.panelCtrl.events.on(PanelEvents.dataReceived, this.onDataReceived.bind(this), $scope);\n this.panelCtrl.events.on(PanelEvents.dataError, this.onDataError.bind(this), $scope);\n }\n\n updateRawSqlAndRefresh() {\n if (!this.target.rawQuery) {\n this.target.rawSql = this.queryModel.buildQuery();\n }\n\n this.panelCtrl.refresh();\n }\n\n timescaleAggCheck() {\n const aggIndex = this.findAggregateIndex(this.selectParts[0]);\n\n // add or remove TimescaleDB aggregate functions as needed\n if (aggIndex !== -1) {\n const baseOpts = this.selectParts[0][aggIndex].def.params[0].baseOptions;\n const timescaleOpts = baseOpts.concat(this.selectParts[0][aggIndex].def.params[0].timescaleOptions);\n\n if (this.datasource.jsonData.timescaledb === true) {\n this.selectParts[0][aggIndex].def.params[0].options = timescaleOpts;\n } else {\n this.selectParts[0][aggIndex].def.params[0].options = baseOpts;\n }\n }\n }\n\n updateProjection() {\n this.selectParts = map(this.target.select, (parts: any) => {\n return map(parts, sqlPart.create).filter((n) => n);\n });\n this.timescaleAggCheck();\n this.whereParts = map(this.target.where, sqlPart.create).filter((n) => n);\n this.groupParts = map(this.target.group, sqlPart.create).filter((n) => n);\n }\n\n updatePersistedParts() {\n this.target.select = map(this.selectParts, (selectParts) => {\n return map(selectParts, (part: any) => {\n return { type: part.def.type, datatype: part.datatype, params: part.params };\n });\n });\n this.timescaleAggCheck();\n this.target.where = map(this.whereParts, (part: any) => {\n return { type: part.def.type, datatype: part.datatype, name: part.name, params: part.params };\n });\n this.target.group = map(this.groupParts, (part: any) => {\n return { type: part.def.type, datatype: part.datatype, params: part.params };\n });\n }\n\n buildSelectMenu() {\n this.selectMenu = [];\n const aggregates = {\n text: 'Aggregate Functions',\n value: 'aggregate',\n submenu: [\n { text: 'Average', value: 'avg' },\n { text: 'Count', value: 'count' },\n { text: 'Maximum', value: 'max' },\n { text: 'Minimum', value: 'min' },\n { text: 'Sum', value: 'sum' },\n { text: 'Standard deviation', value: 'stddev' },\n { text: 'Variance', value: 'variance' },\n ],\n };\n\n // first and last aggregate are timescaledb specific\n if (this.datasource.jsonData.timescaledb === true) {\n aggregates.submenu.push({ text: 'First', value: 'first' });\n aggregates.submenu.push({ text: 'Last', value: 'last' });\n }\n\n this.selectMenu.push(aggregates);\n\n // ordered set aggregates require postgres 9.4+\n if (this.datasource.jsonData.postgresVersion >= 904) {\n const aggregates2 = {\n text: 'Ordered-Set Aggregate Functions',\n value: 'percentile',\n submenu: [\n { text: 'Percentile (continuous)', value: 'percentile_cont' },\n { text: 'Percentile (discrete)', value: 'percentile_disc' },\n ],\n };\n this.selectMenu.push(aggregates2);\n }\n\n const windows = {\n text: 'Window Functions',\n value: 'window',\n submenu: [\n { text: 'Delta', value: 'delta' },\n { text: 'Increase', value: 'increase' },\n { text: 'Rate', value: 'rate' },\n { text: 'Sum', value: 'sum' },\n { text: 'Moving Average', value: 'avg', type: 'moving_window' },\n ],\n };\n this.selectMenu.push(windows);\n\n this.selectMenu.push({ text: 'Alias', value: 'alias' });\n this.selectMenu.push({ text: 'Column', value: 'column' });\n }\n\n toggleEditorMode() {\n if (this.target.rawQuery) {\n appEvents.publish(\n new ShowConfirmModalEvent({\n title: 'Warning',\n text2: 'Switching to query builder may overwrite your raw SQL.',\n icon: 'exclamation-triangle',\n yesText: 'Switch',\n onConfirm: () => {\n // This could be called from React, so wrap in $evalAsync.\n // Will then either run as part of the current digest cycle or trigger a new one.\n this.$scope.$evalAsync(() => {\n this.target.rawQuery = !this.target.rawQuery;\n });\n },\n })\n );\n } else {\n // This could be called from React, so wrap in $evalAsync.\n // Will then either run as part of the current digest cycle or trigger a new one.\n this.$scope.$evalAsync(() => {\n this.target.rawQuery = !this.target.rawQuery;\n });\n }\n }\n\n resetPlusButton(button: { html: any; value: any; type: any; fake: any }) {\n const plusButton = this.uiSegmentSrv.newPlusButton();\n button.html = plusButton.html;\n button.value = plusButton.value;\n button.type = plusButton.type;\n button.fake = plusButton.fake;\n }\n\n getTableSegments() {\n return this.datasource\n .metricFindQuery(this.metaBuilder.buildTableQuery())\n .then(this.transformToSegments({}))\n .catch(this.handleQueryError.bind(this));\n }\n\n tableChanged() {\n this.target.table = this.tableSegment.value;\n this.target.where = [];\n this.target.group = [];\n this.updateProjection();\n\n const segment = this.uiSegmentSrv.newSegment('none');\n this.metricColumnSegment.html = segment.html;\n this.metricColumnSegment.value = segment.value;\n this.target.metricColumn = 'none';\n\n const task1 = this.datasource.metricFindQuery(this.metaBuilder.buildColumnQuery('time')).then((result: any) => {\n // check if time column is still valid\n if (result.length > 0 && !find(result, (r: any) => r.text === this.target.timeColumn)) {\n const segment = this.uiSegmentSrv.newSegment(result[0].text);\n this.timeColumnSegment.html = segment.html;\n this.timeColumnSegment.value = segment.value;\n }\n return this.timeColumnChanged(false);\n });\n const task2 = this.datasource.metricFindQuery(this.metaBuilder.buildColumnQuery('value')).then((result: any) => {\n if (result.length > 0) {\n this.target.select = [[{ type: 'column', params: [result[0].text] }]];\n this.updateProjection();\n }\n });\n\n Promise.all([task1, task2]).then(() => {\n this.updateRawSqlAndRefresh();\n });\n }\n\n getTimeColumnSegments() {\n return this.datasource\n .metricFindQuery(this.metaBuilder.buildColumnQuery('time'))\n .then(this.transformToSegments({}))\n .catch(this.handleQueryError.bind(this));\n }\n\n timeColumnChanged(refresh?: boolean) {\n this.target.timeColumn = this.timeColumnSegment.value;\n return this.datasource\n .metricFindQuery(this.metaBuilder.buildDatatypeQuery(this.target.timeColumn))\n .then((result: any) => {\n if (result.length === 1) {\n if (this.target.timeColumnType !== result[0].text) {\n this.target.timeColumnType = result[0].text;\n }\n let partModel;\n if (this.queryModel.hasUnixEpochTimecolumn()) {\n partModel = sqlPart.create({ type: 'macro', name: '$__unixEpochFilter', params: [] });\n } else {\n partModel = sqlPart.create({ type: 'macro', name: '$__timeFilter', params: [] });\n }\n\n if (this.whereParts.length >= 1 && this.whereParts[0].def.type === 'macro') {\n // replace current macro\n this.whereParts[0] = partModel;\n } else {\n this.whereParts.splice(0, 0, partModel);\n }\n }\n\n this.updatePersistedParts();\n if (refresh !== false) {\n this.updateRawSqlAndRefresh();\n }\n });\n }\n\n getMetricColumnSegments() {\n return this.datasource\n .metricFindQuery(this.metaBuilder.buildColumnQuery('metric'))\n .then(this.transformToSegments({ addNone: true }))\n .catch(this.handleQueryError.bind(this));\n }\n\n metricColumnChanged() {\n this.target.metricColumn = this.metricColumnSegment.value;\n this.updateRawSqlAndRefresh();\n }\n\n onDataReceived(dataList: any) {\n this.lastQueryError = undefined;\n this.lastQueryMeta = dataList[0]?.meta;\n }\n\n onDataError(err: any) {\n if (err.data && err.data.results) {\n const queryRes = err.data.results[this.target.refId];\n if (queryRes) {\n this.lastQueryError = queryRes.error;\n }\n }\n }\n\n transformToSegments(config: { addNone?: any; addTemplateVars?: any; templateQuoter?: any }) {\n return (results: any) => {\n const segments = map(results, (segment) => {\n return this.uiSegmentSrv.newSegment({\n value: segment.text,\n expandable: segment.expandable,\n });\n });\n\n if (config.addTemplateVars) {\n for (const variable of this.templateSrv.getVariables()) {\n let value;\n value = '$' + variable.name;\n if (config.templateQuoter && (variable as unknown as VariableWithMultiSupport).multi === false) {\n value = config.templateQuoter(value);\n }\n\n segments.unshift(\n this.uiSegmentSrv.newSegment({\n type: 'template',\n value: value,\n expandable: true,\n })\n );\n }\n }\n\n if (config.addNone) {\n segments.unshift(this.uiSegmentSrv.newSegment({ type: 'template', value: 'none', expandable: true }));\n }\n\n return segments;\n };\n }\n\n findAggregateIndex(selectParts: any) {\n return findIndex(selectParts, (p: any) => p.def.type === 'aggregate' || p.def.type === 'percentile');\n }\n\n findWindowIndex(selectParts: any) {\n return findIndex(selectParts, (p: any) => p.def.type === 'window' || p.def.type === 'moving_window');\n }\n\n addSelectPart(selectParts: any[], item: { value: any }, subItem: { type: any; value: any }) {\n let partType = item.value;\n if (subItem && subItem.type) {\n partType = subItem.type;\n }\n let partModel = sqlPart.create({ type: partType });\n if (subItem) {\n partModel.params[0] = subItem.value;\n }\n let addAlias = false;\n\n switch (partType) {\n case 'column':\n const parts = map(selectParts, (part: any) => {\n return sqlPart.create({ type: part.def.type, params: clone(part.params) });\n });\n this.selectParts.push(parts);\n break;\n case 'percentile':\n case 'aggregate':\n // add group by if no group by yet\n if (this.target.group.length === 0) {\n this.addGroup('time', '$__interval');\n }\n const aggIndex = this.findAggregateIndex(selectParts);\n if (aggIndex !== -1) {\n // replace current aggregation\n selectParts[aggIndex] = partModel;\n } else {\n selectParts.splice(1, 0, partModel);\n }\n if (!find(selectParts, (p: any) => p.def.type === 'alias')) {\n addAlias = true;\n }\n break;\n case 'moving_window':\n case 'window':\n const windowIndex = this.findWindowIndex(selectParts);\n if (windowIndex !== -1) {\n // replace current window function\n selectParts[windowIndex] = partModel;\n } else {\n const aggIndex = this.findAggregateIndex(selectParts);\n if (aggIndex !== -1) {\n selectParts.splice(aggIndex + 1, 0, partModel);\n } else {\n selectParts.splice(1, 0, partModel);\n }\n }\n if (!find(selectParts, (p: any) => p.def.type === 'alias')) {\n addAlias = true;\n }\n break;\n case 'alias':\n addAlias = true;\n break;\n }\n\n if (addAlias) {\n // set initial alias name to column name\n partModel = sqlPart.create({ type: 'alias', params: [selectParts[0].params[0].replace(/\"/g, '')] });\n if (selectParts[selectParts.length - 1].def.type === 'alias') {\n selectParts[selectParts.length - 1] = partModel;\n } else {\n selectParts.push(partModel);\n }\n }\n\n this.updatePersistedParts();\n this.updateRawSqlAndRefresh();\n }\n\n removeSelectPart(selectParts: any, part: { def: { type: string } }) {\n if (part.def.type === 'column') {\n // remove all parts of column unless its last column\n if (this.selectParts.length > 1) {\n const modelsIndex = indexOf(this.selectParts, selectParts);\n this.selectParts.splice(modelsIndex, 1);\n }\n } else {\n const partIndex = indexOf(selectParts, part);\n selectParts.splice(partIndex, 1);\n }\n\n this.updatePersistedParts();\n }\n\n handleSelectPartEvent(selectParts: any, part: { def: any }, evt: { name: any }) {\n switch (evt.name) {\n case 'get-param-options': {\n switch (part.def.type) {\n case 'aggregate':\n return this.datasource\n .metricFindQuery(this.metaBuilder.buildAggregateQuery())\n .then(this.transformToSegments({}))\n .catch(this.handleQueryError.bind(this));\n case 'column':\n return this.datasource\n .metricFindQuery(this.metaBuilder.buildColumnQuery('value'))\n .then(this.transformToSegments({}))\n .catch(this.handleQueryError.bind(this));\n }\n }\n case 'part-param-changed': {\n this.updatePersistedParts();\n this.updateRawSqlAndRefresh();\n break;\n }\n case 'action': {\n this.removeSelectPart(selectParts, part);\n this.updateRawSqlAndRefresh();\n break;\n }\n case 'get-part-actions': {\n return Promise.resolve([{ text: 'Remove', value: 'remove-part' }]);\n }\n }\n }\n\n handleGroupPartEvent(part: any, index: any, evt: { name: any }) {\n switch (evt.name) {\n case 'get-param-options': {\n return this.datasource\n .metricFindQuery(this.metaBuilder.buildColumnQuery())\n .then(this.transformToSegments({}))\n .catch(this.handleQueryError.bind(this));\n }\n case 'part-param-changed': {\n this.updatePersistedParts();\n this.updateRawSqlAndRefresh();\n break;\n }\n case 'action': {\n this.removeGroup(part, index);\n this.updateRawSqlAndRefresh();\n break;\n }\n case 'get-part-actions': {\n return Promise.resolve([{ text: 'Remove', value: 'remove-part' }]);\n }\n }\n }\n\n addGroup(partType: string, value: string) {\n let params = [value];\n if (partType === 'time') {\n params = ['$__interval', 'none'];\n }\n const partModel = sqlPart.create({ type: partType, params: params });\n\n if (partType === 'time') {\n // put timeGroup at start\n this.groupParts.splice(0, 0, partModel);\n } else {\n this.groupParts.push(partModel);\n }\n\n // add aggregates when adding group by\n for (const selectParts of this.selectParts) {\n if (!selectParts.some((part) => part.def.type === 'aggregate')) {\n const aggregate = sqlPart.create({ type: 'aggregate', params: ['avg'] });\n selectParts.splice(1, 0, aggregate);\n if (!selectParts.some((part) => part.def.type === 'alias')) {\n const alias = sqlPart.create({ type: 'alias', params: [selectParts[0].part.params[0]] });\n selectParts.push(alias);\n }\n }\n }\n\n this.updatePersistedParts();\n }\n\n removeGroup(part: { def: { type: string } }, index: number) {\n if (part.def.type === 'time') {\n // remove aggregations\n this.selectParts = map(this.selectParts, (s: any) => {\n return filter(s, (part: any) => {\n if (part.def.type === 'aggregate' || part.def.type === 'percentile') {\n return false;\n }\n return true;\n });\n });\n }\n\n this.groupParts.splice(index, 1);\n this.updatePersistedParts();\n }\n\n handleWherePartEvent(whereParts: any, part: any, evt: any, index: any) {\n switch (evt.name) {\n case 'get-param-options': {\n switch (evt.param.name) {\n case 'left':\n return this.datasource\n .metricFindQuery(this.metaBuilder.buildColumnQuery())\n .then(this.transformToSegments({}))\n .catch(this.handleQueryError.bind(this));\n case 'right':\n if (['int4', 'int8', 'float4', 'float8', 'timestamp', 'timestamptz'].indexOf(part.datatype) > -1) {\n // don't do value lookups for numerical fields\n return Promise.resolve([]);\n } else {\n return this.datasource\n .metricFindQuery(this.metaBuilder.buildValueQuery(part.params[0]))\n .then(\n this.transformToSegments({\n addTemplateVars: true,\n templateQuoter: (v: string) => {\n return this.queryModel.quoteLiteral(v);\n },\n })\n )\n .catch(this.handleQueryError.bind(this));\n }\n case 'op':\n return Promise.resolve(this.uiSegmentSrv.newOperators(this.metaBuilder.getOperators(part.datatype)));\n default:\n return Promise.resolve([]);\n }\n }\n case 'part-param-changed': {\n this.updatePersistedParts();\n this.datasource.metricFindQuery(this.metaBuilder.buildDatatypeQuery(part.params[0])).then((d: any) => {\n if (d.length === 1) {\n part.datatype = d[0].text;\n }\n });\n this.updateRawSqlAndRefresh();\n break;\n }\n case 'action': {\n // remove element\n whereParts.splice(index, 1);\n this.updatePersistedParts();\n this.updateRawSqlAndRefresh();\n break;\n }\n case 'get-part-actions': {\n return Promise.resolve([{ text: 'Remove', value: 'remove-part' }]);\n }\n }\n }\n\n getWhereOptions() {\n const options = [];\n if (this.queryModel.hasUnixEpochTimecolumn()) {\n options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__unixEpochFilter' }));\n } else {\n options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));\n }\n options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));\n return Promise.resolve(options);\n }\n\n addWhereAction(part: any, index: any) {\n switch (this.whereAdd.type) {\n case 'macro': {\n const partModel = sqlPart.create({ type: 'macro', name: this.whereAdd.value, params: [] });\n if (this.whereParts.length >= 1 && this.whereParts[0].def.type === 'macro') {\n // replace current macro\n this.whereParts[0] = partModel;\n } else {\n this.whereParts.splice(0, 0, partModel);\n }\n break;\n }\n default: {\n this.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));\n }\n }\n\n this.updatePersistedParts();\n this.resetPlusButton(this.whereAdd);\n this.updateRawSqlAndRefresh();\n }\n\n getGroupOptions() {\n return this.datasource\n .metricFindQuery(this.metaBuilder.buildColumnQuery('group'))\n .then((tags: any) => {\n const options = [];\n if (!this.queryModel.hasTimeGroup()) {\n options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time($__interval,none)' }));\n }\n for (const tag of tags) {\n options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));\n }\n return options;\n })\n .catch(this.handleQueryError.bind(this));\n }\n\n addGroupAction() {\n this.addGroup(this.groupAdd.type, this.groupAdd.value);\n this.resetPlusButton(this.groupAdd);\n this.updateRawSqlAndRefresh();\n }\n\n handleQueryError(err: any): any[] {\n this.error = err.message || 'Failed to issue metric query';\n return [];\n }\n}\n","import { DataSourcePlugin } from '@grafana/data';\n\nimport { PostgresConfigCtrl } from './config_ctrl';\nimport { PostgresDatasource } from './datasource';\nimport { PostgresQueryCtrl } from './query_ctrl';\nimport { PostgresQuery } from './types';\n\nconst defaultQuery = `SELECT\n extract(epoch from time_column) AS time,\n text_column as text,\n tags_column as tags\nFROM\n metric_table\nWHERE\n $__timeFilter(time_column)\n`;\n\nclass PostgresAnnotationsQueryCtrl {\n static templateUrl = 'partials/annotations.editor.html';\n\n declare annotation: any;\n\n /** @ngInject */\n constructor($scope: any) {\n this.annotation = $scope.ctrl.annotation;\n this.annotation.rawQuery = this.annotation.rawQuery || defaultQuery;\n }\n}\n\nexport const plugin = new DataSourcePlugin<PostgresDatasource, PostgresQuery>(PostgresDatasource)\n .setQueryCtrl(PostgresQueryCtrl)\n .setConfigCtrl(PostgresConfigCtrl)\n .setAnnotationQueryCtrl(PostgresAnnotationsQueryCtrl);\n"],"names":["PostgresConfigCtrl","constructor","$scope","datasourceSrv","name","value","this","current","ctrl","jsonData","sslmode","tlsConfigurationMethod","postgresVersion","showTimescaleDBHelp","autoDetectFeatures","onPasswordReset","createResetHandler","PasswordFieldEnum","onPasswordChange","createChangeHandler","tlsModeMapping","id","loadDatasource","then","ds","getVersion","version","Number","text","getTimescaleDBVersion","length","timescaledb","major","Math","trunc","minor","String","find","postgresVersions","p","push","toggleTimescaleDBHelp","tlsAuth","tlsAuthWithCACert","tlsSkipVerify","PostgresQueryModel","target","templateSrv","scopedVars","format","timeColumn","metricColumn","group","where","type","params","select","rawQuery","interpolateQueryStr","bind","unquoteIdentifier","substring","replace","quoteIdentifier","quoteLiteral","escapeLiteral","hasTimeGroup","g","hasMetricColumn","variable","defaultFormatFn","multi","includeAll","map","join","render","interpolate","rawSql","buildQuery","hasUnixEpochTimecolumn","indexOf","timeColumnType","buildTimeColumn","alias","timeGroup","query","macro","args","buildMetricColumn","buildValueColumns","column","buildValueColumn","aggregate","windows","func","overParts","over","curr","prev","buildWhereClause","conditions","tag","index","buildGroupClause","groupSection","i","part","table","ResponseParser","transformMetricFindResponse","raw","frames","toDataQueryResponse","data","frame","values","textField","fields","f","valueField","get","flatMap","toArray","v","Array","from","Set","options","timeField","Error","timeEndField","tagsField","list","timeEnd","floor","undefined","annotation","time","tags","trim","split","PostgresDatasource","DataSourceWithBackend","instanceSettings","getTemplateSrv","super","queryModel","_map","responseParser","settingsData","interval","timeInterval","interpolateVariablesInQueries","queries","expandedQueries","datasource","getRef","interpolateVariable","filterQuery","hide","applyTemplateVariables","refId","Promise","reject","message","lastValueFrom","getBackendSrv","fetch","url","method","range","valueOf","toString","to","requestId","pipe","async","transformAnnotationResponse","res","metricFindQuery","optionalOptions","getSearchFilterScopedVar","wildcardChar","interpolatedQuery","rsp","catchError","err","of","_metaRequest","testDatasource","status","catch","toTestingStatus","targetContainsTemplate","containsTemplate","PostgresMetaQuery","getOperators","datatype","quoteIdentAsLiteral","findMetricTable","buildSchemaConstraint","buildTableConstraint","includes","parts","buildTableQuery","buildColumnQuery","buildValueQuery","buildDatatypeQuery","buildAggregateQuery","register","SqlPartDef","style","dynamicLookup","defaultParams","label","baseOptions","timescaleOptions","quote","create","def","SqlPart","PostgresQueryCtrl","QueryCtrl","$injector","uiSegmentSrv","panel","metaBuilder","updateProjection","formats","panelCtrl","result","segment","newSegment","tableSegment","html","timeColumnSegment","updateRawSqlAndRefresh","fake","metricColumnSegment","buildSelectMenu","whereAdd","newPlusButton","groupAdd","events","on","PanelEvents","onDataReceived","onDataError","refresh","timescaleAggCheck","aggIndex","findAggregateIndex","selectParts","baseOpts","timescaleOpts","concat","sqlPart","filter","n","whereParts","groupParts","updatePersistedParts","selectMenu","aggregates","submenu","aggregates2","toggleEditorMode","appEvents","ShowConfirmModalEvent","title","text2","icon","yesText","onConfirm","$evalAsync","resetPlusButton","button","plusButton","getTableSegments","transformToSegments","handleQueryError","tableChanged","task1","r","timeColumnChanged","task2","all","getTimeColumnSegments","partModel","splice","getMetricColumnSegments","addNone","metricColumnChanged","dataList","lastQueryError","lastQueryMeta","meta","results","queryRes","error","config","segments","expandable","addTemplateVars","getVariables","templateQuoter","unshift","findIndex","findWindowIndex","addSelectPart","item","subItem","partType","addAlias","clone","addGroup","windowIndex","removeSelectPart","modelsIndex","partIndex","handleSelectPartEvent","evt","resolve","handleGroupPartEvent","removeGroup","some","s","handleWherePartEvent","param","newOperators","d","getWhereOptions","addWhereAction","getGroupOptions","addGroupAction","PostgresAnnotationsQueryCtrl","plugin","DataSourcePlugin","setQueryCtrl","setConfigCtrl","setAnnotationQueryCtrl"],"sourceRoot":""}
|