pghero 1.7.0 → 2.0.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of pghero might be problematic. Click here for more details.

Files changed (54) hide show
  1. checksums.yaml +4 -4
  2. data/.travis.yml +2 -0
  3. data/CHANGELOG.md +31 -0
  4. data/README.md +2 -2
  5. data/app/assets/javascripts/pghero/Chart.bundle.js +7512 -5661
  6. data/app/assets/javascripts/pghero/application.js +9 -0
  7. data/app/assets/javascripts/pghero/highlight.pack.js +2 -0
  8. data/app/assets/stylesheets/pghero/application.css +54 -2
  9. data/app/assets/stylesheets/pghero/arduino-light.css +86 -0
  10. data/app/controllers/pg_hero/home_controller.rb +148 -52
  11. data/app/helpers/pg_hero/base_helper.rb +15 -0
  12. data/app/views/layouts/pg_hero/application.html.erb +1 -1
  13. data/app/views/pg_hero/home/_connections_table.html.erb +2 -2
  14. data/app/views/pg_hero/home/_live_queries_table.html.erb +11 -7
  15. data/app/views/pg_hero/home/_queries_table.html.erb +21 -10
  16. data/app/views/pg_hero/home/_suggested_index.html.erb +1 -1
  17. data/app/views/pg_hero/home/connections.html.erb +2 -14
  18. data/app/views/pg_hero/home/explain.html.erb +1 -1
  19. data/app/views/pg_hero/home/index.html.erb +58 -22
  20. data/app/views/pg_hero/home/index_bloat.html.erb +69 -0
  21. data/app/views/pg_hero/home/maintenance.html.erb +7 -7
  22. data/app/views/pg_hero/home/queries.html.erb +10 -0
  23. data/app/views/pg_hero/home/relation_space.html.erb +9 -0
  24. data/app/views/pg_hero/home/show_query.html.erb +107 -0
  25. data/app/views/pg_hero/home/space.html.erb +64 -10
  26. data/config/routes.rb +4 -2
  27. data/guides/Rails.md +28 -1
  28. data/guides/Suggested-Indexes.md +1 -1
  29. data/lib/pghero.rb +25 -36
  30. data/lib/pghero/database.rb +5 -1
  31. data/lib/pghero/methods/basic.rb +78 -13
  32. data/lib/pghero/methods/connections.rb +16 -56
  33. data/lib/pghero/methods/explain.rb +2 -6
  34. data/lib/pghero/methods/indexes.rb +173 -18
  35. data/lib/pghero/methods/kill.rb +2 -2
  36. data/lib/pghero/methods/maintenance.rb +23 -26
  37. data/lib/pghero/methods/queries.rb +1 -23
  38. data/lib/pghero/methods/query_stats.rb +95 -96
  39. data/lib/pghero/methods/{replica.rb → replication.rb} +17 -4
  40. data/lib/pghero/methods/sequences.rb +4 -5
  41. data/lib/pghero/methods/space.rb +101 -8
  42. data/lib/pghero/methods/suggested_indexes.rb +49 -108
  43. data/lib/pghero/methods/system.rb +14 -10
  44. data/lib/pghero/methods/tables.rb +8 -8
  45. data/lib/pghero/methods/users.rb +10 -12
  46. data/lib/pghero/version.rb +1 -1
  47. data/lib/tasks/pghero.rake +1 -1
  48. data/test/basic_test.rb +38 -0
  49. data/test/best_index_test.rb +3 -3
  50. data/test/suggested_indexes_test.rb +0 -2
  51. data/test/test_helper.rb +38 -40
  52. metadata +11 -6
  53. data/app/views/pg_hero/home/index_usage.html.erb +0 -27
  54. data/test/explain_test.rb +0 -18
@@ -2,6 +2,13 @@
2
2
  //= require ./jquery.nouislider.min
3
3
  //= require ./Chart.bundle
4
4
  //= require ./chartkick
5
+ //= require ./highlight.pack
6
+
7
+ function highlightQueries() {
8
+ $("pre code").each(function(i, block) {
9
+ hljs.highlightBlock(block);
10
+ });
11
+ }
5
12
 
