Translated using Weblate (Bulgarian)
[phpmyadmin.git] / js / db_structure.js
blob807b8cb898bad5cc73eca881f15d263b7f4917ce
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     $("span.fkc_switch").unbind('click');
26     $('#fkc_checkbox').unbind('change');
27     $("a.truncate_table_anchor.ajax").die('click');
28     $("a.drop_table_anchor.ajax").die('click');
29     $('a.drop_tracking_anchor.ajax').die('click');
30     $('#real_end_input').die('click');
31     $("a.favorite_table_anchor.ajax").die('click');
32     $('a.real_row_count').off('click');
33     $('a.row_count_sum').off('click');
34     $('select[name=submit_mult]').unbind('change');
35 });
37 /**
38  * Adjust number of rows and total size in the summary
39  * when truncating, creating, dropping or inserting into a table
40  */
41 function PMA_adjustTotals() {
42     var byteUnits = new Array(
43         PMA_messages.strB,
44         PMA_messages.strKiB,
45         PMA_messages.strMiB,
46         PMA_messages.strGiB,
47         PMA_messages.strTiB,
48         PMA_messages.strPiB,
49         PMA_messages.strEiB
50     );
51     /**
52      * @var $allTr jQuery object that references all the rows in the list of tables
53      */
54     var $allTr = $("#tablesForm table.data tbody:first tr");
55     // New summary values for the table
56     var tableSum = $allTr.size();
57     var rowsSum = 0;
58     var sizeSum = 0;
59     var overheadSum = 0;
60     var rowSumApproximated = false;
62     $allTr.each(function () {
63         var $this = $(this);
64         var i, tmpVal;
65         // Get the number of rows for this SQL table
66         var strRows = $this.find('.tbl_rows').text();
67         // If the value is approximated
68         if (strRows.indexOf('~') === 0) {
69             rowSumApproximated = true;
70             // The approximated value contains a preceding ~ (Eg 100 --> ~100)
71             strRows = strRows.substring(1, strRows.length);
72         }
73         strRows = strRows.replace(/[,.]/g, '');
74         var intRow = parseInt(strRows, 10);
75         if (! isNaN(intRow)) {
76             rowsSum += intRow;
77         }
78         // Extract the size and overhead
79         var valSize         = 0;
80         var valOverhead     = 0;
81         var strSize         = $.trim($this.find('.tbl_size span:not(.unit)').text());
82         var strSizeUnit     = $.trim($this.find('.tbl_size span.unit').text());
83         var strOverhead     = $.trim($this.find('.tbl_overhead span:not(.unit)').text());
84         var strOverheadUnit = $.trim($this.find('.tbl_overhead span.unit').text());
85         // Given a value and a unit, such as 100 and KiB, for the table size
86         // and overhead calculate their numeric values in bytes, such as 102400
87         for (i = 0; i < byteUnits.length; i++) {
88             if (strSizeUnit == byteUnits[i]) {
89                 tmpVal = parseFloat(strSize);
90                 valSize = tmpVal * Math.pow(1024, i);
91                 break;
92             }
93         }
94         for (i = 0; i < byteUnits.length; i++) {
95             if (strOverheadUnit == byteUnits[i]) {
96                 tmpVal = parseFloat(strOverhead);
97                 valOverhead = tmpVal * Math.pow(1024, i);
98                 break;
99             }
100         }
101         sizeSum += valSize;
102         overheadSum += valOverhead;
103     });
104     // Add some commas for readablility:
105     // 1000000 becomes 1,000,000
106     var strRowSum = rowsSum + "";
107     var regex = /(\d+)(\d{3})/;
108     while (regex.test(strRowSum)) {
109         strRowSum = strRowSum.replace(regex, '$1' + ',' + '$2');
110     }
111     // If approximated total value add ~ in front
112     if (rowSumApproximated) {
113         strRowSum = "~" + strRowSum;
114     }
115     // Calculate the magnitude for the size and overhead values
116     var size_magnitude = 0, overhead_magnitude = 0;
117     while (sizeSum >= 1024) {
118         sizeSum /= 1024;
119         size_magnitude++;
120     }
121     while (overheadSum >= 1024) {
122         overheadSum /= 1024;
123         overhead_magnitude++;
124     }
126     sizeSum = Math.round(sizeSum * 10) / 10;
127     overheadSum = Math.round(overheadSum * 10) / 10;
129     // Update summary with new data
130     var $summary = $("#tbl_summary_row");
131     $summary.find('.tbl_num').text(PMA_sprintf(PMA_messages.strTables, tableSum));
132     $summary.find('.row_count_sum').text(strRowSum);
133     $summary.find('.tbl_size').text(sizeSum + " " + byteUnits[size_magnitude]);
134     $summary.find('.tbl_overhead').text(overheadSum + " " + byteUnits[overhead_magnitude]);
138  * Gets the real row count for a table or DB.
139  * @param object $target Target for appending the real count value.
140  */
141 function PMA_fetchRealRowCount($target)
143     var $throbber = $('#pma_navigation .throbber')
144         .first()
145         .clone()
146         .css({visibility: 'visible', display: 'inline-block'})
147         .click(false);
148     $target.html($throbber);
149     $.ajax({
150         type: 'GET',
151         url: $target.attr('href'),
152         cache: false,
153         dataType: 'json',
154         success: function (response) {
155             if (response.success) {
156                 // If to update all row counts for a DB.
157                 if (response.real_row_count_all) {
158                     $.each(JSON.parse(response.real_row_count_all),
159                         function (index, table) {
160                             // Update each table row count.
161                             $('table.data td[data-table*="' + table.table + '"]')
162                             .text(table.row_count);
163                         }
164                     );
165                 }
166                 // If to update a particular table's row count.
167                 if (response.real_row_count) {
168                     // Append the parent cell with real row count.
169                     $target.parent().text(response.real_row_count);
170                 }
171                 // Adjust the 'Sum' displayed at the bottom.
172                 PMA_adjustTotals();
173             } else {
174                 PMA_ajaxShowMessage(PMA_messages.strErrorRealRowCount);
175             }
176         },
177         error: function () {
178             PMA_ajaxShowMessage(PMA_messages.strErrorRealRowCount);
179         }
180     });
183 AJAX.registerOnload('db_structure.js', function () {
184     /**
185      * Handler for the print view multisubmit.
186      * All other multi submits can be handled via ajax, but this one needs
187      * special treatment as the results need to open in another browser window
188      */
189     $('#tablesForm').submit(function (event) {
190         var $form = $(this);
191         if ($form.find('select[name=submit_mult]').val() === 'print') {
192             event.preventDefault();
193             event.stopPropagation();
194             $('form#clone').remove();
195             var $clone = $form
196                 .clone()
197                 .hide()
198                 .appendTo('body');
199             $clone
200                 .find('select[name=submit_mult]')
201                 .val('print');
202             $clone
203                 .attr('target', 'printview')
204                 .attr('id', 'clone')
205                 .submit();
206         }
207     });
210  * function to open the confirmation dialog for making table consistent with central list
212  * @param string   msg     message text to be displayedd to user
213  * @param function success function to be called on success
215  */
216     var jqConfirm = function(msg, success) {
217         var dialogObj = $("<div style='display:none'>"+msg+"</div>");
218         $('body').append(dialogObj);
219         var buttonOptions = {};
220         buttonOptions[PMA_messages.strContinue] = function () {
221             success();
222             $( this ).dialog( "close" );
223         };
224         buttonOptions[PMA_messages.strCancel] = function () {
225             $( this ).dialog( "close" );
226             $('#tablesForm')[0].reset();
227         };
228         $(dialogObj).dialog({
229             resizable: false,
230             modal: true,
231             title: PMA_messages.confirmTitle,
232             buttons: buttonOptions
233         });
234     };
237  *  Event handler on select of "Make consistent with central list"
238  */
239     $('select[name=submit_mult]').change(function(event) {
240         if($(this).val() === 'make_consistent_with_central_list') {
241             event.preventDefault();
242             event.stopPropagation();
243             jqConfirm(PMA_messages.makeConsistentMessage, function(){
244                         $('#tablesForm').submit();
245                     });
246             return false;
247         }
248     });
249      /**
250      * Event handler for 'Foreign Key Checks' disabling option
251      * in the drop table confirmation form
252      */
253     $("span.fkc_switch").click(function (event) {
254         if ($("#fkc_checkbox").prop('checked')) {
255             $("#fkc_checkbox").prop('checked', false);
256             $("#fkc_status").html(PMA_messages.strForeignKeyCheckDisabled);
257             return;
258         }
259         $("#fkc_checkbox").prop('checked', true);
260         $("#fkc_status").html(PMA_messages.strForeignKeyCheckEnabled);
261     });
263     $('#fkc_checkbox').change(function () {
264         if ($(this).prop("checked")) {
265             $("#fkc_status").html(PMA_messages.strForeignKeyCheckEnabled);
266             return;
267         }
268         $("#fkc_status").html(PMA_messages.strForeignKeyCheckDisabled);
269     }); // End of event handler for 'Foreign Key Check'
271     /**
272      * Ajax Event handler for 'Truncate Table'
273      */
274     $("a.truncate_table_anchor.ajax").live('click', function (event) {
275         event.preventDefault();
277         /**
278          * @var $this_anchor Object  referring to the anchor clicked
279          */
280         var $this_anchor = $(this);
282         //extract current table name and build the question string
283         /**
284          * @var curr_table_name String containing the name of the table to be truncated
285          */
286         var curr_table_name = $this_anchor.parents('tr').children('th').children('a').text();
287         /**
288          * @var question    String containing the question to be asked for confirmation
289          */
290         var question = PMA_messages.strTruncateTableStrongWarning + ' ' +
291             PMA_sprintf(PMA_messages.strDoYouReally, 'TRUNCATE ' + escapeHtml(curr_table_name));
293         $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) {
295             PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
297             $.get(url, {'is_js_confirmed' : 1, 'ajax_request' : true}, function (data) {
298                 if (typeof data !== 'undefined' && data.success === true) {
299                     PMA_ajaxShowMessage(data.message);
300                     // Adjust table statistics
301                     var $tr = $this_anchor.closest('tr');
302                     $tr.find('.tbl_rows').text('0');
303                     $tr.find('.tbl_size, .tbl_overhead').text('-');
304                     //Fetch inner span of this anchor
305                     //and replace the icon with its disabled version
306                     var span = $this_anchor.html().replace(/b_empty/, 'bd_empty');
307                     //To disable further attempts to truncate the table,
308                     //replace the a element with its inner span (modified)
309                     $this_anchor
310                         .replaceWith(span)
311                         .removeClass('truncate_table_anchor');
312                     PMA_adjustTotals();
313                 } else {
314                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
315                 }
316             }); // end $.get()
317         }); //end $.PMA_confirm()
318     }); //end of Truncate Table Ajax action
320     /**
321      * Ajax Event handler for 'Drop Table' or 'Drop View'
322      */
323     $("a.drop_table_anchor.ajax").live('click', function (event) {
324         event.preventDefault();
326         var $this_anchor = $(this);
328         //extract current table name and build the question string
329         /**
330          * @var $curr_row    Object containing reference to the current row
331          */
332         var $curr_row = $this_anchor.parents('tr');
333         /**
334          * @var curr_table_name String containing the name of the table to be truncated
335          */
336         var curr_table_name = $curr_row.children('th').children('a').text();
337         /**
338          * @var is_view Boolean telling if we have a view
339          */
340         var is_view = $curr_row.hasClass('is_view') || $this_anchor.hasClass('view');
341         /**
342          * @var question    String containing the question to be asked for confirmation
343          */
344         var question;
345         if (! is_view) {
346             question = PMA_messages.strDropTableStrongWarning + ' ' +
347                 PMA_sprintf(PMA_messages.strDoYouReally, 'DROP TABLE ' + escapeHtml(curr_table_name));
348         } else {
349             question =
350                 PMA_sprintf(PMA_messages.strDoYouReally, 'DROP VIEW ' + escapeHtml(curr_table_name));
351         }
353         $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) {
355             var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
357             $.get(url, {'is_js_confirmed' : 1, 'ajax_request' : true}, function (data) {
358                 if (typeof data !== 'undefined' && data.success === true) {
359                     PMA_ajaxShowMessage(data.message);
360                     toggleRowColors($curr_row.next());
361                     $curr_row.hide("medium").remove();
362                     PMA_adjustTotals();
363                     PMA_reloadNavigation();
364                     PMA_ajaxRemoveMessage($msg);
365                 } else {
366                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
367                 }
368             }); // end $.get()
369         }); // end $.PMA_confirm()
370     }); //end of Drop Table Ajax action
372     /**
373      * Ajax Event handler for 'Drop tracking'
374      */
375     $('a.drop_tracking_anchor.ajax').live('click', function (event) {
376         event.preventDefault();
378         var $anchor = $(this);
380         /**
381          * @var curr_tracking_row   Object containing reference to the current tracked table's row
382          */
383         var $curr_tracking_row = $anchor.parents('tr');
384          /**
385          * @var question    String containing the question to be asked for confirmation
386          */
387         var question = PMA_messages.strDeleteTrackingData;
389         $anchor.PMA_confirm(question, $anchor.attr('href'), function (url) {
391             PMA_ajaxShowMessage(PMA_messages.strDeletingTrackingData);
393             $.get(url, {'is_js_confirmed': 1, 'ajax_request': true}, function (data) {
394                 if (typeof data !== 'undefined' && data.success === true) {
395                     var $tracked_table = $curr_tracking_row.parents('table');
396                     var table_name = $curr_tracking_row.find('td:nth-child(2)').text();
398                     // Check how many rows will be left after we remove
399                     if ($tracked_table.find('tbody tr').length === 1) {
400                         // We are removing the only row it has
401                         $('#tracked_tables').hide("slow").remove();
402                     } else {
403                         // There are more rows left after the deletion
404                         toggleRowColors($curr_tracking_row.next());
405                         $curr_tracking_row.hide("slow", function () {
406                             $(this).remove();
407                         });
408                     }
410                     // Make the removed table visible in the list of 'Untracked tables'.
411                     var $untracked_table = $('table#noversions');
413                     // This won't work if no untracked tables are there.
414                     if ($untracked_table.length > 0) {
415                         var $rows = $untracked_table.find('tbody tr');
417                         $rows.each(function (index) {
418                             var $row = $(this);
419                             var tmp_tbl_name = $row.find('td:first-child').text();
420                             var is_last_iteration = (index == ($rows.length - 1));
422                             if (tmp_tbl_name > table_name || is_last_iteration) {
423                                 var $cloned = $row.clone();
425                                 // Change the table name of the cloned row.
426                                 $cloned.find('td:first-child').text(table_name);
428                                 // Change the link of the cloned row.
429                                 var new_url = $cloned
430                                     .find('td:nth-child(2) a')
431                                     .attr('href')
432                                     .replace('table=' + tmp_tbl_name, 'table=' + encodeURIComponent(table_name));
433                                 $cloned.find('td:nth-child(2) a').attr('href', new_url);
435                                 // Insert the cloned row in an appropriate location.
436                                 if (tmp_tbl_name > table_name) {
437                                     $cloned.insertBefore($row);
438                                     toggleRowColors($row);
439                                     return false;
440                                 } else {
441                                     $cloned.insertAfter($row);
442                                     toggleRowColors($cloned);
443                                 }
444                             }
445                         });
446                     }
448                     PMA_ajaxShowMessage(data.message);
449                 } else {
450                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
451                 }
452             }); // end $.get()
453         }); // end $.PMA_confirm()
454     }); //end Drop Tracking
456     //Calculate Real End for InnoDB
457     /**
458      * Ajax Event handler for calculatig the real end for a InnoDB table
459      *
460      */
461     $('#real_end_input').live('click', function (event) {
462         event.preventDefault();
464         /**
465          * @var question    String containing the question to be asked for confirmation
466          */
467         var question = PMA_messages.strOperationTakesLongTime;
469         $(this).PMA_confirm(question, '', function () {
470             return true;
471         });
472         return false;
473     }); //end Calculate Real End for InnoDB
475     PMA_tooltip(
476         $("select[name*='funcs']"),
477         'select',
478         PMA_messages.strFunctionHint
479     );
480     // Add tooltip to favorite icons.
481     $(".favorite_table_anchor").each(function () {
482         PMA_tooltip(
483             $(this),
484             'a',
485             $(this).attr("title")
486         );
487     });
489     // Get real row count via Ajax.
490     $('a.real_row_count').on('click', function (event) {
491         event.preventDefault();
492         PMA_fetchRealRowCount($(this));
493     });
494     // Get all real row count.
495     $('a.row_count_sum').on('click', function (event) {
496         event.preventDefault();
497         PMA_fetchRealRowCount($(this));
498     });
499 }); // end $()