sql.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. /* vim: set expandtab sw=4 ts=4 sts=4: */
  2. /**
  3. * @fileoverview functions used wherever an sql query form is used
  4. *
  5. * @requires jQuery
  6. * @requires js/functions.js
  7. *
  8. */
  9. var $data_a;
  10. var prevScrollX = 0, fixedTop;
  11. /**
  12. * decode a string URL_encoded
  13. *
  14. * @param string str
  15. * @return string the URL-decoded string
  16. */
  17. function PMA_urldecode(str)
  18. {
  19. return decodeURIComponent(str.replace(/\+/g, '%20'));
  20. }
  21. /**
  22. * endecode a string URL_decoded
  23. *
  24. * @param string str
  25. * @return string the URL-encoded string
  26. */
  27. function PMA_urlencode(str)
  28. {
  29. return encodeURIComponent(str).replace(/\%20/g, '+');
  30. }
  31. /**
  32. * Get the field name for the current field. Required to construct the query
  33. * for grid editing
  34. *
  35. * @param $this_field jQuery object that points to the current field's tr
  36. */
  37. function getFieldName($this_field)
  38. {
  39. var this_field_index = $this_field.index();
  40. // ltr or rtl direction does not impact how the DOM was generated
  41. // check if the action column in the left exist
  42. var left_action_exist = !$('#table_results').find('th:first').hasClass('draggable');
  43. // number of column span for checkbox and Actions
  44. var left_action_skip = left_action_exist ? $('#table_results').find('th:first').attr('colspan') - 1 : 0;
  45. // If this column was sorted, the text of the a element contains something
  46. // like <small>1</small> that is useful to indicate the order in case
  47. // of a sort on multiple columns; however, we dont want this as part
  48. // of the column name so we strip it ( .clone() to .end() )
  49. var field_name = $('#table_results')
  50. .find('thead')
  51. .find('th:eq(' + (this_field_index - left_action_skip) + ') a')
  52. .clone() // clone the element
  53. .children() // select all the children
  54. .remove() // remove all of them
  55. .end() // go back to the selected element
  56. .text(); // grab the text
  57. // happens when just one row (headings contain no a)
  58. if (field_name === '') {
  59. var $heading = $('#table_results').find('thead').find('th:eq(' + (this_field_index - left_action_skip) + ')').children('span');
  60. // may contain column comment enclosed in a span - detach it temporarily to read the column name
  61. var $tempColComment = $heading.children().detach();
  62. field_name = $heading.text();
  63. // re-attach the column comment
  64. $heading.append($tempColComment);
  65. }
  66. field_name = $.trim(field_name);
  67. return field_name;
  68. }
  69. /**
  70. * Unbind all event handlers before tearing down a page
  71. */
  72. AJAX.registerTeardown('sql.js', function () {
  73. $('a.delete_row.ajax').die('click');
  74. $('#bookmarkQueryForm').die('submit');
  75. $('input#bkm_label').unbind('keyup');
  76. $("#sqlqueryresults").die('makegrid');
  77. $("#sqlqueryresults").die('stickycolumns');
  78. $("#togglequerybox").unbind('click');
  79. $("#button_submit_query").die('click');
  80. $("input[name=bookmark_variable]").unbind("keypress");
  81. $("#sqlqueryform.ajax").die('submit');
  82. $("input[name=navig].ajax").die('click');
  83. $("#pageselector").die('change');
  84. $("#table_results.ajax").find("a[title=Sort]").die('click');
  85. $("#displayOptionsForm.ajax").die('submit');
  86. $('a.browse_foreign').die('click');
  87. $('th.column_heading.pointer').die('hover');
  88. $('th.column_heading.marker').die('click');
  89. $(window).unbind('scroll');
  90. $(".filter_rows").die("keyup");
  91. });
  92. /**
  93. * @description <p>Ajax scripts for sql and browse pages</p>
  94. *
  95. * Actions ajaxified here:
  96. * <ul>
  97. * <li>Retrieve results of an SQL query</li>
  98. * <li>Paginate the results table</li>
  99. * <li>Sort the results table</li>
  100. * <li>Change table according to display options</li>
  101. * <li>Grid editing of data</li>
  102. * <li>Saving a bookmark</li>
  103. * </ul>
  104. *
  105. * @name document.ready
  106. * @memberOf jQuery
  107. */
  108. AJAX.registerOnload('sql.js', function () {
  109. // Delete row from SQL results
  110. $('a.delete_row.ajax').live('click', function (e) {
  111. e.preventDefault();
  112. var question = $.sprintf(PMA_messages.strDoYouReally, escapeHtml($(this).closest('td').find('div').text()));
  113. var $link = $(this);
  114. $link.PMA_confirm(question, $link.attr('href'), function (url) {
  115. $msgbox = PMA_ajaxShowMessage();
  116. $.get(url, {'ajax_request': true, 'is_js_confirmed': true}, function (data) {
  117. if (data.success) {
  118. PMA_ajaxShowMessage(data.message);
  119. $link.closest('tr').remove();
  120. } else {
  121. PMA_ajaxShowMessage(data.error, false);
  122. }
  123. });
  124. });
  125. });
  126. // Ajaxification for 'Bookmark this SQL query'
  127. $('#bookmarkQueryForm').live('submit', function (e) {
  128. e.preventDefault();
  129. PMA_ajaxShowMessage();
  130. $.post($(this).attr('action'), 'ajax_request=1&' + $(this).serialize(), function (data) {
  131. if (data.success) {
  132. PMA_ajaxShowMessage(data.message);
  133. } else {
  134. PMA_ajaxShowMessage(data.error, false);
  135. }
  136. });
  137. });
  138. /* Hides the bookmarkoptions checkboxes when the bookmark label is empty */
  139. $('input#bkm_label').keyup(function () {
  140. $('input#id_bkm_all_users, input#id_bkm_replace')
  141. .parent()
  142. .toggle($(this).val().length > 0);
  143. }).trigger('keyup');
  144. /**
  145. * Attach the {@link makegrid} function to a custom event, which will be
  146. * triggered manually everytime the table of results is reloaded
  147. * @memberOf jQuery
  148. */
  149. $("#sqlqueryresults").live('makegrid', function () {
  150. PMA_makegrid($('#table_results')[0]);
  151. });
  152. /*
  153. * Attach a custom event for sticky column headings which will be
  154. * triggered manually everytime the table of results is reloaded
  155. * @memberOf jQuery
  156. */
  157. $("#sqlqueryresults").live('stickycolumns', function () {
  158. if ($("#table_results").length === 0) {
  159. return;
  160. }
  161. //add sticky columns div
  162. initStickyColumns();
  163. rearrangeStickyColumns();
  164. //adjust sticky columns on scroll
  165. $(window).bind('scroll', function() {
  166. handleStickyColumns();
  167. });
  168. });
  169. /**
  170. * Append the "Show/Hide query box" message to the query input form
  171. *
  172. * @memberOf jQuery
  173. * @name appendToggleSpan
  174. */
  175. // do not add this link more than once
  176. if (! $('#sqlqueryform').find('a').is('#togglequerybox')) {
  177. $('<a id="togglequerybox"></a>')
  178. .html(PMA_messages.strHideQueryBox)
  179. .appendTo("#sqlqueryform")
  180. // initially hidden because at this point, nothing else
  181. // appears under the link
  182. .hide();
  183. // Attach the toggling of the query box visibility to a click
  184. $("#togglequerybox").bind('click', function () {
  185. var $link = $(this);
  186. $link.siblings().slideToggle("fast");
  187. if ($link.text() == PMA_messages.strHideQueryBox) {
  188. $link.text(PMA_messages.strShowQueryBox);
  189. // cheap trick to add a spacer between the menu tabs
  190. // and "Show query box"; feel free to improve!
  191. $('#togglequerybox_spacer').remove();
  192. $link.before('<br id="togglequerybox_spacer" />');
  193. } else {
  194. $link.text(PMA_messages.strHideQueryBox);
  195. }
  196. // avoid default click action
  197. return false;
  198. });
  199. }
  200. /**
  201. * Event handler for sqlqueryform.ajax button_submit_query
  202. *
  203. * @memberOf jQuery
  204. */
  205. $("#button_submit_query").live('click', function (event) {
  206. $(".success,.error").hide();
  207. //hide already existing error or success message
  208. var $form = $(this).closest("form");
  209. // the Go button related to query submission was clicked,
  210. // instead of the one related to Bookmarks, so empty the
  211. // id_bookmark selector to avoid misinterpretation in
  212. // import.php about what needs to be done
  213. $form.find("select[name=id_bookmark]").val("");
  214. // let normal event propagation happen
  215. });
  216. /**
  217. * Event handler for hitting enter on sqlqueryform bookmark_variable
  218. * (the Variable textfield in Bookmarked SQL query section)
  219. *
  220. * @memberOf jQuery
  221. */
  222. $("input[name=bookmark_variable]").bind("keypress", function (event) {
  223. // force the 'Enter Key' to implicitly click the #button_submit_bookmark
  224. var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
  225. if (keycode == 13) { // keycode for enter key
  226. // When you press enter in the sqlqueryform, which
  227. // has 2 submit buttons, the default is to run the
  228. // #button_submit_query, because of the tabindex
  229. // attribute.
  230. // This submits #button_submit_bookmark instead,
  231. // because when you are in the Bookmarked SQL query
  232. // section and hit enter, you expect it to do the
  233. // same action as the Go button in that section.
  234. $("#button_submit_bookmark").click();
  235. return false;
  236. } else {
  237. return true;
  238. }
  239. });
  240. /**
  241. * Ajax Event handler for 'SQL Query Submit'
  242. *
  243. * @see PMA_ajaxShowMessage()
  244. * @memberOf jQuery
  245. * @name sqlqueryform_submit
  246. */
  247. $("#sqlqueryform.ajax").live('submit', function (event) {
  248. event.preventDefault();
  249. var $form = $(this);
  250. if (codemirror_editor) {
  251. $form[0].elements['sql_query'].value = codemirror_editor.getValue();
  252. }
  253. if (! checkSqlQuery($form[0])) {
  254. return false;
  255. }
  256. // remove any div containing a previous error message
  257. $('div.error').remove();
  258. var $msgbox = PMA_ajaxShowMessage();
  259. var $sqlqueryresults = $('#sqlqueryresults');
  260. PMA_prepareForAjaxRequest($form);
  261. $.post($form.attr('action'), $form.serialize(), function (data) {
  262. if (data.success === true) {
  263. // success happens if the query returns rows or not
  264. //
  265. // fade out previous messages, if any
  266. $('div.success, div.sqlquery_message').fadeOut();
  267. if ($('#result_query').length) {
  268. $('#result_query').remove();
  269. }
  270. // show a message that stays on screen
  271. if (typeof data.action_bookmark != 'undefined') {
  272. // view only
  273. if ('1' == data.action_bookmark) {
  274. $('#sqlquery').text(data.sql_query);
  275. // send to codemirror if possible
  276. setQuery(data.sql_query);
  277. }
  278. // delete
  279. if ('2' == data.action_bookmark) {
  280. $("#id_bookmark option[value='" + data.id_bookmark + "']").remove();
  281. // if there are no bookmarked queries now (only the empty option),
  282. // remove the bookmark section
  283. if ($('#id_bookmark option').length == 1) {
  284. $('#fieldsetBookmarkOptions').hide();
  285. $('#fieldsetBookmarkOptionsFooter').hide();
  286. }
  287. }
  288. $sqlqueryresults
  289. .show()
  290. .html(data.message);
  291. } else if (typeof data.sql_query != 'undefined') {
  292. $('<div class="sqlquery_message"></div>')
  293. .html(data.sql_query)
  294. .insertBefore('#sqlqueryform');
  295. // unnecessary div that came from data.sql_query
  296. $('div.notice').remove();
  297. } else {
  298. $sqlqueryresults
  299. .show()
  300. .html(data.message);
  301. }
  302. PMA_highlightSQL($('#result_query'));
  303. if (typeof data.ajax_reload != 'undefined') {
  304. if (data.ajax_reload.reload) {
  305. if (data.ajax_reload.table_name) {
  306. PMA_commonParams.set('table', data.ajax_reload.table_name);
  307. PMA_commonActions.refreshMain();
  308. } else {
  309. PMA_reloadNavigation();
  310. }
  311. }
  312. } else if (typeof data.reload != 'undefined') {
  313. // this happens if a USE or DROP command was typed
  314. PMA_commonActions.setDb(data.db);
  315. var url;
  316. if (data.db) {
  317. if (data.table) {
  318. url = 'table_sql.php';
  319. } else {
  320. url = 'db_sql.php';
  321. }
  322. } else {
  323. url = 'server_sql.php';
  324. }
  325. PMA_commonActions.refreshMain(url, function () {
  326. if ($('#result_query').length) {
  327. $('#result_query').remove();
  328. }
  329. if (data.sql_query) {
  330. $('<div id="result_query"></div>')
  331. .html(data.sql_query)
  332. .prependTo('#page_content');
  333. PMA_highlightSQL($('#page_content'));
  334. }
  335. });
  336. }
  337. $sqlqueryresults.show().trigger('makegrid').trigger('stickycolumns');
  338. $('#togglequerybox').show();
  339. PMA_init_slider();
  340. if (typeof data.action_bookmark == 'undefined') {
  341. if ($('#sqlqueryform input[name="retain_query_box"]').is(':checked') !== true) {
  342. if ($("#togglequerybox").siblings(":visible").length > 0) {
  343. $("#togglequerybox").trigger('click');
  344. }
  345. }
  346. }
  347. } else if (data.success === false) {
  348. // show an error message that stays on screen
  349. $('#sqlqueryform').before(data.error);
  350. $sqlqueryresults.hide();
  351. }
  352. PMA_ajaxRemoveMessage($msgbox);
  353. }); // end $.post()
  354. }); // end SQL Query submit
  355. /**
  356. * Paginate results with Page Selector dropdown
  357. * @memberOf jQuery
  358. * @name paginate_dropdown_change
  359. */
  360. $("#pageselector").live('change', function (event) {
  361. var $form = $(this).parent("form");
  362. $form.submit();
  363. }); // end Paginate results with Page Selector
  364. /**
  365. * Ajax Event handler for the display options
  366. * @memberOf jQuery
  367. * @name displayOptionsForm_submit
  368. */
  369. $("#displayOptionsForm.ajax").live('submit', function (event) {
  370. event.preventDefault();
  371. $form = $(this);
  372. $.post($form.attr('action'), $form.serialize() + '&ajax_request=true', function (data) {
  373. $("#sqlqueryresults")
  374. .html(data.message)
  375. .trigger('makegrid');
  376. PMA_init_slider();
  377. }); // end $.post()
  378. }); //end displayOptionsForm handler
  379. // Filter row handling. --STARTS--
  380. $(".filter_rows").live("keyup", function () {
  381. var $target_table = $("#table_results");
  382. var $header_cells = $target_table.find("th[data-column]");
  383. var target_columns = Array();
  384. // To handle colspan=4, in case of edit,copy etc options.
  385. var dummy_th = ($(".edit_row_anchor").length !== 0 ?
  386. '<th class="hide dummy_th"></th><th class="hide dummy_th"></th><th class="hide dummy_th"></th>'
  387. : '');
  388. // Selecting columns that will be considered for filtering and searching.
  389. $header_cells.each(function () {
  390. target_columns.push($.trim($(this).text()));
  391. });
  392. var phrase = $(this).val();
  393. // Set same value to both Filter rows fields.
  394. $(".filter_rows").val(phrase);
  395. // Handle colspan.
  396. $target_table.find("thead > tr").prepend(dummy_th);
  397. $.uiTableFilter($target_table, phrase, target_columns);
  398. $target_table.find("th.dummy_th").remove();
  399. });
  400. // Filter row handling. --ENDS--
  401. }); // end $()
  402. /**
  403. * Starting from some th, change the class of all td under it.
  404. * If isAddClass is specified, it will be used to determine whether to add or remove the class.
  405. */
  406. function PMA_changeClassForColumn($this_th, newclass, isAddClass)
  407. {
  408. // index 0 is the th containing the big T
  409. var th_index = $this_th.index();
  410. var has_big_t = !$this_th.closest('tr').children(':first').hasClass('column_heading');
  411. // .eq() is zero-based
  412. if (has_big_t) {
  413. th_index--;
  414. }
  415. var $tds = $("#table_results").find('tbody tr').find('td.data:eq(' + th_index + ')');
  416. if (isAddClass === undefined) {
  417. $tds.toggleClass(newclass);
  418. } else {
  419. $tds.toggleClass(newclass, isAddClass);
  420. }
  421. }
  422. AJAX.registerOnload('sql.js', function () {
  423. $('a.browse_foreign').live('click', function (e) {
  424. e.preventDefault();
  425. window.open(this.href, 'foreigners', 'width=640,height=240,scrollbars=yes,resizable=yes');
  426. $anchor = $(this);
  427. $anchor.addClass('browse_foreign_clicked');
  428. });
  429. /**
  430. * vertical column highlighting in horizontal mode when hovering over the column header
  431. */
  432. $('th.column_heading.pointer').live('hover', function (e) {
  433. PMA_changeClassForColumn($(this), 'hover', e.type == 'mouseenter');
  434. });
  435. /**
  436. * vertical column marking in horizontal mode when clicking the column header
  437. */
  438. $('th.column_heading.marker').live('click', function () {
  439. PMA_changeClassForColumn($(this), 'marked');
  440. });
  441. /**
  442. * create resizable table
  443. */
  444. $("#sqlqueryresults").trigger('makegrid').trigger('stickycolumns');
  445. });
  446. /*
  447. * Profiling Chart
  448. */
  449. function makeProfilingChart()
  450. {
  451. if ($('#profilingchart').length === 0 ||
  452. $('#profilingchart').html().length !== 0 ||
  453. !$.jqplot || !$.jqplot.Highlighter || !$.jqplot.PieRenderer
  454. ) {
  455. return;
  456. }
  457. var data = [];
  458. $.each(jQuery.parseJSON($('#profilingChartData').html()), function (key, value) {
  459. data.push([key, parseFloat(value)]);
  460. });
  461. // Remove chart and data divs contents
  462. $('#profilingchart').html('').show();
  463. $('#profilingChartData').html('');
  464. PMA_createProfilingChartJqplot('profilingchart', data);
  465. }
  466. /*
  467. * initialize profiling data tables
  468. */
  469. function initProfilingTables()
  470. {
  471. if (!$.tablesorter) {
  472. return;
  473. }
  474. $('#profiletable').tablesorter({
  475. widgets: ['zebra'],
  476. sortList: [[0, 0]],
  477. textExtraction: function (node) {
  478. if (node.children.length > 0) {
  479. return node.children[0].innerHTML;
  480. } else {
  481. return node.innerHTML;
  482. }
  483. }
  484. });
  485. $('#profilesummarytable').tablesorter({
  486. widgets: ['zebra'],
  487. sortList: [[1, 1]],
  488. textExtraction: function (node) {
  489. if (node.children.length > 0) {
  490. return node.children[0].innerHTML;
  491. } else {
  492. return node.innerHTML;
  493. }
  494. }
  495. });
  496. }
  497. /*
  498. * Set position, left, top, width of sticky_columns div
  499. */
  500. function setStickyColumnsPosition(position, top, left) {
  501. if ($("#sticky_columns").length !== 0) {
  502. $("#sticky_columns")
  503. .css("position", position)
  504. .css("top", top)
  505. .css("left", left ? left : "auto")
  506. .css("width", $("#table_results").width());
  507. }
  508. }
  509. /*
  510. * Initialize sticky columns
  511. */
  512. function initStickyColumns() {
  513. fixedTop = $('#floating_menubar').height();
  514. if ($("#sticky_columns").length === 0) {
  515. $('<table id="sticky_columns"></table>')
  516. .insertBefore('#page_content')
  517. .css("position", "fixed")
  518. .css("z-index", "99")
  519. .css("width", $("#table_results").width())
  520. .css("margin-left", $('#page_content').css("margin-left"))
  521. .css("top", fixedTop)
  522. .css("display", "none");
  523. }
  524. }
  525. /*
  526. * Arrange/Rearrange columns in sticky header
  527. */
  528. function rearrangeStickyColumns() {
  529. var $sticky_columns = $("#sticky_columns");
  530. var $originalHeader = $("#table_results > thead");
  531. var $originalColumns = $originalHeader.find("tr:first").children();
  532. var $clonedHeader = $originalHeader.clone();
  533. // clone width per cell
  534. $clonedHeader.find("tr:first").children().width(function(i,val) {
  535. return $originalColumns.eq(i).width();
  536. });
  537. $sticky_columns.empty().append($clonedHeader);
  538. }
  539. /*
  540. * Adjust sticky columns on horizontal/vertical scroll
  541. */
  542. function handleStickyColumns() {
  543. if ($("#table_results").length === 0) {
  544. return;
  545. }
  546. var currentScrollX = $(window).scrollLeft();
  547. var windowOffset = $(window).scrollTop();
  548. var tableStartOffset = $("#table_results").offset().top;
  549. var tableEndOffset = tableStartOffset + $("#table_results").height();
  550. var $sticky_columns = $("#sticky_columns");
  551. if (windowOffset >= tableStartOffset && windowOffset <= tableEndOffset) {
  552. //for horizontal scrolling
  553. if(prevScrollX != currentScrollX) {
  554. prevScrollX = currentScrollX;
  555. setStickyColumnsPosition("absolute", fixedTop + windowOffset);
  556. //for vertical scrolling
  557. } else {
  558. setStickyColumnsPosition("fixed", fixedTop, $("#pma_navigation").width() - currentScrollX);
  559. }
  560. $sticky_columns.show();
  561. } else {
  562. $sticky_columns.hide();
  563. }
  564. }
  565. AJAX.registerOnload('sql.js', function () {
  566. makeProfilingChart();
  567. initProfilingTables();
  568. });