UPDATE 4.4.0.0
[phpmyadmin.git] / js / db_structure.js
blob0b89dd64ea44371df6a6def4d55a2e561471c896
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * @fileoverview    functions used on the database structure page
4  * @name            Database Structure
5  *
6  * @requires    jQuery
7  * @requires    jQueryUI
8  * @required    js/functions.js
9  */
11 /**
12  * AJAX scripts for db_structure.php
13  *
14  * Actions ajaxified here:
15  * Drop Database
16  * Truncate Table
17  * Drop Table
18  *
19  */
21 /**
22  * Unbind all event handlers before tearing down a page
23  */
24 AJAX.registerTeardown('db_structure.js', function () {
25     $(document).off('click', "a.truncate_table_anchor.ajax");
26     $(document).off('click', "a.drop_table_anchor.ajax");
27     $(document).off('click', '#real_end_input');
28     $(document).off('click', "a.favorite_table_anchor.ajax");
29     $('a.real_row_count').off('click');
30     $('a.row_count_sum').off('click');
31     $('select[name=submit_mult]').unbind('change');
32 });
34 /**
35  * Adjust number of rows and total size in the summary
36  * when truncating, creating, dropping or inserting into a table
37  */
38 function PMA_adjustTotals() {
39     var byteUnits = new Array(
40         PMA_messages.strB,
41         PMA_messages.strKiB,
42         PMA_messages.strMiB,
43         PMA_messages.strGiB,
44         PMA_messages.strTiB,
45         PMA_messages.strPiB,
46         PMA_messages.strEiB
47     );
48     /**
49      * @var $allTr jQuery object that references all the rows in the list of tables
50      */
51     var $allTr = $("#tablesForm table.data tbody:first tr");
52     // New summary values for the table
53     var tableSum = $allTr.size();
54     var rowsSum = 0;
55     var sizeSum = 0;
56     var overheadSum = 0;
57     var rowSumApproximated = false;
59     $allTr.each(function () {
60         var $this = $(this);
61         var i, tmpVal;
62         // Get the number of rows for this SQL table
63         var strRows = $this.find('.tbl_rows').text();
64         // If the value is approximated
65         if (strRows.indexOf('~') === 0) {
66             rowSumApproximated = true;
67             // The approximated value contains a preceding ~ (Eg 100 --> ~100)
68             strRows = strRows.substring(1, strRows.length);
69         }
70         strRows = strRows.replace(/[,.]/g, '');
71         var intRow = parseInt(strRows, 10);
72         if (! isNaN(intRow)) {
73             rowsSum += intRow;
74         }
75         // Extract the size and overhead
76         var valSize         = 0;
77         var valOverhead     = 0;
78         var strSize         = $.trim($this.find('.tbl_size span:not(.unit)').text());
79         var strSizeUnit     = $.trim($this.find('.tbl_size span.unit').text());
80         var strOverhead     = $.trim($this.find('.tbl_overhead span:not(.unit)').text());
81         var strOverheadUnit = $.trim($this.find('.tbl_overhead span.unit').text());
82         // Given a value and a unit, such as 100 and KiB, for the table size
83         // and overhead calculate their numeric values in bytes, such as 102400
84         for (i = 0; i < byteUnits.length; i++) {
85             if (strSizeUnit == byteUnits[i]) {
86                 tmpVal = parseFloat(strSize);
87                 valSize = tmpVal * Math.pow(1024, i);
88                 break;
89             }
90         }
91         for (i = 0; i < byteUnits.length; i++) {
92             if (strOverheadUnit == byteUnits[i]) {
93                 tmpVal = parseFloat(strOverhead);
94                 valOverhead = tmpVal * Math.pow(1024, i);
95                 break;
96             }
97         }
98         sizeSum += valSize;
99         overheadSum += valOverhead;
100     });
101     // Add some commas for readability:
102     // 1000000 becomes 1,000,000
103     var strRowSum = rowsSum + "";
104     var regex = /(\d+)(\d{3})/;
105     while (regex.test(strRowSum)) {
106         strRowSum = strRowSum.replace(regex, '$1' + ',' + '$2');
107     }
108     // If approximated total value add ~ in front
109     if (rowSumApproximated) {
110         strRowSum = "~" + strRowSum;
111     }
112     // Calculate the magnitude for the size and overhead values
113     var size_magnitude = 0, overhead_magnitude = 0;
114     while (sizeSum >= 1024) {
115         sizeSum /= 1024;
116         size_magnitude++;
117     }
118     while (overheadSum >= 1024) {
119         overheadSum /= 1024;
120         overhead_magnitude++;
121     }
123     sizeSum = Math.round(sizeSum * 10) / 10;
124     overheadSum = Math.round(overheadSum * 10) / 10;
126     // Update summary with new data
127     var $summary = $("#tbl_summary_row");
128     $summary.find('.tbl_num').text(PMA_sprintf(PMA_messages.strNTables, tableSum));
129     $summary.find('.row_count_sum').text(strRowSum);
130     $summary.find('.tbl_size').text(sizeSum + " " + byteUnits[size_magnitude]);
131     $summary.find('.tbl_overhead').text(overheadSum + " " + byteUnits[overhead_magnitude]);
135  * Gets the real row count for a table or DB.
136  * @param object $target Target for appending the real count value.
137  */
138 function PMA_fetchRealRowCount($target)
140     var $throbber = $('#pma_navigation .throbber')
141         .first()
142         .clone()
143         .css({visibility: 'visible', display: 'inline-block'})
144         .click(false);
145     $target.html($throbber);
146     $.ajax({
147         type: 'GET',
148         url: $target.attr('href'),
149         cache: false,
150         dataType: 'json',
151         success: function (response) {
152             if (response.success) {
153                 // If to update all row counts for a DB.
154                 if (response.real_row_count_all) {
155                     $.each(JSON.parse(response.real_row_count_all),
156                         function (index, table) {
157                             // Update each table row count.
158                             $('table.data td[data-table*="' + table.table + '"]')
159                             .text(table.row_count);
160                         }
161                     );
162                 }
163                 // If to update a particular table's row count.
164                 if (response.real_row_count) {
165                     // Append the parent cell with real row count.
166                     $target.parent().text(response.real_row_count);
167                 }
168                 // Adjust the 'Sum' displayed at the bottom.
169                 PMA_adjustTotals();
170             } else {
171                 PMA_ajaxShowMessage(PMA_messages.strErrorRealRowCount);
172             }
173         },
174         error: function () {
175             PMA_ajaxShowMessage(PMA_messages.strErrorRealRowCount);
176         }
177     });
180 AJAX.registerOnload('db_structure.js', function () {
181     /**
182      * Handler for the print view multisubmit.
183      * All other multi submits can be handled via ajax, but this one needs
184      * special treatment as the results need to open in another browser window
185      */
186     $('#tablesForm').submit(function (event) {
187         var $form = $(this);
188         if ($form.find('select[name=submit_mult]').val() === 'print') {
189             event.preventDefault();
190             event.stopPropagation();
191             $('form#clone').remove();
192             var $clone = $form
193                 .clone()
194                 .hide()
195                 .appendTo('body');
196             $clone
197                 .find('select[name=submit_mult]')
198                 .val('print');
199             $clone
200                 .attr('target', 'printview')
201                 .attr('id', 'clone')
202                 .submit();
203         }
204     });
207  * function to open the confirmation dialog for making table consistent with central list
209  * @param string   msg     message text to be displayed to user
210  * @param function success function to be called on success
212  */
213     var jqConfirm = function(msg, success) {
214         var dialogObj = $("<div style='display:none'>"+msg+"</div>");
215         $('body').append(dialogObj);
216         var buttonOptions = {};
217         buttonOptions[PMA_messages.strContinue] = function () {
218             success();
219             $( this ).dialog( "close" );
220         };
221         buttonOptions[PMA_messages.strCancel] = function () {
222             $( this ).dialog( "close" );
223             $('#tablesForm')[0].reset();
224         };
225         $(dialogObj).dialog({
226             resizable: false,
227             modal: true,
228             title: PMA_messages.confirmTitle,
229             buttons: buttonOptions
230         });
231     };
234  *  Event handler on select of "Make consistent with central list"
235  */
236     $('select[name=submit_mult]').change(function(event) {
237         if($(this).val() === 'make_consistent_with_central_list') {
238             event.preventDefault();
239             event.stopPropagation();
240             jqConfirm(PMA_messages.makeConsistentMessage, function(){
241                         $('#tablesForm').submit();
242                     });
243             return false;
244         }
245     });
247     /**
248      * Ajax Event handler for 'Truncate Table'
249      */
250     $(document).on('click', "a.truncate_table_anchor.ajax", function (event) {
251         event.preventDefault();
253         /**
254          * @var $this_anchor Object  referring to the anchor clicked
255          */
256         var $this_anchor = $(this);
258         //extract current table name and build the question string
259         /**
260          * @var curr_table_name String containing the name of the table to be truncated
261          */
262         var curr_table_name = $this_anchor.parents('tr').children('th').children('a').text();
263         /**
264          * @var question    String containing the question to be asked for confirmation
265          */
266         var question = PMA_messages.strTruncateTableStrongWarning + ' ' +
267             PMA_sprintf(PMA_messages.strDoYouReally, 'TRUNCATE ' + escapeHtml(curr_table_name));
269         $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) {
271             PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
273             $.get(url, {'is_js_confirmed' : 1, 'ajax_request' : true}, function (data) {
274                 if (typeof data !== 'undefined' && data.success === true) {
275                     PMA_ajaxShowMessage(data.message);
276                     // Adjust table statistics
277                     var $tr = $this_anchor.closest('tr');
278                     $tr.find('.tbl_rows').text('0');
279                     $tr.find('.tbl_size, .tbl_overhead').text('-');
280                     //Fetch inner span of this anchor
281                     //and replace the icon with its disabled version
282                     var span = $this_anchor.html().replace(/b_empty/, 'bd_empty');
283                     //To disable further attempts to truncate the table,
284                     //replace the a element with its inner span (modified)
285                     $this_anchor
286                         .replaceWith(span)
287                         .removeClass('truncate_table_anchor');
288                     PMA_adjustTotals();
289                 } else {
290                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
291                 }
292             }); // end $.get()
293         }); //end $.PMA_confirm()
294     }); //end of Truncate Table Ajax action
296     /**
297      * Ajax Event handler for 'Drop Table' or 'Drop View'
298      */
299     $(document).on('click', "a.drop_table_anchor.ajax", function (event) {
300         event.preventDefault();
302         var $this_anchor = $(this);
304         //extract current table name and build the question string
305         /**
306          * @var $curr_row    Object containing reference to the current row
307          */
308         var $curr_row = $this_anchor.parents('tr');
309         /**
310          * @var curr_table_name String containing the name of the table to be truncated
311          */
312         var curr_table_name = $curr_row.children('th').children('a').text();
313         /**
314          * @var is_view Boolean telling if we have a view
315          */
316         var is_view = $curr_row.hasClass('is_view') || $this_anchor.hasClass('view');
317         /**
318          * @var question    String containing the question to be asked for confirmation
319          */
320         var question;
321         if (! is_view) {
322             question = PMA_messages.strDropTableStrongWarning + ' ' +
323                 PMA_sprintf(PMA_messages.strDoYouReally, 'DROP TABLE ' + escapeHtml(curr_table_name));
324         } else {
325             question =
326                 PMA_sprintf(PMA_messages.strDoYouReally, 'DROP VIEW ' + escapeHtml(curr_table_name));
327         }
329         $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) {
331             var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
333             $.get(url, {'is_js_confirmed' : 1, 'ajax_request' : true}, function (data) {
334                 if (typeof data !== 'undefined' && data.success === true) {
335                     PMA_ajaxShowMessage(data.message);
336                     toggleRowColors($curr_row.next());
337                     $curr_row.hide("medium").remove();
338                     PMA_adjustTotals();
339                     PMA_reloadNavigation();
340                     PMA_ajaxRemoveMessage($msg);
341                 } else {
342                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
343                 }
344             }); // end $.get()
345         }); // end $.PMA_confirm()
346     }); //end of Drop Table Ajax action
348     //Calculate Real End for InnoDB
349     /**
350      * Ajax Event handler for calculating the real end for a InnoDB table
351      *
352      */
353     $(document).on('click', '#real_end_input', function (event) {
354         event.preventDefault();
356         /**
357          * @var question    String containing the question to be asked for confirmation
358          */
359         var question = PMA_messages.strOperationTakesLongTime;
361         $(this).PMA_confirm(question, '', function () {
362             return true;
363         });
364         return false;
365     }); //end Calculate Real End for InnoDB
367     PMA_tooltip(
368         $("select[name*='funcs']"),
369         'select',
370         PMA_messages.strFunctionHint
371     );
372     // Add tooltip to favorite icons.
373     $(".favorite_table_anchor").each(function () {
374         PMA_tooltip(
375             $(this),
376             'a',
377             $(this).attr("title")
378         );
379     });
381     // Get real row count via Ajax.
382     $('a.real_row_count').on('click', function (event) {
383         event.preventDefault();
384         PMA_fetchRealRowCount($(this));
385     });
386     // Get all real row count.
387     $('a.row_count_sum').on('click', function (event) {
388         event.preventDefault();
389         PMA_fetchRealRowCount($(this));
390     });
391 }); // end $()