6
13
  function initSlider() {
7
14
  function roundTime(time) {
@@ -122,6 +129,8 @@ function initSlider() {
122
129
  var callback = function (response, status, xhr) {
123
130
  if (status === "error" ) {
124
131
  $(".queries-info").css("color", "red").html(xhr.status + " " + xhr.statusText);
132
+ } else {
133
+ highlightQueries();
125
134
  }
126
135
  };
127
136
  $("#queries").html('<tr><td colspan="3"><p class="queries-info text-muted">...</p></td></tr>').load(path, callback);
@@ -0,0 +1,2 @@
1
+ /*! highlight.js v9.12.0 | BSD3 License | git.io/hljslicense */
2
+ !function(e){var n="object"==typeof window&&window||"object"==typeof self&&self;"undefined"!=typeof exports?e(exports):n&&(n.hljs=e({}),"function"==typeof define&&define.amd&&define([],function(){return n.hljs}))}(function(e){function n(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0===t.index}function a(e){return k.test(e)}function i(e){var n,t,r,i,o=e.className+" ";if(o+=e.parentNode?e.parentNode.className:"",t=B.exec(o))return w(t[1])?t[1]:"no-highlight";for(o=o.split(/\s+/),n=0,r=o.length;r>n;n++)if(i=o[n],a(i)||w(i))return i}function o(e){var n,t={},r=Array.prototype.slice.call(arguments,1);for(n in e)t[n]=e[n];return r.forEach(function(e){for(n in e)t[n]=e[n]}),t}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3===i.nodeType?a+=i.nodeValue.length:1===i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function c(e,r,a){function i(){return e.length&&r.length?e[0].offset!==r[0].offset?e[0].offset<r[0].offset?e:r:"start"===r[0].event?e:r:e.length?e:r}function o(e){function r(e){return" "+e.nodeName+'="'+n(e.value).replace('"',"&quot;")+'"'}s+="<"+t(e)+E.map.call(e.attributes,r).join("")+">"}function u(e){s+="</"+t(e)+">"}function c(e){("start"===e.event?o:u)(e.node)}for(var l=0,s="",f=[];e.length||r.length;){var g=i();if(s+=n(a.substring(l,g[0].offset)),l=g[0].offset,g===e){f.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g===e&&g.length&&g[0].offset===l);f.reverse().forEach(o)}else"start"===g[0].event?f.push(g[0].node):f.pop(),c(g.splice(0,1)[0])}return s+n(a.substr(l))}function l(e){return e.v&&!e.cached_variants&&(e.cached_variants=e.v.map(function(n){return o(e,{v:null},n)})),e.cached_variants||e.eW&&[o(e)]||[e]}function s(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var o={},u=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");o[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?u("keyword",a.k):x(a.k).forEach(function(e){u(e,a.k[e])}),a.k=o}a.lR=t(a.l||/\w+/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),null==a.r&&(a.r=1),a.c||(a.c=[]),a.c=Array.prototype.concat.apply([],a.c.map(function(e){return l("self"===e?a:e)})),a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var c=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=c.length?t(c.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e,n){var t,a;for(t=0,a=n.c.length;a>t;t++)if(r(n.c[t].bR,e))return n.c[t]}function u(e,n){if(r(e.eR,n)){for(;e.endsParent&&e.parent;)e=e.parent;return e}return e.eW?u(e.parent,n):void 0}function c(e,n){return!a&&r(n.iR,e)}function l(e,n){var t=N.cI?n[0].toLowerCase():n[0];return e.k.hasOwnProperty(t)&&e.k[t]}function p(e,n,t,r){var a=r?"":I.classPrefix,i='<span class="'+a,o=t?"":C;return i+=e+'">',i+n+o}function h(){var e,t,r,a;if(!E.k)return n(k);for(a="",t=0,E.lR.lastIndex=0,r=E.lR.exec(k);r;)a+=n(k.substring(t,r.index)),e=l(E,r),e?(B+=e[1],a+=p(e[0],n(r[0]))):a+=n(r[0]),t=E.lR.lastIndex,r=E.lR.exec(k);return a+n(k.substr(t))}function d(){var e="string"==typeof E.sL;if(e&&!y[E.sL])return n(k);var t=e?f(E.sL,k,!0,x[E.sL]):g(k,E.sL.length?E.sL:void 0);return E.r>0&&(B+=t.r),e&&(x[E.sL]=t.top),p(t.language,t.value,!1,!0)}function b(){L+=null!=E.sL?d():h(),k=""}function v(e){L+=e.cN?p(e.cN,"",!0):"",E=Object.create(e,{parent:{value:E}})}function m(e,n){if(k+=e,null==n)return b(),0;var t=o(n,E);if(t)return t.skip?k+=n:(t.eB&&(k+=n),b(),t.rB||t.eB||(k=n)),v(t,n),t.rB?0:n.length;var r=u(E,n);if(r){var a=E;a.skip?k+=n:(a.rE||a.eE||(k+=n),b(),a.eE&&(k=n));do E.cN&&(L+=C),E.skip||(B+=E.r),E=E.parent;while(E!==r.parent);return r.starts&&v(r.starts,""),a.rE?0:n.length}if(c(n,E))throw new Error('Illegal lexeme "'+n+'" for mode "'+(E.cN||"<unnamed>")+'"');return k+=n,n.length||1}var N=w(e);if(!N)throw new Error('Unknown language: "'+e+'"');s(N);var R,E=i||N,x={},L="";for(R=E;R!==N;R=R.parent)R.cN&&(L=p(R.cN,"",!0)+L);var k="",B=0;try{for(var M,j,O=0;;){if(E.t.lastIndex=O,M=E.t.exec(t),!M)break;j=m(t.substring(O,M.index),M[0]),O=M.index+j}for(m(t.substr(O)),R=E;R.parent;R=R.parent)R.cN&&(L+=C);return{r:B,value:L,language:e,top:E}}catch(T){if(T.message&&-1!==T.message.indexOf("Illegal"))return{r:0,value:n(t)};throw T}}function g(e,t){t=t||I.languages||x(y);var r={r:0,value:n(e)},a=r;return t.filter(w).forEach(function(n){var t=f(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}),a.language&&(r.second_best=a),r}function p(e){return I.tabReplace||I.useBR?e.replace(M,function(e,n){return I.useBR&&"\n"===e?"<br>":I.tabReplace?n.replace(/\t/g,I.tabReplace):""}):e}function h(e,n,t){var r=n?L[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function d(e){var n,t,r,o,l,s=i(e);a(s)||(I.useBR?(n=document.createElementNS("http://www.w3.org/1999/xhtml","div"),n.innerHTML=e.innerHTML.replace(/\n/g,"").replace(/<br[ \/]*>/g,"\n")):n=e,l=n.textContent,r=s?f(s,l,!0):g(l),t=u(n),t.length&&(o=document.createElementNS("http://www.w3.org/1999/xhtml","div"),o.innerHTML=r.value,r.value=c(t,u(o),l)),r.value=p(r.value),e.innerHTML=r.value,e.className=h(e.className,s,r.language),e.result={language:r.language,re:r.r},r.second_best&&(e.second_best={language:r.second_best.language,re:r.second_best.r}))}function b(e){I=o(I,e)}function v(){if(!v.called){v.called=!0;var e=document.querySelectorAll("pre code");E.forEach.call(e,d)}}function m(){addEventListener("DOMContentLoaded",v,!1),addEventListener("load",v,!1)}function N(n,t){var r=y[n]=t(e);r.aliases&&r.aliases.forEach(function(e){L[e]=n})}function R(){return x(y)}function w(e){return e=(e||"").toLowerCase(),y[e]||y[L[e]]}var E=[],x=Object.keys,y={},L={},k=/^(no-?highlight|plain|text)$/i,B=/\blang(?:uage)?-([\w-]+)\b/i,M=/((^(<[^>]+>|\t|)+|(?:\n)))/gm,C="</span>",I={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0};return e.highlight=f,e.highlightAuto=g,e.fixMarkup=p,e.highlightBlock=d,e.configure=b,e.initHighlighting=v,e.initHighlightingOnLoad=m,e.registerLanguage=N,e.listLanguages=R,e.getLanguage=w,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e.METHOD_GUARD={b:"\\.\\s*"+e.UIR,r:0},e});hljs.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*#]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias allocate allow alter always analyze ancillary and any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second section securefile security seed segment select self sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null",built_in:"array bigint binary bit blob boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t]},e.CBCM,t]}});
@@ -1,5 +1,6 @@
1
1
  /*
2
2
  *= require ./jquery.nouislider
3
+ *= require ./arduino-light
3
4
  *= require_self
4
5
  */
5
6
 
@@ -44,6 +45,12 @@ h1 {
44
45
  font-weight: bold;
45
46
  }
46
47
 
48
+ h1 small {
49
+ font-weight: normal;
50
+ font-size: 14px;
51
+ color: #999;
52
+ }
53
+
47
54
  h1, p {
48
55
  margin-bottom: 20px;
49
56
  }
@@ -58,12 +65,18 @@ ul {
58
65
  margin: 0;
59
66
  }
60
67
 
68
+ ul.list-normal {
69
+ list-style-type: disc;
70
+ padding-left: 20px;
71
+ }
72
+
61
73
  table td, table th {
62
74
  padding: 8px;
63
75
  }
64
76
 
65
77
  td {
66
78
  border-top: solid 1px #ddd;
79
+ vertical-align: top;
67
80
  }
68
81
 
69
82
  pre {
@@ -71,11 +84,12 @@ pre {
71
84
  padding: 10px;
72
85
  white-space: pre-wrap;
73
86
  word-break: break-word;
87
+ margin-top: 0;
74
88
  }
75
89
 
76
90
  textarea {
77
91
  width: 100%;
78
- height: 100px;
92
+ height: 120px;
79
93
  border: solid 1px #ddd;
80
94
  padding: 10px;
81
95
  }
@@ -107,6 +121,22 @@ hr {
107
121
  margin-left: 6px;
108
122
  }
109
123
 
124
+ .btn-explain {
125
+ background: none;
126
+ border: none;
127
+ padding: 0;
128
+ font: inherit;
129
+ cursor: pointer;
130
+ color: #999;
131
+ font-size: 12px;
132
+ line-height: 20px;
133
+ margin-left: 6px;
134
+ }
135
+
136
+ .btn-explain:hover {
137
+ text-decoration: underline;
138
+ }
139
+
110
140
  .user {
111
141
  color: #999;
112
142
  font-size: 12px;
@@ -114,6 +144,10 @@ hr {
114
144
  line-height: 20px;
115
145
  }
116
146
 
147
+ .user a {
148
+ color: inherit;
149
+ }
150
+
117
151
  .tiny {
118
152
  font-size: 12px;
119
153
  margin-left: 6px;
@@ -140,7 +174,7 @@ hr {
140
174
  padding: 6px 140px 20px 140px;
141
175
  }
142
176
 
143
- .queries-table th a {
177
+ .queries-table th a, .space-table th a {
144
178
  color: inherit;
145
179
  }
146
180
 
@@ -434,3 +468,21 @@ body {
434
468
  text-align: center;
435
469
  color: #999;
436
470
  }
471
+
472
+ .unused-index {
473
+ color: #f0ad4e;
474
+ font-size: 11px;
475
+ font-weight: bold;
476
+ }
477
+
478
+ .origin {
479
+ word-break: break-word;
480
+ }
481
+
482
+ .duplicate-indexes td {
483
+ padding: 15px 0 5px 0;
484
+ }
485
+
486
+ .duplicate-indexes pre {
487
+ margin-top: 10px;
488
+ }
@@ -0,0 +1,86 @@
1
+ /*
2
+
3
+ Arduino® Light Theme - Stefania Mellai <s.mellai@arduino.cc>
4
+
5
+ */
6
+
7
+ .hljs {
8
+ display: block;
9
+ overflow-x: auto;
10
+ }
11
+
12
+ .hljs,
13
+ .hljs-subst {
14
+ color: #434f54;
15
+ }
16
+
17
+ .hljs-keyword,
18
+ .hljs-attribute,
19
+ .hljs-selector-tag,
20
+ .hljs-doctag,
21
+ .hljs-name {
22
+ color: #00979D;
23
+ }
24
+
25
+ .hljs-built_in,
26
+ .hljs-literal,
27
+ .hljs-bullet,
28
+ .hljs-code,
29
+ .hljs-addition {
30
+ color: #D35400;
31
+ }
32
+
33
+ .hljs-regexp,
34
+ .hljs-symbol,
35
+ .hljs-variable,
36
+ .hljs-template-variable,
37
+ .hljs-link,
38
+ .hljs-selector-attr,
39
+ .hljs-selector-pseudo {
40
+ color: #00979D;
41
+ }
42
+
43
+ .hljs-type,
44
+ .hljs-string,
45
+ .hljs-selector-id,
46
+ .hljs-selector-class,
47
+ .hljs-quote,
48
+ .hljs-template-tag,
49
+ .hljs-deletion {
50
+ color: #005C5F;
51
+ }
52
+
53
+ .hljs-title,
54
+ .hljs-section {
55
+ color: #880000;
56
+ font-weight: bold;
57
+ }
58
+
59
+ .hljs-comment {
60
+ color: #777;
61
+ }
62
+
63
+ .hljs-meta-keyword {
64
+ color: #728E00;
65
+ }
66
+
67
+ .hljs-meta {
68
+ color: #728E00;
69
+ color: #434f54;
70
+ }
71
+
72
+ .hljs-emphasis {
73
+ font-style: italic;
74
+ }
75
+
76
+ .hljs-strong {
77
+ font-weight: bold;
78
+ }
79
+
80
+ .hljs-function {
81
+ color: #728E00;
82
+ }
83
+
84
+ .hljs-number {
85
+ color: #8A7B52;
86
+ }
@@ -9,52 +9,91 @@ module PgHero
9
9
  if respond_to?(:before_action)
10
10
  before_action :set_database
11
11
  before_action :set_query_stats_enabled
12
+ before_action :set_show_details, only: [:index, :queries, :show_query]
12
13
  else
13
14
  before_filter :set_database
14
15
  before_filter :set_query_stats_enabled
16
+ before_filter :set_show_details, only: [:index, :queries, :show_query]
15
17
  end
16
18
 
17
19
  def index
18
20
  @title = "Overview"
19
21
  @extended = params[:extended]
20
- @query_stats = @database.query_stats(historical: true, start_at: 3.hours.ago)
21
- @slow_queries = @database.slow_queries(query_stats: @query_stats)
22
- @autovacuum_queries, @long_running_queries = @database.long_running_queries.partition { |q| q["query"].starts_with?("autovacuum:") }
23
22
 
24
- if @extended
25
- @index_hit_rate = @database.index_hit_rate
26
- @table_hit_rate = @database.table_hit_rate
27
- @good_cache_rate = @table_hit_rate >= @database.cache_hit_rate_threshold.to_f / 100 && @index_hit_rate >= @database.cache_hit_rate_threshold.to_f / 100
23
+ if @replica
24
+ @replication_lag = @database.replication_lag
25
+ @good_replication_lag = @replication_lag < 5
26
+ else
27
+ @inactive_replication_slots = @database.replication_slots.select { |r| !r[:active] }
28
28
  end
29
29
 
30
- @unused_indexes = @database.unused_indexes.select { |q| q["index_scans"].to_i == 0 } if @extended
31
- @invalid_indexes = @database.invalid_indexes
32
- @duplicate_indexes = @database.duplicate_indexes
33
- unless @query_stats_enabled
30
+ @autovacuum_queries, @long_running_queries = @database.long_running_queries.partition { |q| q[:query].starts_with?("autovacuum:") }
31
+
32
+ @total_connections = @database.total_connections
33
+ @good_total_connections = @total_connections < @database.total_connections_threshold
34
+
35
+ @transaction_id_danger = @database.transaction_id_danger(threshold: 1500000000)
36
+ @sequence_danger = @database.sequence_danger(threshold: (params[:sequence_threshold] || 0.9).to_f)
37
+
38
+ @indexes = @database.indexes
39
+ @invalid_indexes = @indexes.select { |i| !i[:valid] }
40
+ @duplicate_indexes = @database.duplicate_indexes(indexes: @indexes)
41
+
42
+ if @query_stats_enabled
43
+ @query_stats = @database.query_stats(historical: true, start_at: 3.hours.ago)
44
+ @slow_queries = @database.slow_queries(query_stats: @query_stats)
45
+ set_suggested_indexes((params[:min_average_time] || 20).to_f, (params[:min_calls] || 50).to_i)
46
+ else
34
47
  @query_stats_available = @database.query_stats_available?
35
48
  @query_stats_extension_enabled = @database.query_stats_extension_enabled? if @query_stats_available
49
+ @suggested_indexes = []
36
50
  end
37
- @total_connections = @database.total_connections
38
- @good_total_connections = @total_connections < @database.total_connections_threshold
39
- if @replica
40
- @replication_lag = @database.replication_lag
41
- @good_replication_lag = @replication_lag < 5
51
+
52
+ if @extended
53
+ @index_hit_rate = @database.index_hit_rate || 0
54
+ @table_hit_rate = @database.table_hit_rate || 0
55
+ @good_cache_rate = @table_hit_rate >= @database.cache_hit_rate_threshold / 100.0 && @index_hit_rate >= @database.cache_hit_rate_threshold / 100.0
56
+ @unused_indexes = @database.unused_indexes(max_scans: 0)
42
57
  end
43
- @transaction_id_danger = @database.transaction_id_danger(threshold: 1500000000)
44
- set_suggested_indexes((params[:min_average_time] || 20).to_f, (params[:min_calls] || 50).to_i)
45
- @show_migrations = PgHero.show_migrations
46
- @sequence_danger = @database.sequence_danger(threshold: params[:sequence_threshold])
47
- end
48
58
 
49
- def index_usage
50
- @title = "Index Usage"
51
- @index_usage = @database.index_usage
59
+ @show_migrations = PgHero.show_migrations
52
60
  end
53
61
 
54
62
  def space
55
63
  @title = "Space"
64
+ @days = (params[:days] || 7).to_i
56
65
  @database_size = @database.database_size
57
- @relation_sizes = @database.relation_sizes
66
+ @relation_sizes = params[:tables] ? @database.table_sizes : @database.relation_sizes
67
+ @space_stats_enabled = @database.space_stats_enabled? && !params[:tables]
68
+ if @space_stats_enabled
69
+ space_growth = @database.space_growth(days: @days, relation_sizes: @relation_sizes)
70
+ @growth_bytes_by_relation = Hash[ space_growth.map { |r| [r[:relation], r[:growth_bytes]] } ]
71
+ case params[:sort]
72
+ when "growth"
73
+ @relation_sizes.sort_by! { |r| s = @growth_bytes_by_relation[r[:relation]]; [s ? 0 : 1, -s.to_i, r[:relation]] }
74
+ when "name"
75
+ @relation_sizes.sort_by! { |r| r[:relation] || r[:table] }
76
+ end
77
+ end
78
+
79
+ @unused_indexes = @database.unused_indexes(max_scans: 0)
80
+ @unused_index_names = Set.new(@unused_indexes.map { |r| r[:index] })
81
+ @show_migrations = PgHero.show_migrations
82
+ @system_stats_enabled = @database.system_stats_enabled?
83
+ @index_bloat = @database.index_bloat
84
+ end
85
+
86
+ def relation_space
87
+ @relation = params[:relation]
88
+ @title = @relation
89
+ relation_space_stats = @database.relation_space_stats(@relation)
90
+ @chart_data = [{name: "Value", data: relation_space_stats.map { |r| [r[:captured_at], (r[:size_bytes].to_f / 1.megabyte).round(1)] }, library: chart_library_options}]
91
+ end
92
+
93
+ def index_bloat
94
+ @title = "Index Bloat"
95
+ @index_bloat = @database.index_bloat
96
+ @show_sql = params[:sql]
58
97
  end
59
98
 
60
99
  def live_queries
@@ -64,35 +103,34 @@ module PgHero
64
103
 
65
104
  def queries
66
105
  @title = "Queries"
67
- @historical_query_stats_enabled = @database.historical_query_stats_enabled?
68
106
  @sort = %w(average_time calls).include?(params[:sort]) ? params[:sort] : nil
69
107
  @min_average_time = params[:min_average_time] ? params[:min_average_time].to_i : nil
70
108
  @min_calls = params[:min_calls] ? params[:min_calls].to_i : nil
71
109
 
72
- @query_stats =
110
+ if @historical_query_stats_enabled
73
111
  begin
74
- if @historical_query_stats_enabled
75
- @start_at = params[:start_at] ? Time.zone.parse(params[:start_at]) : 24.hours.ago
76
- @end_at = Time.zone.parse(params[:end_at]) if params[:end_at]
77
- end
78
-
79
- if @historical_query_stats_enabled && !request.xhr?
80
- []
81
- else
82
- @database.query_stats(
83
- historical: true,
84
- start_at: @start_at,
85
- end_at: @end_at,
86
- sort: @sort,
87
- min_average_time: @min_average_time,
88
- min_calls: @min_calls
89
- )
90
- end
112
+ @start_at = params[:start_at] ? Time.zone.parse(params[:start_at]) : 24.hours.ago
113
+ @end_at = Time.zone.parse(params[:end_at]) if params[:end_at]
91
114
  rescue
92
115
  @error = true
116
+ end
117
+ end
118
+
119
+ @query_stats =
120
+ if @historical_query_stats_enabled && !request.xhr?
93
121
  []
122
+ else
123
+ @database.query_stats(
124
+ historical: true,
125
+ start_at: @start_at,
126
+ end_at: @end_at,
127
+ sort: @sort,
128
+ min_average_time: @min_average_time,
129
+ min_calls: @min_calls
130
+ )
94
131
  end
95
132
 
133
+ @indexes = @database.indexes
96
134
  set_suggested_indexes
97
135
 
98
136
  # fix back button issue with caching
@@ -102,6 +140,38 @@ module PgHero
102
140
  end
103
141
  end
104
142
 
143
+ def show_query
144
+ @query_hash = params[:query_hash].to_i
145
+ @title = @query_hash
146
+
147
+ stats = @database.query_stats(historical: true, query_hash: @query_hash, start_at: 24.hours.ago).first
148
+ if stats
149
+ @query = stats[:query]
150
+ @explainable_query = stats[:explainable_query]
151
+
152
+ if @show_details
153
+ query_hash_stats = @database.query_hash_stats(@query_hash)
154
+
155
+ @chart_data = [{name: "Value", data: query_hash_stats.map { |r| [r[:captured_at], (r[:total_minutes] * 60 * 1000).round] }, library: chart_library_options}]
156
+ @chart2_data = [{name: "Value", data: query_hash_stats.map { |r| [r[:captured_at], r[:average_time].round(1)] }, library: chart_library_options}]
157
+ @chart3_data = [{name: "Value", data: query_hash_stats.map { |r| [r[:captured_at], r[:calls]] }, library: chart_library_options}]
158
+
159
+ @origins = Hash[query_hash_stats.group_by { |r| r[:origin].to_s }.map { |k, v| [k, v.size] }]
160
+ @total_count = query_hash_stats.size
161
+ end
162
+
163
+ @tables = PgQuery.parse(@query).tables rescue []
164
+ @tables.sort!
165
+
166
+ if @tables.any?
167
+ @row_counts = Hash[@database.table_stats(table: @tables).map { |i| [i[:table], i[:estimated_rows]] }]
168
+ @indexes_by_table = @database.indexes.group_by { |i| i[:table] }
169
+ end
170
+ else
171
+ render text: "Unknown query"
172
+ end
173
+ end
174
+
105
175
  def system
106
176
  @title = "System"
107
177
  @periods = {
@@ -131,6 +201,12 @@ module PgHero
131
201
  ]
132
202
  end
133
203
 
204
+ def free_space_stats
205
+ render json: [
206
+ {name: "Free Space", data: @database.free_space_stats(duration: 14.days, period: 1.hour).map { |k, v| [k, (v / 1.gigabyte).round] }, library: chart_library_options},
207
+ ]
208
+ end
209
+
134
210
  def explain
135
211
  @title = "Explain"
136
212
  @query = params[:query]
@@ -163,8 +239,11 @@ module PgHero
163
239
 
164
240
  def connections
165
241
  @title = "Connections"
166
- @total_connections = @database.total_connections
167
- @connection_sources = @database.connection_sources(by_database_and_user: true)
242
+ @connection_sources = @database.connection_sources
243
+ @total_connections = @connection_sources.sum { |cs| cs[:total_connections] }
244
+
245
+ @connections_by_database = group_connections(@connection_sources, :database)
246
+ @connections_by_user = group_connections(@connection_sources, :user)
168
247
  end
169
248
 
170
249
  def maintenance
@@ -218,7 +297,8 @@ module PgHero
218
297
  def set_database
219
298
  @databases = PgHero.databases.values
220
299
  if params[:database]
221
- @database = PgHero.databases[params[:database]]
300
+ # don't do direct lookup, since you don't want to call to_sym on user input
301
+ @database = @databases.find { |d| d.id == params[:database] }
222
302
  elsif @databases.size > 1
223
303
  redirect_to url_for(controller: controller_name, action: action_name, database: @databases.first.id)
224
304
  else
@@ -237,18 +317,34 @@ module PgHero
237
317
  end
238
318
 
239
319
  def set_suggested_indexes(min_average_time = 0, min_calls = 0)
240
- @suggested_indexes_by_query = @database.suggested_indexes_by_query(query_stats: @query_stats.select { |qs| qs["average_time"].to_f >= min_average_time && qs["calls"].to_i >= min_calls })
241
- @suggested_indexes = @database.suggested_indexes(suggested_indexes_by_query: @suggested_indexes_by_query)
242
- @query_stats_by_query = @query_stats.index_by { |q| q["query"] }
243
- @debug = params[:debug] == "true"
320
+ @suggested_indexes_by_query = @database.suggested_indexes_by_query(query_stats: @query_stats.select { |qs| qs[:average_time] >= min_average_time && qs[:calls] >= min_calls })
321
+ @suggested_indexes = @database.suggested_indexes(suggested_indexes_by_query: @suggested_indexes_by_query, indexes: @indexes)
322
+ @query_stats_by_query = @query_stats.index_by { |q| q[:query] }
323
+ @debug = params[:debug].present?
244
324
  end
245
325
 
246
326
  def system_params
247
- params.permit(:duration, :period)
327
+ {
328
+ duration: params[:duration],
329
+ period: params[:period]
330
+ }.delete_if { |_, v| v.nil? }
248
331
  end
249
332
 
250
333
  def chart_library_options
251
334
  {pointRadius: 0, pointHitRadius: 5, borderWidth: 4}
252
335
  end
336
+
337
+ def set_show_details
338
+ @historical_query_stats_enabled = @query_stats_enabled && @database.historical_query_stats_enabled?
339
+ @show_details = @historical_query_stats_enabled && @database.supports_query_hash?
340
+ end
341
+
342
+ def group_connections(connection_sources, key)
343
+ top_connections = Hash.new(0)
344
+ connection_sources.each do |source|
345
+ top_connections[source[key]] += source[:total_connections]
346
+ end
347
+ top_connections.sort_by { |k, v| [-v, k] }
348
+ end
253
349
  end
254
350
  end