"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[8651],{38254:(R,L,n)=>{n.r(L),n.d(L,{plugin:()=>Ee});var o=n(40187),g=n(32196),e=n(96540),y=n(40845);function w(){const t=(0,y.of)(N);return e.createElement("div",null,e.createElement("h2",null,"PostgreSQL cheat sheet"),"Time series:",e.createElement("ul",{className:t.ulPadding},e.createElement("li",null,"return column named ",e.createElement("i",null,"time")," (UTC in seconds or timestamp)"),e.createElement("li",null,"return column(s) with numeric datatype as values")),"Optional:",e.createElement("ul",{className:t.ulPadding},e.createElement("li",null,"return column named ",e.createElement("i",null,"metric")," to represent the series name."),e.createElement("li",null,"If multiple value columns are returned the metric column is used as prefix."),e.createElement("li",null,"If no column named metric is found the column name of the value column is used as series name")),e.createElement("p",null,"Resultsets of time series queries need to be sorted by time."),"Table:",e.createElement("ul",{className:t.ulPadding},e.createElement("li",null,"return any set of columns")),"Macros:",e.createElement("ul",{className:t.ulPadding},e.createElement("li",null,'$__time(column) -> column as "time"'),e.createElement("li",null,'$__timeEpoch -> extract(epoch from column) as "time"'),e.createElement("li",null,"$__timeFilter(column) -> column BETWEEN '2017-04-21T05:01:17Z' AND '2017-04-21T05:01:17Z'"),e.createElement("li",null,"$__unixEpochFilter(column) -> column >= 1492750877 AND column <= 1492750877"),e.createElement("li",null,"$__unixEpochNanoFilter(column) -> column >= 1494410783152415214 AND column <= 1494497183142514872"),e.createElement("li",null,"$__timeGroup(column,'5m'[, fillvalue]) -> (extract(epoch from column)/300)::bigint*300 by setting fillvalue grafana will fill in missing values according to the interval fillvalue can be either a literal value, NULL or previous; previous will fill in the previous seen value or NULL if none has been seen yet"),e.createElement("li",null,`$__timeGroupAlias(column,'5m') -> (extract(epoch from column)/300)::bigint*300 AS "time"`),e.createElement("li",null,"$__unixEpochGroup(column,'5m') -> floor(column/300)*300"),e.createElement("li",null,`$__unixEpochGroupAlias(column,'5m') -> floor(column/300)*300 AS "time"`)),e.createElement("p",null,"Example of group by and order by with $__timeGroup:"),e.createElement("pre",null,e.createElement("code",null,"SELECT $__timeGroup(date_time_col, '1h'), sum(value) as value ",e.createElement("br",null),"FROM yourtable",e.createElement("br",null),"GROUP BY time",e.createElement("br",null),"ORDER BY time",e.createElement("br",null))),"Or build your own conditionals using these macros which just return the values:",e.createElement("ul",{className:t.ulPadding},e.createElement("li",null,"$__timeFrom() -> '2017-04-21T05:01:17Z'"),e.createElement("li",null,"$__timeTo() -> '2017-04-21T05:01:17Z'"),e.createElement("li",null,"$__unixEpochFrom() -> 1492750877"),e.createElement("li",null,"$__unixEpochTo() -> 1492750877"),e.createElement("li",null,"$__unixEpochNanoFrom() -> 1494410783152415214"),e.createElement("li",null,"$__unixEpochNanoTo() -> 1494497183142514872")))}function N(t){return{ulPadding:(0,g.css)({margin:t.spacing(1,0),paddingLeft:t.spacing(5)})}}var u=n(71928);const M={dialect:"postgres"};function j(t){return e.createElement(u.e_,{...t,queryHeaderProps:M})}var m=n(22391),h=n(68704),b=n(91062),p=n(46819),x=n(29020),H=n(32264),U=n(82762),f=n(88575),F=n(10354),W=n(9226),S=n(60029),C=n(56034),D=n(14578),G=n(88323),q=n(15292),Y=n(17081),E=(t=>(t.disable="disable",t.require="require",t.verifyCA="verify-ca",t.verifyFull="verify-full",t))(E||{}),B=(t=>(t.filePath="file-path",t.fileContent="file-content",t))(B||{}),K=n(45214),Z=n(17172),X=n(19347),k=n(52622);class _{constructor(a,l,r){this.target=(0,u.To)(a||{refId:"A"}),this.templateSrv=l,this.scopedVars=r}interpolate(){return this.templateSrv?.replace(this.target.rawSql,this.scopedVars,k.$m.SQLString)||""}quoteLiteral(a){return"'"+a.replace(/'/g,"''")+"'"}}function ee(){return"SELECT current_setting('server_version_num')::int/100 as version"}function te(){return"SELECT extversion FROM pg_extension WHERE extname = 'timescaledb'"}function ne(){return`select quote_ident(table_name) as "table" from information_schema.tables
    where quote_ident(table_schema) not in ('information_schema',
                             'pg_catalog',
                             '_timescaledb_cache',
                             '_timescaledb_catalog',
                             '_timescaledb_internal',
                             '_timescaledb_config',
                             'timescaledb_information',
                             'timescaledb_experimental')
      and ${ae()}`}function le(t){return`select quote_ident(column_name) as "column", data_type as "type"
    from information_schema.columns
    where quote_ident(table_name) = ${"'"+t.replace(/'/g,"''")+"'"};
    `}function ae(){return`
          quote_ident(table_schema) IN (
          SELECT
            CASE WHEN trim(s[i]) = '"$user"' THEN user ELSE trim(s[i]) END
          FROM
            generate_series(
              array_lower(string_to_array(current_setting('search_path'),','),1),
              array_upper(string_to_array(current_setting('search_path'),','),1)
            ) as i,
            string_to_array(current_setting('search_path'),',') s
          )`}var re=n(33125);const ie=({getColumns:t,getTables:a})=>(l,r)=>({...r&&(0,re.N)(l,r),tables:{resolve:async()=>await a.current()},columns:{resolve:async i=>await t.current({table:i?.table,refId:"A"})}});async function se(t,a){const l=await t.fields(a);return l.length>0?l.map(r=>({name:r.value,type:r.value,description:r.value})):[]}async function oe(t){return await t.lookup?.()||[]}var ce=n(2543);function ue(t){switch(t){case"boolean":return{raqbFieldType:"boolean",icon:"toggle-off"};case"bit":case"bit varying":case"character":case"character varying":case"text":return{raqbFieldType:"text",icon:"text"};case"smallint":case"integer":case"bigint":case"decimal":case"numeric":case"real":case"double precision":case"serial":case"bigserial":case"smallserial":return{raqbFieldType:"number",icon:"calculator-alt"};case"date":return{raqbFieldType:"date",icon:"clock-nine"};case"time":case"time with time zone":case"time without time zone":case"interval":return{raqbFieldType:"time",icon:"clock-nine"};case"timestamp":case"timestamp with time zone":case"timestamp without time zone":return{raqbFieldType:"datetime",icon:"clock-nine"};default:return{raqbFieldType:"text",icon:"text"}}}function me({sql:t,table:a}){let l="";if(!t||!(0,u.YW)(t.columns))return l;if(l+=(0,u.oF)(t.columns),a&&(l+=`FROM ${a} `),t.whereString&&(l+=`WHERE ${t.whereString} `),t.groupBy?.[0]?.property.name){const r=t.groupBy.map(i=>i.property.name).filter(i=>!(0,ce.isEmpty)(i));l+=`GROUP BY ${r.join(", ")} `}return t.orderBy?.property.name&&(l+=`ORDER BY ${t.orderBy.property.name} `),t.orderBy?.property.name&&t.orderByDirection&&(l+=`${t.orderByDirection} `),t.limit!==void 0&&t.limit>=0&&(l+=`LIMIT ${t.limit} `),l}class J extends u.oK{constructor(a){super(a),this.sqlLanguageDefinition=void 0}getQueryModel(a,l,r){return new _(a,l,r)}async getVersion(){const l=(await this.runSql(ee())).fields.version?.values;return l?l[0].toString():""}async getTimescaleDBVersion(){const l=(await this.runSql(te())).fields.extversion?.values;if(l)return l[0]}async fetchTables(){return(await this.runSql(ne(),{refId:"tables"})).fields.table?.values.flat()??[]}getSqlLanguageDefinition(a){if(this.sqlLanguageDefinition!==void 0)return this.sqlLanguageDefinition;const l={getColumns:{current:r=>se(a,r)},getTables:{current:()=>oe(a)}};return this.sqlLanguageDefinition={id:"pgsql",completionProvider:ie(l),formatter:u.se},this.sqlLanguageDefinition}async fetchFields(a){const{table:l}=a;if(l===void 0)return[];const r=await this.runSql(le(l),{refId:"columns"}),i=[];for(let c=0;c<r.length;c++){const T=r.fields.column.values[c],s=r.fields.type.values[c];i.push({label:T,value:T,type:s,...ue(s)})}return i}getDB(){return this.db!==void 0?this.db:{init:()=>Promise.resolve(!0),datasets:()=>Promise.resolve([]),tables:()=>this.fetchTables(),getEditorLanguageDefinition:()=>this.getSqlLanguageDefinition(this.db),fields:async a=>a?.table?this.fetchFields(a):[],validateQuery:a=>Promise.resolve({isError:!1,isValid:!0,query:a,error:"",rawSql:a.rawSql}),dsID:()=>this.id,toRawSql:me,lookup:async()=>(await this.fetchTables()).map(l=>({name:l,completion:l}))}}}function de({props:t,setVersionOptions:a}){const[l,r]=(0,e.useState)(!1),{options:i,onOptionsChange:c}=t;(0,K.A)(()=>{const T=async()=>{if(l){const s=await(0,X.l)().get(i.name);if(s instanceof J){const V=await s.getVersion(),v=parseInt(V,10);v>=906&&!i.jsonData.timescaledb&&await s.getTimescaleDBVersion()&&(0,m.lO)({options:i,onOptionsChange:c},"timescaledb",!0);const $=Math.trunc(v/100),I=v%100;let A=String($);v<1e3&&(A=String($)+"."+String(I)),z.find(P=>P.value===v)||a(P=>[...P,{label:A,value:v}]),(i.jsonData.postgresVersion===void 0||i.jsonData.postgresVersion!==v)&&(0,m.lO)({options:i,onOptionsChange:c},"postgresVersion",v)}}else{const s=await(0,Z.AI)().put(`/api/datasources/${i.id}`,i);r(!0),(0,m.pN)({options:i,onOptionsChange:c},"version",s.datasource.version)}};fe(i)&&T()},[i,l,a])}function fe(t){return t.url&&t.jsonData.database&&t.user&&(t.secureJsonData?.password||t.secureJsonFields?.password)&&(t.jsonData.sslmode===E.disable||t.jsonData.sslCertFile&&t.jsonData.sslKeyFile&&t.jsonData.sslRootCertFile)&&!t.jsonData.postgresVersion&&!t.readOnly}const z=[{label:"9.0",value:900},{label:"9.1",value:901},{label:"9.2",value:902},{label:"9.3",value:903},{label:"9.4",value:904},{label:"9.5",value:905},{label:"9.6",value:906},{label:"10",value:1e3},{label:"11",value:1100},{label:"12",value:1200},{label:"13",value:1300},{label:"14",value:1400},{label:"15",value:1500}],he=t=>{const[a,l]=(0,e.useState)(z),[r,i]=(0,e.useState)(!0);de({props:t,setVersionOptions:l}),(0,u.nj)(t);const{options:c,onOptionsChange:T}=t,s=c.jsonData,V=()=>{(0,m.QP)(t,"password")},v=[{value:E.disable,label:"disable"},{value:E.require,label:"require"},{value:E.verifyCA,label:"verify-ca"},{value:E.verifyFull,label:"verify-full"}],$=[{value:B.filePath,label:"File system path"},{value:B.fileContent,label:"Certificate content"}],I=O=>Q=>{(0,m.lO)(t,O,Q.value)},A=O=>{(0,m.lO)(t,"timescaledb",O.currentTarget.checked)},P=O=>Q=>{T({...c,[O]:Q.currentTarget.value})},d=40;return e.createElement(e.Fragment,null,e.createElement(h.I,{dataSourceName:"Postgres",docsLink:"https://grafana.com/docs/grafana/latest/datasources/postgres/",hasRequiredFields:!0}),e.createElement(u.cG,null),e.createElement(U.S,{collapsible:!0,label:"User Permissions",isOpen:r,onToggle:()=>i(O=>!O)},"The database user should only be granted SELECT permissions on the specified database & tables you want to query. ",e.createElement("br",null),"Grafana does not validate that queries are safe so queries can contain any SQL statement. For example, statements like ",e.createElement("code",null,"DELETE FROM user;")," and ",e.createElement("code",null,"DROP TABLE user;")," would be executed. ",e.createElement("br",null),"To protect against this we ",e.createElement("strong",null,"Highly")," recommend you create a specific PostgreSQL user with restricted permissions. Check out the docs for more information."),e.createElement(u.cG,null),e.createElement(b.A,{title:"Connection"},e.createElement(f.D,{label:"Host URL",required:!0},e.createElement(F.p,{width:d,name:"host",type:"text",value:c.url||"",placeholder:"localhost:5432",onChange:P("url")})),e.createElement(f.D,{label:"Database name",required:!0},e.createElement(F.p,{width:d,name:"database",value:s.database||"",placeholder:"Database",onChange:(0,m.PG)(t,"database")}))),e.createElement(u.cG,null),e.createElement(b.A,{title:"Authentication"},e.createElement(f.D,{label:"Username",required:!0},e.createElement(F.p,{width:d,value:c.user||"",placeholder:"Username",onChange:P("user")})),e.createElement(f.D,{label:"Password",required:!0},e.createElement(W.L4,{width:d,placeholder:"Password",isConfigured:c.secureJsonFields&&c.secureJsonFields.password,onReset:V,onBlur:(0,m.mn)(t,"password")})),e.createElement(f.D,{label:e.createElement(S.J,null,e.createElement(p.B,{gap:.5},e.createElement("span",null,"TLS/SSL Mode"),e.createElement(C.m,{content:e.createElement("span",null,"This option determines whether or with what priority a secure TLS/SSL TCP/IP connection will be negotiated with the server")},e.createElement(D.I,{name:"info-circle",size:"sm"}))))},e.createElement(G.l6,{options:v,value:s.sslmode||E.verifyFull,onChange:I("sslmode"),width:d})),c.jsonData.sslmode!==E.disable?e.createElement(f.D,{label:e.createElement(S.J,null,e.createElement(p.B,{gap:.5},e.createElement("span",null,"TLS/SSL Method"),e.createElement(C.m,{content:e.createElement("span",null,"This option determines how TLS/SSL certifications are configured. Selecting"," ",e.createElement("i",null,"File system path")," will allow you to configure certificates by specifying paths to existing certificates on the local file system where Grafana is running. Be sure that the file is readable by the user executing the Grafana process.",e.createElement("br",null),e.createElement("br",null),"Selecting ",e.createElement("i",null,"Certificate content")," will allow you to configure certificates by specifying its content. The content will be stored encrypted in Grafana's database. When connecting to the database the certificates will be written as files to Grafana's configured data path on the local file system.")},e.createElement(D.I,{name:"info-circle",size:"sm"}))))},e.createElement(G.l6,{options:$,value:s.tlsConfigurationMethod||B.filePath,onChange:I("tlsConfigurationMethod"),width:d})):null),s.sslmode!==E.disable?e.createElement(e.Fragment,null,e.createElement(u.cG,null),e.createElement(b.A,{title:"TLS/SSL Auth Details"},s.tlsConfigurationMethod===B.fileContent?e.createElement(u.X3,{showCACert:s.sslmode===E.verifyCA||s.sslmode===E.verifyFull,editorProps:t,labelWidth:d}):e.createElement(e.Fragment,null,e.createElement(f.D,{label:e.createElement(S.J,null,e.createElement(p.B,{gap:.5},e.createElement("span",null,"TLS/SSL Root Certificate"),e.createElement(C.m,{content:e.createElement("span",null,"If the selected TLS/SSL mode requires a server root certificate, provide the path to the file here.")},e.createElement(D.I,{name:"info-circle",size:"sm"}))))},e.createElement(F.p,{value:s.sslRootCertFile||"",onChange:(0,m.PG)(t,"sslRootCertFile"),placeholder:"TLS/SSL root cert file",width:d})),e.createElement(f.D,{label:e.createElement(S.J,null,e.createElement(p.B,{gap:.5},e.createElement("span",null,"TLS/SSL Client Certificate"),e.createElement(C.m,{content:e.createElement("span",null,"To authenticate with an TLS/SSL client certificate, provide the path to the file here. Be sure that the file is readable by the user executing the grafana process.")},e.createElement(D.I,{name:"info-circle",size:"sm"}))))},e.createElement(F.p,{value:s.sslCertFile||"",onChange:(0,m.PG)(t,"sslCertFile"),placeholder:"TLS/SSL client cert file",width:d})),e.createElement(f.D,{label:e.createElement(S.J,null,e.createElement(p.B,{gap:.5},e.createElement("span",null,"TLS/SSL Client Key"),e.createElement(C.m,{content:e.createElement("span",null,"To authenticate with a client TLS/SSL certificate, provide the path to the corresponding key file here. Be sure that the file is ",e.createElement("i",null,"only")," readable by the user executing the grafana process.")},e.createElement(D.I,{name:"info-circle",size:"sm"}))))},e.createElement(F.p,{value:s.sslKeyFile||"",onChange:(0,m.PG)(t,"sslKeyFile"),placeholder:"TLS/SSL client key file",width:d}))))):null,e.createElement(u.cG,null),e.createElement(b.A,{title:"Additional settings",isCollapsible:!0},e.createElement(x.I,{title:"PostgreSQL Options"},e.createElement(f.D,{label:e.createElement(S.J,null,e.createElement(p.B,{gap:.5},e.createElement("span",null,"Version"),e.createElement(C.m,{content:e.createElement("span",null,"This option controls what functions are available in the PostgreSQL query builder")},e.createElement(D.I,{name:"info-circle",size:"sm"}))))},e.createElement(G.l6,{value:s.postgresVersion||903,onChange:I("postgresVersion"),options:a,width:d})),e.createElement(f.D,{label:e.createElement(S.J,null,e.createElement(p.B,{gap:.5},e.createElement("span",null,"Min time interval"),e.createElement(C.m,{content:e.createElement("span",null,"A lower limit for the auto group by time interval. Recommended to be set to write frequency, for example",e.createElement("code",null,"1m")," if your data is written every minute.")},e.createElement(D.I,{name:"info-circle",size:"sm"}))))},e.createElement(F.p,{placeholder:"1m",value:s.timeInterval||"",onChange:(0,m.PG)(t,"timeInterval"),width:d})),e.createElement(f.D,{label:e.createElement(S.J,null,e.createElement(p.B,{gap:.5},e.createElement("span",null,"TimescaleDB"),e.createElement(C.m,{content:e.createElement("span",null,"TimescaleDB is a time-series database built as a PostgreSQL extension. If enabled, Grafana will use",e.createElement("code",null,"time_bucket")," in the ",e.createElement("code",null,"$__timeGroup")," macro and display TimescaleDB specific aggregate functions in the query builder.")},e.createElement(D.I,{name:"info-circle",size:"sm"}))))},e.createElement(q.d,{value:s.timescaledb||!1,onChange:A,width:d}))),e.createElement(u.jN,{options:c,onOptionsChange:T}),H.$.secureSocksDSProxyEnabled&&e.createElement(Y.Y,{options:c,onOptionsChange:T})))},Ee=new o.tD(J).setQueryEditor(j).setQueryEditorHelp(w).setConfigEditor(he)},72774:R=>{R.exports=function L(n,o){if(n===o)return!0;if(n&&o&&typeof n=="object"&&typeof o=="object"){if(n.constructor!==o.constructor)return!1;var g,e,y;if(Array.isArray(n)){if(g=n.length,g!=o.length)return!1;for(e=g;e--!==0;)if(!L(n[e],o[e]))return!1;return!0}if(n.constructor===RegExp)return n.source===o.source&&n.flags===o.flags;if(n.valueOf!==Object.prototype.valueOf)return n.valueOf()===o.valueOf();if(n.toString!==Object.prototype.toString)return n.toString()===o.toString();if(y=Object.keys(n),g=y.length,g!==Object.keys(o).length)return!1;for(e=g;e--!==0;)if(!Object.prototype.hasOwnProperty.call(o,y[e]))return!1;for(e=g;e--!==0;){var w=y[e];if(!(w==="_owner"&&n.$$typeof)&&!L(n[w],o[w]))return!1}return!0}return n!==n&&o!==o}},45214:(R,L,n)=>{n.d(L,{A:()=>m});var o=n(96540),g=function(h){return h!==Object(h)},e=function(h,b,p){var x=(0,o.useRef)(void 0);(!x.current||!p(b,x.current))&&(x.current=b),(0,o.useEffect)(h,x.current)};const y=e;var w=n(72774),N=n.n(w);const u=N();var M=function(h){return h!==Object(h)},j=function(h,b){y(h,b,u)};const m=j}}]);

//# sourceMappingURL=postgresPlugin.f88c598bae2653ae177b.js.map