ALTER TABLE users ADD COLUMN welcome_closed integer;--omnidb--

CREATE TABLE mon_units_temp AS
SELECT unit_id,
       dbt_st_name,
       script_chart,
       script_data,
       type,
       title,
       is_default,
       user_id,
       interval
FROM mon_units;--omnidb--

CREATE TABLE units_users_connections_temp AS
SELECT uuc_id,
       unit_id,
       user_id,
       conn_id,
       interval,
       plugin_name
FROM units_users_connections;--omnidb--

DELETE FROM mon_units;--omnidb--
DELETE FROM units_users_connections;--omnidb--

INSERT INTO mon_units VALUES(1,'postgresql',replace('max_connections = connection.ExecuteScalar(''SHOW max_connections'')\n\nresult = {\n    "type": "line",\n    "data": None,\n    "options": {\n        "responsive": True,\n        "title":{\n            "display":True,\n            "text":"Backends (max_connections: " + str(max_connections) + ")"\n        },\n        "tooltips": {\n            "mode": "index",\n            "intersect": False\n        },\n        "hover": {\n            "mode": "nearest",\n            "intersect": True\n        },\n        "scales": {\n            "xAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Time"\n                }\n            }],\n            "yAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Value"\n                },\n                "ticks": {\n                    "beginAtZero": True,\n                    "max": int(max_connections)\n                }\n            }]\n        }\n    }\n}\n','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\ndatabases = connection.Query(''''''\n    SELECT d.datname,\n           s.numbackends\n    FROM pg_stat_database s\n    INNER JOIN pg_database d\n    ON d.oid = s.datid\n    WHERE NOT d.datistemplate\n'''''')\n\ndatasets = []\nfor db in databases.Rows:\n    color = "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")"\n    datasets.append({\n            "label": db[''datname''],\n            "fill": False,\n            "backgroundColor": color,\n            "borderColor": color,\n            "lineTension": 0,\n            "pointRadius": 1,\n            "borderWidth": 1,\n            "data": [db["numbackends"]]\n        })\n\nresult = {\n    "labels": [datetime.now().strftime(''%H:%M:%S'')],\n    "datasets": datasets\n}\n','\n',char(10)),'chart_append','Backends',1,NULL,5);--omnidb--
INSERT INTO mon_units VALUES(2,'postgresql',replace('total_size = connection.ExecuteScalar(''''''\n    SELECT round(sum(pg_catalog.pg_database_size(datname)/1048576.0),2)\n    FROM pg_catalog.pg_database\n    WHERE NOT datistemplate\n'''''')\n\nresult = {\n    "type": "line",\n    "data": None,\n    "options": {\n        "responsive": True,\n        "title":{\n            "display":True,\n            "text":"Database Size (Total: " + str(total_size) + " MB)"\n        },\n        "tooltips": {\n            "mode": "index",\n            "intersect": False\n        },\n        "hover": {\n            "mode": "nearest",\n            "intersect": True\n        },\n        "scales": {\n            "xAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Time"\n                }\n            }],\n            "yAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Size (MB)"\n                }\n            }]\n        }\n    }\n}\n','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\ndatabases = connection.Query(''''''\n    SELECT datname AS datname,\n           round(pg_catalog.pg_database_size(datname)/1048576.0,2) AS size\n    FROM pg_catalog.pg_database\n    WHERE NOT datistemplate\n    ORDER BY\n        CASE WHEN pg_catalog.has_database_privilege(datname, ''CONNECT'')\n             THEN pg_catalog.pg_database_size(datname)\n             ELSE NULL\n        END DESC\n'''''')\n\ndatasets = []\nfor db in databases.Rows:\n    color = "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")"\n    datasets.append({\n            "label": db[''datname''],\n            "fill": False,\n            "backgroundColor": color,\n            "borderColor": color,\n            "lineTension": 0,\n            "pointRadius": 1,\n            "borderWidth": 1,\n            "data": [db["size"]]\n        })\n\ntotal_size = connection.ExecuteScalar(''''''\n    SELECT round(sum(pg_catalog.pg_database_size(datname)/1048576.0),2)\n    FROM pg_catalog.pg_database\n    WHERE NOT datistemplate\n'''''')\n\nresult = {\n    "labels": [datetime.now().strftime(''%H:%M:%S'')],\n    "datasets": datasets,\n    "title": "Database Size (Total: " + str(total_size) + " MB)"\n}\n','\n',char(10)),'chart_append','Database Size',1,NULL,30);--omnidb--
INSERT INTO mon_units VALUES(3,'postgresql',replace('result = {\n    "type": "line",\n    "data": None,\n    "options": {\n        "responsive": True,\n        "title":{\n            "display":True,\n            "text":"Size: Top 5 Tables"\n        },\n        "tooltips": {\n            "mode": "index",\n            "intersect": False\n        },\n        "hover": {\n            "mode": "nearest",\n            "intersect": True\n        },\n        "scales": {\n            "xAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Time"\n                }\n            }],\n            "yAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Size (MB)"\n                }\n            }]\n        }\n    }\n}\n','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\ntables = connection.Query(''''''\n    SELECT nspname || ''.'' || relname AS relation,\n           round(pg_relation_size(c.oid)/1048576.0,2) AS size\n    FROM pg_class c\n    LEFT JOIN pg_namespace n ON (n.oid = c.relnamespace)\n    WHERE nspname NOT IN (''pg_catalog'', ''information_schema'')\n      AND c.relkind <> ''i''\n      AND nspname !~ ''^pg_toast''\n    ORDER BY pg_total_relation_size(c.oid) DESC\n    LIMIT 5\n'''''')\n\ndatasets = []\nfor table in tables.Rows:\n    color = "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")"\n    datasets.append({\n            "label": table[''relation''],\n            "fill": False,\n            "backgroundColor": color,\n            "borderColor": color,\n            "lineTension": 0,\n            "pointRadius": 1,\n            "borderWidth": 1,\n            "data": [table["size"]]\n        })\n\nresult = {\n    "labels": [datetime.now().strftime(''%H:%M:%S'')],\n    "datasets": datasets\n}\n','\n',char(10)),'chart_append','Size: Top 5 Tables',0,NULL,15);--omnidb--
INSERT INTO mon_units VALUES(4,'postgresql','',replace('from datetime import datetime\n\ndata = connection.Query(''''''\n    SELECT *\n    FROM pg_stat_activity\n'''''')\n\nresult = {\n    "columns": data.Columns,\n    "data": data.Rows\n}\n','\n',char(10)),'grid','Activity',0,NULL,15);--omnidb--
INSERT INTO mon_units VALUES(5,'postgresql','',replace('from datetime import datetime\n\ndata = connection.Query(''''''\n    SELECT z.current_database,z.schemaname,z.tablename, pg_size_pretty(sum_wasted) AS total_bloat\n    FROM (\n    SELECT y.schemaname, y.tablename, y.current_database, sum(wastedbytes+wastedibytes)::bigint AS sum_wasted\n    FROM (\n    SELECT current_database,schemaname, tablename, tbloat, wastedbytes, iname, ibloat, wastedibytes AS wastedibytes\n    FROM (\n    SELECT\n      current_database(), schemaname, tablename, /*reltuples::bigint, relpages::bigint, otta,*/\n      ROUND((CASE WHEN otta=0 THEN 0.0 ELSE sml.relpages::FLOAT/otta END)::NUMERIC,1) AS tbloat,\n      CASE WHEN relpages < otta THEN 0 ELSE bs*(sml.relpages-otta)::BIGINT END AS wastedbytes,\n      iname, /*ituples::bigint, ipages::bigint, iotta,*/\n      ROUND((CASE WHEN iotta=0 OR ipages=0 THEN 0.0 ELSE ipages::FLOAT/iotta END)::NUMERIC,1) AS ibloat,\n      CASE WHEN ipages < iotta THEN 0 ELSE bs*(ipages-iotta) END AS wastedibytes\n    FROM (\n      SELECT\n        schemaname, tablename, cc.reltuples, cc.relpages, bs,\n        CEIL((cc.reltuples*((datahdr+ma-\n          (CASE WHEN datahdr%ma=0 THEN ma ELSE datahdr%ma END))+nullhdr2+4))/(bs-20::FLOAT)) AS otta,\n        COALESCE(c2.relname,''?'') AS iname, COALESCE(c2.reltuples,0) AS ituples, COALESCE(c2.relpages,0) AS ipages,\n        COALESCE(CEIL((c2.reltuples*(datahdr-12))/(bs-20::FLOAT)),0) AS iotta -- very rough approximation, assumes all cols\n      FROM (\n        SELECT\n          ma,bs,schemaname,tablename,\n          (datawidth+(hdr+ma-(CASE WHEN hdr%ma=0 THEN ma ELSE hdr%ma END)))::NUMERIC AS datahdr,\n          (maxfracsum*(nullhdr+ma-(CASE WHEN nullhdr%ma=0 THEN ma ELSE nullhdr%ma END))) AS nullhdr2\n        FROM (\n          SELECT\n            schemaname, tablename, hdr, ma, bs,\n            SUM((1-null_frac)*avg_width) AS datawidth,\n            MAX(null_frac) AS maxfracsum,\n            hdr+(\n              SELECT 1+COUNT(*)/8\n              FROM pg_stats s2\n              WHERE null_frac<>0 AND s2.schemaname = s.schemaname AND s2.tablename = s.tablename\n            ) AS nullhdr\n          FROM pg_stats s, (\n            SELECT\n              (SELECT current_setting(''block_size'')::NUMERIC) AS bs,\n              CASE WHEN SUBSTRING(v,12,3) IN (''8.0'',''8.1'',''8.2'') THEN 27 ELSE 23 END AS hdr,\n              CASE WHEN v ~ ''mingw32'' THEN 8 ELSE 4 END AS ma\n            FROM (SELECT version() AS v) AS foo\n          ) AS constants\n          GROUP BY 1,2,3,4,5\n        ) AS foo\n      ) AS rs\n      JOIN pg_class cc ON cc.relname = rs.tablename\n      JOIN pg_namespace nn ON cc.relnamespace = nn.oid AND nn.nspname = rs.schemaname AND nn.nspname <> ''information_schema''\n      LEFT JOIN pg_index i ON indrelid = cc.oid\n      LEFT JOIN pg_class c2 ON c2.oid = i.indexrelid\n    ) AS sml) x) y\n    GROUP BY y.schemaname, y.tablename, y.current_database) z\n    ORDER BY z.sum_wasted DESC\n    LIMIT 20\n'''''')\n\nresult = {\n    "columns": data.Columns,\n    "data": data.Rows\n}','\n',char(10)),'grid','Bloat: Top 20 Tables',0,NULL,30);--omnidb--
INSERT INTO mon_units VALUES(6,'postgresql',replace('max_connections = connection.ExecuteScalar(''SHOW max_connections'')\n\nresult = {\n    "type": "pie",\n    "data": None,\n    "options": {\n        "responsive": True,\n        "title":{\n            "display":True,\n            "text":"Backends (max_connections: " + str(max_connections) + ")"\n        }\n    }\n}\n','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\ndatabases = connection.Query(''''''\n    SELECT d.datname,\n           s.numbackends\n    FROM pg_stat_database s\n    INNER JOIN pg_database d\n    ON d.oid = s.datid\n    WHERE NOT d.datistemplate\n'''''')\n\ndata = []\ncolor = []\nlabel = []\n\nfor db in databases.Rows:\n    data.append(db["numbackends"])\n    color.append("rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")")\n    label.append(db["datname"])\n\nresult = {\n    "labels": label,\n    "datasets": [\n        {\n            "data": data,\n            "backgroundColor": color,\n            "label": "Dataset 1"\n        }\n    ]\n}\n','\n',char(10)),'chart','Backends',1,NULL,15);--omnidb--
INSERT INTO mon_units VALUES(7,'postgresql',replace('result = {\n    "type": "line",\n    "data": None,\n    "options": {\n        "responsive": True,\n        "title":{\n            "display":True,\n            "text":"CPU Usage"\n        },\n        "tooltips": {\n            "mode": "index",\n            "intersect": False\n        },\n        "hover": {\n            "mode": "nearest",\n            "intersect": True\n        },\n        "scales": {\n            "xAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Time"\n                }\n            }],\n            "yAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Value",\n                },\n                "ticks": {\n                    "beginAtZero": True,\n                    "max": 100\n                }\n            }]\n        }\n    }\n}\n','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\ntry:\n    cpu_data = connection.Query(''''''\n        create temporary table tabela (c1 text);\n        copy tabela from program ''mpstat -P ALL 1 1 | grep "Average:" | tail -n +2 | tr -s " " | cut -f2,3 -d" "'';\n        select * from tabela;\n    '''''')\nexcept:\n    raise Exception(''This chart can not be executed in a standby server.'')\n\nif len(cpu_data.Rows) == 0:\n    raise Exception(''This chart can only be executed in a Linux server.'')\n\ndatasets = []\nfor cpu in cpu_data.Rows:\n    if cpu!='''':\n        cpu_split = cpu[0].split('' '')\n        color = "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")"\n        datasets.append({\n            "label": cpu_split[0],\n            "fill": False,\n            "backgroundColor": color,\n            "borderColor": color,\n            "lineTension": 0,\n            "pointRadius": 1,\n            "borderWidth": 1,\n            "data": [cpu_split[1]]\n        })\n\nresult = {\n    "labels": [datetime.now().strftime(''%H:%M:%S'')],\n    "datasets": datasets\n}\n','\n',char(10)),'chart_append','CPU Usage',0,NULL,10);--omnidb--
INSERT INTO mon_units VALUES(8,'postgresql',replace('result = {\n    "type": "line",\n    "data": None,\n    "options": {\n        "responsive": True,\n        "title":{\n            "display":True,\n            "text":"Locks"\n        },\n        "tooltips": {\n            "mode": "index",\n            "intersect": False\n        },\n        "hover": {\n            "mode": "nearest",\n            "intersect": True\n        },\n        "scales": {\n            "xAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Time"\n                }\n            }],\n            "yAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Num locks"\n                }\n            }]\n        }\n    }\n}\n','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\nlocks = connection.Query(''''''\n    SELECT mode,\n           count(*) as count\n    FROM pg_locks\n    GROUP BY mode\n'''''')\n\ndatasets = []\nfor lock in locks.Rows:\n    color = "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")"\n    datasets.append({\n            "label": lock[''mode''],\n            "fill": False,\n            "backgroundColor": color,\n            "borderColor": color,\n            "lineTension": 0,\n            "pointRadius": 1,\n            "borderWidth": 1,\n            "data": [lock["count"]]\n        })\n\nresult = {\n    "labels": [datetime.now().strftime(''%H:%M:%S'')],\n    "datasets": datasets\n}\n','\n',char(10)),'chart_append','Locks',1,NULL,15);--omnidb--
INSERT INTO mon_units VALUES(9,'postgresql','',replace('data = connection.Query(''''''\n    SELECT pg_is_in_recovery() as "In Recovery"\n'''''')\n\nresult = {\n    "columns": data.Columns,\n    "data": data.Rows\n}','\n',char(10)),'grid','In Recovery',0,NULL,120);--omnidb--
INSERT INTO mon_units VALUES(10,'postgresql',replace('total_size = connection.ExecuteScalar(''''''\n    SELECT round(sum(pg_catalog.pg_database_size(datname)/1048576.0),2)\n    FROM pg_catalog.pg_database\n    WHERE NOT datistemplate\n'''''')\n\nresult = {\n    "type": "pie",\n    "data": None,\n    "options": {\n        "responsive": True,\n        "title":{\n            "display":True,\n            "text":"Database Size (Total: " + str(total_size) + " MB)"\n        }\n    }\n}\n','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\ndatabases = connection.Query(''''''\n    SELECT d.datname AS datname,\n           round(pg_catalog.pg_database_size(d.datname)/1048576.0,2) AS size\n    FROM pg_catalog.pg_database d\n    WHERE d.datname not in (''template0'',''template1'')\n'''''')\n\ndata = []\ncolor = []\nlabel = []\n\nfor db in databases.Rows:\n    data.append(db["size"])\n    color.append("rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")")\n    label.append(db["datname"])\n\ntotal_size = connection.ExecuteScalar(''''''\n    SELECT round(sum(pg_catalog.pg_database_size(datname)/1048576.0),2)\n    FROM pg_catalog.pg_database\n    WHERE NOT datistemplate\n'''''')\n\nresult = {\n    "labels": label,\n    "datasets": [\n        {\n            "data": data,\n            "backgroundColor": color,\n            "label": "Dataset 1"\n        }\n    ],\n    "title": "Database Size (Total: " + str(total_size) + " MB)"\n}\n','\n',char(10)),'chart','Database Size',1,NULL,30);--omnidb--
INSERT INTO mon_units VALUES(11,'postgresql',replace('result = {\n    "type": "line",\n    "data": None,\n    "options": {\n        "responsive": True,\n        "title":{\n            "display":True,\n            "text":"Bloat: Top 5 Tables"\n        },\n        "tooltips": {\n            "mode": "index",\n            "intersect": False\n        },\n        "hover": {\n            "mode": "nearest",\n            "intersect": True\n        },\n        "scales": {\n            "xAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Time"\n                }\n            }],\n            "yAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Size (MB)"\n                }\n            }]\n        }\n    }\n}\n','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\ntables = connection.Query(''''''\n    SELECT z.schemaname || ''.'' || z.tablename as relation, sum_wasted/1048576.0 AS size\n    FROM (\n    SELECT y.schemaname, y.tablename, y.current_database, wastedbytes + sum(wastedibytes)::bigint AS sum_wasted\n    FROM (\n    SELECT current_database,schemaname, tablename, tbloat, wastedbytes, iname, ibloat, wastedibytes AS wastedibytes\n    FROM (\n    SELECT\n      current_database(), schemaname, tablename, /*reltuples::bigint, relpages::bigint, otta,*/\n      ROUND((CASE WHEN otta=0 THEN 0.0 ELSE sml.relpages::FLOAT/otta END)::NUMERIC,1) AS tbloat,\n      CASE WHEN relpages < otta THEN 0 ELSE bs*(sml.relpages-otta)::BIGINT END AS wastedbytes,\n      iname, /*ituples::bigint, ipages::bigint, iotta,*/\n      ROUND((CASE WHEN iotta=0 OR ipages=0 THEN 0.0 ELSE ipages::FLOAT/iotta END)::NUMERIC,1) AS ibloat,\n      CASE WHEN ipages < iotta THEN 0 ELSE bs*(ipages-iotta) END AS wastedibytes\n    FROM (\n      SELECT\n        schemaname, tablename, cc.reltuples, cc.relpages, bs,\n        CEIL((cc.reltuples*((datahdr+ma-\n          (CASE WHEN datahdr%ma=0 THEN ma ELSE datahdr%ma END))+nullhdr2+4))/(bs-20::FLOAT)) AS otta,\n        COALESCE(c2.relname,''?'') AS iname, COALESCE(c2.reltuples,0) AS ituples, COALESCE(c2.relpages,0) AS ipages,\n        COALESCE(CEIL((c2.reltuples*(datahdr-12))/(bs-20::FLOAT)),0) AS iotta -- very rough approximation, assumes all cols\n      FROM (\n        SELECT\n          ma,bs,schemaname,tablename,\n          (datawidth+(hdr+ma-(CASE WHEN hdr%ma=0 THEN ma ELSE hdr%ma END)))::NUMERIC AS datahdr,\n          (maxfracsum*(nullhdr+ma-(CASE WHEN nullhdr%ma=0 THEN ma ELSE nullhdr%ma END))) AS nullhdr2\n        FROM (\n          SELECT\n            schemaname, tablename, hdr, ma, bs,\n            SUM((1-null_frac)*avg_width) AS datawidth,\n            MAX(null_frac) AS maxfracsum,\n            hdr+(\n              SELECT 1+COUNT(*)/8\n              FROM pg_stats s2\n              WHERE null_frac<>0 AND s2.schemaname = s.schemaname AND s2.tablename = s.tablename\n            ) AS nullhdr\n          FROM pg_stats s, (\n            SELECT\n              (SELECT current_setting(''block_size'')::NUMERIC) AS bs,\n              CASE WHEN SUBSTRING(v,12,3) IN (''8.0'',''8.1'',''8.2'') THEN 27 ELSE 23 END AS hdr,\n              CASE WHEN v ~ ''mingw32'' THEN 8 ELSE 4 END AS ma\n            FROM (SELECT version() AS v) AS foo\n          ) AS constants\n          GROUP BY 1,2,3,4,5\n        ) AS foo\n      ) AS rs\n      JOIN pg_class cc ON cc.relname = rs.tablename\n      JOIN pg_namespace nn ON cc.relnamespace = nn.oid AND nn.nspname = rs.schemaname AND nn.nspname <> ''information_schema''\n      LEFT JOIN pg_index i ON indrelid = cc.oid\n      LEFT JOIN pg_class c2 ON c2.oid = i.indexrelid\n    ) AS sml) x) y\n    GROUP BY y.schemaname, y.tablename, y.current_database, y.wastedbytes) z\n    ORDER BY z.sum_wasted DESC\n    LIMIT 5\n'''''')\n\ndatasets = []\nfor table in tables.Rows:\n    color = "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")"\n    datasets.append({\n            "label": table[''relation''],\n            "fill": False,\n            "backgroundColor": color,\n            "borderColor": color,\n            "lineTension": 0,\n            "pointRadius": 1,\n            "borderWidth": 1,\n            "data": [table["size"]]\n        })\n\nresult = {\n    "labels": [datetime.now().strftime(''%H:%M:%S'')],\n    "datasets": datasets\n}\n','\n',char(10)),'chart_append','Bloat: Top 5 Tables',0,NULL,45);--omnidb--
INSERT INTO mon_units VALUES(12,'postgresql','',replace('from datetime import datetime\n\ndata = connection.Query(''''''\n    SELECT relname as table_name,\n           pg_size_pretty(pg_table_size(oid)) as table_size,\n           age(relfrozenxid) as xid_age,\n           current_setting(''autovacuum_freeze_max_age'')::integer as max_age,\n           round(age(relfrozenxid)/(current_setting(''autovacuum_freeze_max_age'')::integer)::numeric*100.0,4) as perc\n    FROM pg_class\n    WHERE relkind in (''r'', ''t'')\n    ORDER BY age(relfrozenxid) DESC\n    LIMIT 20;\n'''''')\n\nresult = {\n    "columns": data.Columns,\n    "data": data.Rows\n}\n','\n',char(10)),'grid','AutovacFreeze: Top 20 Tables',0,NULL,60);--omnidb--
INSERT INTO mon_units VALUES(13,'postgresql',replace('result = {\n    "type": "line",\n    "data": None,\n    "options": {\n        "responsive": True,\n        "title":{\n            "display":True,\n            "text":"Master: Replication Lag"\n        },\n        "tooltips": {\n            "mode": "index",\n            "intersect": False\n        },\n        "hover": {\n            "mode": "nearest",\n            "intersect": True\n        },\n        "scales": {\n            "xAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Time"\n                }\n            }],\n            "yAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Size (MB)"\n                },\n                "ticks": {\n                    "beginAtZero": True\n                }\n            }]\n        }\n    }\n}\n','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\nreplags = connection.Query(''''''\n    CREATE TEMPORARY TABLE omnidb_monitor_result (result1 TEXT, result2 TEXT);\n    DO $$\n    BEGIN\n        IF current_setting(''server_version_num'')::integer < 100000 THEN\n            EXECUTE ''INSERT INTO omnidb_monitor_result SELECT client_addr || ''''-'''' || application_name as standby,''\n                    ''round(pg_xlog_location_diff(pg_current_xlog_location(),replay_location)/1048576.0,2) as lag ''\n                    ''FROM pg_stat_replication'';\n        ELSE\n            EXECUTE ''INSERT INTO omnidb_monitor_result SELECT client_addr || ''''-'''' || application_name as standby,''\n                ''round(pg_wal_lsn_diff(pg_current_wal_lsn(),replay_lsn)/1048576.0,2) as lag ''\n                ''FROM pg_stat_replication'';\n        END IF;\n    END$$;\n    SELECT result1 as standby, result2 as lag FROM omnidb_monitor_result;\n'''''')\n\ndatasets = []\nfor replag in replags.Rows:\n    color = "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")"\n    datasets.append({\n            "label": replag[''standby''],\n            "fill": False,\n            "backgroundColor": color,\n            "borderColor": color,\n            "lineTension": 0,\n            "pointRadius": 1,\n            "borderWidth": 1,\n            "data": [replag[''lag'']]\n        })\n\nresult = {\n    "labels": [datetime.now().strftime(''%H:%M:%S'')],\n    "datasets": datasets\n}\n','\n',char(10)),'chart_append','Master: Replication Lag',0,NULL,15);--omnidb--
INSERT INTO mon_units VALUES(14,'postgresql',replace('result = {\n    "type": "line",\n    "data": None,\n    "options": {\n        "responsive": True,\n        "title":{\n            "display":True,\n            "text":"Standby: Replication Lag (Size)"\n        },\n        "tooltips": {\n            "mode": "index",\n            "intersect": False\n        },\n        "hover": {\n            "mode": "nearest",\n            "intersect": True\n        },\n        "scales": {\n            "xAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Time"\n                }\n            }],\n            "yAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Size (MB)"\n                },\n                "ticks": {\n                    "beginAtZero": True\n                }\n            }]\n        }\n    }\n}\n','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\nreplags = connection.Query(''''''\n    CREATE TEMPORARY TABLE omnidb_monitor_result (result TEXT);\n    DO $$DECLARE r record;\n    BEGIN\n        IF current_setting(''server_version_num'')::integer < 100000 THEN\n            EXECUTE ''INSERT INTO omnidb_monitor_result ''\n                    ''SELECT round(pg_xlog_location_diff(pg_last_xlog_receive_location(), pg_last_xlog_replay_location())/1048576.0,2) AS lag'';\n        ELSE\n            EXECUTE ''INSERT INTO omnidb_monitor_result ''\n                    ''SELECT round(pg_wal_lsn_diff(pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn())/1048576.0,2) AS lag'';\n        END IF;\n    END$$;\n    SELECT result as lag FROM omnidb_monitor_result;\n'''''')\n\ndatasets = []\nfor replag in replags.Rows:\n    color = "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")"\n    datasets.append({\n            "label": "Lag",\n            "fill": False,\n            "backgroundColor": color,\n            "borderColor": color,\n            "lineTension": 0,\n            "pointRadius": 1,\n            "borderWidth": 1,\n            "data": [replag[''lag'']]\n        })\n\nresult = {\n    "labels": [datetime.now().strftime(''%H:%M:%S'')],\n    "datasets": datasets\n}\n','\n',char(10)),'chart_append','Standby: Replication Lag (Size)',0,NULL,15);--omnidb--
INSERT INTO mon_units VALUES(15,'postgresql',replace('result = {\n    "type": "line",\n    "data": None,\n    "options": {\n        "responsive": True,\n        "title":{\n            "display":True,\n            "text":"Standby: Replication Lag (Time)"\n        },\n        "tooltips": {\n            "mode": "index",\n            "intersect": False\n        },\n        "hover": {\n            "mode": "nearest",\n            "intersect": True\n        },\n        "scales": {\n            "xAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Time"\n                }\n            }],\n            "yAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Seconds"\n                }\n            }]\n        }\n    }\n}\n','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\nreplags = connection.Query(''''''\n    SELECT COALESCE(ROUND(EXTRACT(epoch FROM now() - pg_last_xact_replay_timestamp())),0) AS lag\n'''''')\n\ndatasets = []\nfor replag in replags.Rows:\n    color = "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")"\n    datasets.append({\n            "label": "Lag",\n            "fill": False,\n            "backgroundColor": color,\n            "borderColor": color,\n            "lineTension": 0,\n            "pointRadius": 1,\n            "borderWidth": 1,\n            "data": [replag[''lag'']]\n        })\n\nresult = {\n    "labels": [datetime.now().strftime(''%H:%M:%S'')],\n    "datasets": datasets\n}\n','\n',char(10)),'chart_append','Standby: Replication Lag (Time)',0,NULL,15);--omnidb--
INSERT INTO mon_units VALUES(16,'postgresql',replace('result = {\n    "type": "line",\n    "data": None,\n    "options": {\n        "responsive": True,\n        "title":{\n            "display":True,\n            "text":"System Memory Usage (Total: " + total_mem + "MB)"\n        },\n        "tooltips": {\n            "mode": "index",\n            "intersect": False\n        },\n        "hover": {\n            "mode": "nearest",\n            "intersect": True\n        },\n        "scales": {\n            "xAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Time"\n                }\n            }],\n            "yAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "%",\n                },\n                "ticks": {\n                    "beginAtZero": True,\n                    "max": 100\n                }\n            }]\n        }\n    }\n}\n','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\ntry:\n    mem_data = connection.ExecuteScalar(''''''\n        create temporary table tabela (c1 text);\n        copy tabela from program ''free -m | tail -n +2 | head -n 1 | tr -s " " | cut -f2,3,4 -d " "'';\n        select * from tabela;\n    '''''')\nexcept:\n    raise Exception(''This chart can not be executed in a standby server.'')\n\nif mem_data is None:\n    raise Exception(''This chart can only be executed in a Linux server.'')\n\ndatasets = []\nmem_split = mem_data.split('' '')\ntotal_mem = mem_split[0]\nused_mem = mem_split[1]\nfree_mem = mem_split[2]\nperc_mem = round(int(used_mem)*100/int(total_mem),2)\ncolor = "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")"\ndatasets.append({\n        "label": "Memory",\n        "fill": False,\n        "backgroundColor": color,\n        "borderColor": color,\n        "lineTension": 0,\n        "pointRadius": 1,\n        "borderWidth": 1,\n        "data": [perc_mem]\n    })\n\nresult = {\n    "labels": [datetime.now().strftime(''%H:%M:%S'')],\n    "datasets": datasets\n}\n','\n',char(10)),'chart_append','Memory Usage',0,NULL,10);--omnidb--
INSERT INTO mon_units VALUES(17,'postgresql',replace('result = {\n    "type": "line",\n    "data": None,\n    "options": {\n        "legend": {\n            "display": False\n        },\n        "responsive": True,\n        "title":{\n            "display":True,\n            "text":"Longest Active Query"\n        },\n        "tooltips": {\n            "mode": "index",\n            "intersect": False\n        },\n        "hover": {\n            "mode": "nearest",\n            "intersect": True\n        },\n        "scales": {\n            "xAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Time"\n                }\n            }],\n            "yAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Duration(s)"\n                },\n                "ticks": {\n                    "beginAtZero": True\n                }\n            }]\n        }\n    }\n}\n','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\nduration = connection.ExecuteScalar(''''''\n    SELECT duration FROM\n    (SELECT EXTRACT(EPOCH FROM(now() - query_start))::INTEGER AS duration FROM pg_stat_activity WHERE state=''active''\n    UNION ALL\n    SELECT 0) t\n    WHERE duration is NOT NULL\n    ORDER BY duration DESC\n    LIMIT 1\n'''''')\n\ndatasets = []\ncolor = "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")"\ndatasets.append({\n        "label": ''Query'',\n        "fill": False,\n        "backgroundColor": color,\n        "borderColor": color,\n        "lineTension": 0,\n        "pointRadius": 1,\n        "borderWidth": 1,\n        "data": [duration]\n    })\n\nresult = {\n    "labels": [datetime.now().strftime(''%H:%M:%S'')],\n    "datasets": datasets\n}\n','\n',char(10)),'chart_append','Longest Active Query',0,NULL,5);--omnidb--
INSERT INTO mon_units VALUES(18,'postgresql',replace('result = {\n    "type": "line",\n    "data": None,\n    "options": {\n        "legend": {\n            "display": False\n        },\n        "responsive": True,\n        "title":{\n            "display":True,\n            "text":"WAL Folder Size"\n        },\n        "tooltips": {\n            "mode": "index",\n            "intersect": False\n        },\n        "hover": {\n            "mode": "nearest",\n            "intersect": True\n        },\n        "scales": {\n            "xAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Time"\n                }\n            }],\n            "yAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "Size(MB)"\n                },\n                "ticks": {\n                    "beginAtZero": True\n                }\n            }]\n        }\n    }\n}\n','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\nsize = connection.ExecuteScalar(''''''\n    CREATE TEMPORARY TABLE omnidb_temp (c1 TEXT, c2 TEXT);\n    COPY omnidb_temp FROM PROGRAM ''du -s pg_xlog || du -s pg_wal'';\n    SELECT ROUND(c1::BIGINT/1048576.0,2) AS pg_xlog_size FROM omnidb_temp;\n'''''')\n\ndatasets = []\ncolor = "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")"\ndatasets.append({\n        "label": ''WAL Folder Size'',\n        "fill": False,\n        "backgroundColor": color,\n        "borderColor": color,\n        "lineTension": 0,\n        "pointRadius": 1,\n        "borderWidth": 1,\n        "data": [size]\n    })\n\nresult = {\n    "labels": [datetime.now().strftime(''%H:%M:%S'')],\n    "datasets": datasets\n}\n','\n',char(10)),'chart_append','WAL Folder Size',0,NULL,30);--omnidb--
INSERT INTO mon_units VALUES(19,'postgresql',replace('result = {\n    "type": "line",\n    "data": None,\n    "options": {\n        "legend": {\n            "display": False\n        },\n        "responsive": True,\n        "title":{\n            "display":False\n        },\n        "tooltips": {\n            "mode": "index",\n            "intersect": False\n        },\n        "hover": {\n            "mode": "nearest",\n            "intersect": True\n        },\n        "scales": {\n            "xAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": False,\n                    "labelString": "Time"\n                }\n            }],\n            "yAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": True,\n                    "labelString": "MB/s"\n                },\n                "ticks": {\n                    "beginAtZero": True,\n                    "suggestedMax": 1\n                }\n            }]\n        }\n    }\n}','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\ntry:\n    if previous_data != None:\n        query = "select round(pg_wal_lsn_diff(pg_current_wal_lsn(),''" + previous_data["current_lsn"] + "'')/(1048576*extract(epoch from now()::time - ''" + previous_data["current_time"] + "''::time))::numeric,2) as wal_rate, pg_current_wal_lsn() as current_lsn, now()::time as current_time"\n    else:\n        query = ''select 0 as wal_rate, pg_current_wal_lsn() as current_lsn, now()::time as current_time''\n    query_data = connection.Query(query)\nexcept:\n    if previous_data != None:\n        query = "select round(pg_xlog_location_diff(pg_current_xlog_location(),''" + previous_data["current_lsn"] + "'')/(1048576*extract(epoch from now()::time - ''" + previous_data["current_time"] + "''::time))::numeric,2) as wal_rate, pg_current_xlog_location() as current_lsn, now()::time as current_time"\n    else:\n        query = ''select 0 as wal_rate, pg_current_xlog_location() as current_lsn, now()::time as current_time''\n    query_data = connection.Query(query)\n\ndatasets = []\ncolor = "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")"\ndatasets.append({\n        "label": ''Rate'',\n        "fill": False,\n        "backgroundColor": color,\n        "borderColor": color,\n        "lineTension": 0,\n        "pointRadius": 1,\n        "borderWidth": 1,\n        "data": [query_data.Rows[0][''wal_rate'']]\n    })\n\nresult = {\n    "labels": [datetime.now().strftime(''%H:%M:%S'')],\n    "datasets": datasets,\n    "current_lsn": query_data.Rows[0][''current_lsn''],\n    ''current_time'': query_data.Rows[0][''current_time'']\n}','\n',char(10)),'chart_append','WAL Production Rate',0,NULL,10);--omnidb--
INSERT INTO mon_units VALUES(20,'postgresql',replace('result = {\n    "type": "line",\n    "data": None,\n    "options": {\n        "legend": {\n            "display": False\n        },\n        "responsive": True,\n        "title":{\n            "display":False\n        },\n        "tooltips": {\n            "mode": "index",\n            "intersect": False\n        },\n        "hover": {\n            "mode": "nearest",\n            "intersect": True\n        },\n        "scales": {\n            "xAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": False,\n                    "labelString": "Time"\n                }\n            }],\n            "yAxes": [{\n                "display": True,\n                "scaleLabel": {\n                    "display": False\n                },\n                "ticks": {\n                    "beginAtZero": True\n                }\n            }]\n        }\n    }\n}','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\nif previous_data != None:\n    query = "select round((sum(xact_commit+xact_rollback) - " + previous_data["current_count"] + ")/(extract(epoch from now()::time - ''" + previous_data["current_time"] + "''::time))::numeric,2) as tps, sum(xact_commit+xact_rollback) as current_count, now()::time as current_time FROM pg_stat_database"\nelse:\n    query = ''select 0 as tps, sum(xact_commit+xact_rollback) as current_count, now()::time as current_time FROM pg_stat_database''\n\nquery_data = connection.Query(query)\n\ndatasets = []\ncolor = "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")"\ndatasets.append({\n        "label": ''Rate'',\n        "fill": False,\n        "backgroundColor": color,\n        "borderColor": color,\n        "lineTension": 0,\n        "pointRadius": 0,\n        "borderWidth": 1,\n        "data": [query_data.Rows[0][''tps'']]\n    })\n\nresult = {\n    "labels": [datetime.now().strftime(''%H:%M:%S'')],\n    "datasets": datasets,\n    "current_count": query_data.Rows[0][''current_count''],\n    ''current_time'': query_data.Rows[0][''current_time'']\n}','\n',char(10)),'chart_append','TPS',1,NULL,10);--omnidb--
INSERT INTO mon_units VALUES(21,'postgresql',replace('from random import randint\n\nresult = {\n    "container": None,\n    "boxSelectionEnabled": False,\n    "autounselectify": True,\n    "layout": {\n        "name": "spread",\n        "minDist": 1000\n    },\n    "style": [\n        {\n            "selector": "node",\n            "style": {\n                "content": "data(label)",\n                "text-opacity": 1,\n                "text-valign": "top",\n                "text-halign": "right",\n                "text-wrap": "wrap",\n                "color": "gray",\n                "text-rotation": "autorotate",\n                "font-size": 12\n            }\n        },\n        {\n            "selector": "node.node_local",\n            "style": {\n                "background-color": "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")",\n                "shape": ''square''\n            }\n        },\n        {\n            "selector": "node.node_remote",\n            "style": {\n                "background-color": "rgb(" + str(randint(125, 225)) + "," + str(randint(125, 225)) + "," + str(randint(125, 225)) + ")",\n            }\n        },\n        {\n            "selector": "edge",\n            "style": {\n                "curve-style": "bezier",\n                "control-point-step-size": 40,\n                "target-arrow-shape": "triangle",\n                "text-opacity": 1,\n                "width": 2,\n                "control-point-distances": 50,\n                "content": "data(label)",\n                "text-wrap": "wrap",\n                "line-style": "solid",\n                "width": 1,\n                "color": "gray",\n                "text-outline-color": ''gray'',\n                "text-outline-width": 0\n            }\n        }\n    ],\n    "elements": {\n        "nodes": None,\n        "edges": None\n    }\n}','\n',char(10)),replace('from datetime import datetime\nfrom random import randint\n\nnodes = []\nedges = []\n\ntry:\n    repl_nodes = connection.Query(''''''\n    select application_name,\n           pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(),coalesce(replay_lsn,flush_lsn))) lag_size\n    from pg_stat_replication\n    '''''')\nexcept:\n    repl_nodes = connection.Query(''''''\n    select application_name,\n           pg_size_pretty(pg_xlog_location_diff(pg_current_xlog_location(),coalesce(replay_location,flush_location)) lag_size\n    from pg_stat_replication\n    '''''')\n\nif len(repl_nodes.Rows) == 0:\n    raise Exception(''There are no nodes replicating from this instance.'')\n\nnodes.append({\n            "data": {\n                "id": ''local'',\n                "label": ''local'',\n            },\n            "classes": ''node_local''\n        })\n\nfor repl_node in repl_nodes.Rows:\n    nodes.append({\n            "data": {\n                "id": ''node_'' + repl_node[''application_name''],\n                "label": repl_node[''application_name'']\n            },\n            "classes": ''node_remote''\n        })\n    edges.append({\n            "data": {\n                "id": ''edge_'' + repl_node[''application_name''],\n                "label": repl_node[''lag_size''],\n                "source": ''local'',\n                "target": ''node_'' + repl_node[''application_name'']\n            }\n        })\n\nresult = {\n    "nodes": nodes,\n    "edges": edges\n}','\n',char(10)),'graph','Replication',0,NULL,10);--omnidb--

INSERT INTO units_users_connections
SELECT uuc_id,
       unit_id,
       user_id,
       conn_id,
       interval,
       plugin_name
FROM units_users_connections_temp
WHERE unit_id <= 18;--omnidb--

INSERT INTO mon_units
SELECT unit_id + 3 AS unit_id,
       dbt_st_name,
       script_chart,
       script_data,
       type,
       title,
       is_default,
       user_id,
       interval
FROM mon_units_temp
WHERE unit_id > 18;--omnidb--

INSERT INTO units_users_connections
SELECT uuc_id,
       unit_id + 3 AS unit_id,
       user_id,
       conn_id,
       interval,
       plugin_name
FROM units_users_connections_temp
WHERE unit_id > 18;--omnidb--

DROP TABLE mon_units_temp;--omnidb--
DROP TABLE units_users_connections_temp;--omnidb--

UPDATE users SET welcome_closed = 0;--omnidb--
UPDATE version SET ver_id = '2.16.0';--omnidb--
