Translated using Weblate (Belarusian)
[phpmyadmin.git] / js / db_structure.js
blobb7cd057e8f0153acb8d4ea6569796371d41391f8
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     $(document).off('click', '#printView');
30     $('a.real_row_count').off('click');
31     $('a.row_count_sum').off('click');
32     $('select[name=submit_mult]').unbind('change');
33     $("#filterText").unbind('keyup');
34 });
36 /**
37  * Adjust number of rows and total size in the summary
38  * when truncating, creating, dropping or inserting into a table
39  */
40 function PMA_adjustTotals() {
41     var byteUnits = [
42         PMA_messages.strB,
43         PMA_messages.strKiB,
44         PMA_messages.strMiB,
45         PMA_messages.strGiB,
46         PMA_messages.strTiB,
47         PMA_messages.strPiB,
48         PMA_messages.strEiB
49     ];
50     /**
51      * @var $allTr jQuery object that references all the rows in the list of tables
52      */
53     var $allTr = $("#tablesForm").find("table.data tbody:first tr");
54     // New summary values for the table
55     var tableSum = $allTr.size();
56     var rowsSum = 0;
57     var sizeSum = 0;
58     var overheadSum = 0;
59     var rowSumApproximated = false;
61     $allTr.each(function () {
62         var $this = $(this);
63         var i, tmpVal;
64         // Get the number of rows for this SQL table
65         var strRows = $this.find('.tbl_rows').text();
66         // If the value is approximated
67         if (strRows.indexOf('~') === 0) {
68             rowSumApproximated = true;
69             // The approximated value contains a preceding ~ (Eg 100 --> ~100)
70             strRows = strRows.substring(1, strRows.length);
71         }
72         strRows = strRows.replace(/[,.]/g, '');
73         var intRow = parseInt(strRows, 10);
74         if (! isNaN(intRow)) {
75             rowsSum += intRow;
76         }
77         // Extract the size and overhead
78         var valSize         = 0;
79         var valOverhead     = 0;
80         var strSize         = $.trim($this.find('.tbl_size span:not(.unit)').text());
81         var strSizeUnit     = $.trim($this.find('.tbl_size span.unit').text());
82         var strOverhead     = $.trim($this.find('.tbl_overhead span:not(.unit)').text());
83         var strOverheadUnit = $.trim($this.find('.tbl_overhead span.unit').text());
84         // Given a value and a unit, such as 100 and KiB, for the table size
85         // and overhead calculate their numeric values in bytes, such as 102400
86         for (i = 0; i < byteUnits.length; i++) {
87             if (strSizeUnit == byteUnits[i]) {
88                 tmpVal = parseFloat(strSize);
89                 valSize = tmpVal * Math.pow(1024, i);
90                 break;
91             }
92         }
93         for (i = 0; i < byteUnits.length; i++) {
94             if (strOverheadUnit == byteUnits[i]) {
95                 tmpVal = parseFloat(strOverhead);
96                 valOverhead = tmpVal * Math.pow(1024, i);
97                 break;
98             }
99         }
100         sizeSum += valSize;
101         overheadSum += valOverhead;
102     });
103     // Add some commas for readability:
104     // 1000000 becomes 1,000,000
105     var strRowSum = rowsSum + "";
106     var regex = /(\d+)(\d{3})/;
107     while (regex.test(strRowSum)) {
108         strRowSum = strRowSum.replace(regex, '$1' + ',' + '$2');
109     }
110     // If approximated total value add ~ in front
111     if (rowSumApproximated) {
112         strRowSum = "~" + strRowSum;
113     }
114     // Calculate the magnitude for the size and overhead values
115     var size_magnitude = 0, overhead_magnitude = 0;
116     while (sizeSum >= 1024) {
117         sizeSum /= 1024;
118         size_magnitude++;
119     }
120     while (overheadSum >= 1024) {
121         overheadSum /= 1024;
122         overhead_magnitude++;
123     }
125     sizeSum = Math.round(sizeSum * 10) / 10;
126     overheadSum = Math.round(overheadSum * 10) / 10;
128     // Update summary with new data
129     var $summary = $("#tbl_summary_row");
130     $summary.find('.tbl_num').text(PMA_sprintf(PMA_messages.strNTables, tableSum));
131     if (rowSumApproximated) {
132         $summary.find('.row_count_sum').text(strRowSum);
133     } else {
134         $summary.find('.tbl_rows').text(strRowSum);
135     }
136     $summary.find('.tbl_size').text(sizeSum + " " + byteUnits[size_magnitude]);
137     $summary.find('.tbl_overhead').text(overheadSum + " " + byteUnits[overhead_magnitude]);
141  * Gets the real row count for a table or DB.
142  * @param object $target Target for appending the real count value.
143  */
144 function PMA_fetchRealRowCount($target)
146     var $throbber = $('#pma_navigation').find('.throbber')
147         .first()
148         .clone()
149         .css({visibility: 'visible', display: 'inline-block'})
150         .click(false);
151     $target.html($throbber);
152     $.ajax({
153         type: 'GET',
154         url: $target.attr('href'),
155         cache: false,
156         dataType: 'json',
157         success: function (response) {
158             if (response.success) {
159                 // If to update all row counts for a DB.
160                 if (response.real_row_count_all) {
161                     $.each(JSON.parse(response.real_row_count_all),
162                         function (index, table) {
163                             // Update each table row count.
164                             $('table.data td[data-table*="' + table.table + '"]')
165                             .text(table.row_count);
166                         }
167                     );
168                 }
169                 // If to update a particular table's row count.
170                 if (response.real_row_count) {
171                     // Append the parent cell with real row count.
172                     $target.parent().text(response.real_row_count);
173                 }
174                 // Adjust the 'Sum' displayed at the bottom.
175                 PMA_adjustTotals();
176             } else {
177                 PMA_ajaxShowMessage(PMA_messages.strErrorRealRowCount);
178             }
179         },
180         error: function () {
181             PMA_ajaxShowMessage(PMA_messages.strErrorRealRowCount);
182         }
183     });
186 AJAX.registerOnload('db_structure.js', function () {
188  * function to open the confirmation dialog for making table consistent with central list
190  * @param string   msg     message text to be displayed to user
191  * @param function success function to be called on success
193  */
194     var jqConfirm = function(msg, success) {
195         var dialogObj = $("<div style='display:none'>"+msg+"</div>");
196         $('body').append(dialogObj);
197         var buttonOptions = {};
198         buttonOptions[PMA_messages.strContinue] = function () {
199             success();
200             $( this ).dialog( "close" );
201         };
202         buttonOptions[PMA_messages.strCancel] = function () {
203             $( this ).dialog( "close" );
204             $('#tablesForm')[0].reset();
205         };
206         $(dialogObj).dialog({
207             resizable: false,
208             modal: true,
209             title: PMA_messages.confirmTitle,
210             buttons: buttonOptions
211         });
212     };
215 * Filtering tables on table listing of particular database
218     $("#filterText").keyup(function() {
219         var filterInput = $(this).val().toUpperCase();
220         var structureTable = $('#structureTable')[0];
221         $('#structureTable tbody tr').each(function() {
222             var tr = $(this);
223             var a = tr.find('a')[0];
224             if (a) {
225                 if (a.text.trim().toUpperCase().indexOf(filterInput) > -1) {
226                     tr[0].style.display = "";
227                 } else {
228                     tr[0].style.display = "none";
229                 }
230             }
231         });
232     });
235  *  Event handler on select of "Make consistent with central list"
236  */
237     $('select[name=submit_mult]').change(function(event) {
238         if ($(this).val() === 'make_consistent_with_central_list') {
239             event.preventDefault();
240             event.stopPropagation();
241             jqConfirm(
242                 PMA_messages.makeConsistentMessage, function(){
243                     $('#tablesForm').submit();
244                 }
245             );
246             return false;
247         }
248         else if ($(this).val() === 'copy_tbl' || $(this).val() === 'add_prefix_tbl' || $(this).val() === 'replace_prefix_tbl' || $(this).val() === 'copy_tbl_change_prefix') {
249             event.preventDefault();
250             event.stopPropagation();
251             if ($('input[name="selected_tbl[]"]:checked').length === 0) {
252                 return false;
253             }
254             var formData = $('#tablesForm').serialize();
255             var modalTitle = '';
256             if ($(this).val() === 'copy_tbl') {
257                 modalTitle = PMA_messages.strCopyTablesTo;
258             }
259             else if ($(this).val() === 'add_prefix_tbl') {
260                 modalTitle = PMA_messages.strAddPrefix;
261             }
262             else if ($(this).val() === 'replace_prefix_tbl') {
263                 modalTitle = PMA_messages.strReplacePrefix;
264             }
265             else if ($(this).val() === 'copy_tbl_change_prefix') {
266                 modalTitle = PMA_messages.strCopyPrefix;
267             }
268             $.ajax({
269                 type: 'POST',
270                 url: 'db_structure.php',
271                 dataType: 'html',
272                 data: formData
274             }).done(function(data) {
276                 var dialogObj = $("<div style='display:none'>"+data+"</div>");
277                 $('body').append(dialogObj);
278                 var buttonOptions = {};
279                 buttonOptions[PMA_messages.strContinue] = function () {
280                     $('#ajax_form').submit();
281                     $( this ).dialog( "close" );
282                 };
283                 buttonOptions[PMA_messages.strCancel] = function () {
284                     $( this ).dialog( "close" );
285                     $('#tablesForm')[0].reset();
286                 };
287                 $(dialogObj).dialog({
288                     minWidth: 500,
289                     resizable: false,
290                     modal: true,
291                     title: modalTitle,
292                     buttons: buttonOptions
293                 });
294             });
295         }
296         else {
297             $('#tablesForm').submit();
298         }
299     });
301     /**
302      * Ajax Event handler for 'Truncate Table'
303      */
304     $(document).on('click', "a.truncate_table_anchor.ajax", function (event) {
305         event.preventDefault();
307         /**
308          * @var $this_anchor Object  referring to the anchor clicked
309          */
310         var $this_anchor = $(this);
312         //extract current table name and build the question string
313         /**
314          * @var curr_table_name String containing the name of the table to be truncated
315          */
316         var curr_table_name = $this_anchor.parents('tr').children('th').children('a').text();
317         /**
318          * @var question    String containing the question to be asked for confirmation
319          */
320         var question = PMA_messages.strTruncateTableStrongWarning + ' ' +
321             PMA_sprintf(PMA_messages.strDoYouReally, 'TRUNCATE `' + escapeHtml(curr_table_name) + '`') +
322             getForeignKeyCheckboxLoader();
324         $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) {
326             PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
328             var params = getJSConfirmCommonParam(this);
329             params.token = PMA_commonParams.get('token');
331             $.post(url, params, function (data) {
332                 if (typeof data !== 'undefined' && data.success === true) {
333                     PMA_ajaxShowMessage(data.message);
334                     // Adjust table statistics
335                     var $tr = $this_anchor.closest('tr');
336                     $tr.find('.tbl_rows').text('0');
337                     $tr.find('.tbl_size, .tbl_overhead').text('-');
338                     //Fetch inner span of this anchor
339                     //and replace the icon with its disabled version
340                     var span = $this_anchor.html().replace(/b_empty/, 'bd_empty');
341                     //To disable further attempts to truncate the table,
342                     //replace the a element with its inner span (modified)
343                     $this_anchor
344                         .replaceWith(span)
345                         .removeClass('truncate_table_anchor');
346                     PMA_adjustTotals();
347                 } else {
348                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
349                 }
350             }); // end $.post()
351         }, loadForeignKeyCheckbox); //end $.PMA_confirm()
352     }); //end of Truncate Table Ajax action
354     /**
355      * Ajax Event handler for 'Drop Table' or 'Drop View'
356      */
357     $(document).on('click', "a.drop_table_anchor.ajax", function (event) {
358         event.preventDefault();
360         var $this_anchor = $(this);
362         //extract current table name and build the question string
363         /**
364          * @var $curr_row    Object containing reference to the current row
365          */
366         var $curr_row = $this_anchor.parents('tr');
367         /**
368          * @var curr_table_name String containing the name of the table to be truncated
369          */
370         var curr_table_name = $curr_row.children('th').children('a').text();
371         /**
372          * @var is_view Boolean telling if we have a view
373          */
374         var is_view = $curr_row.hasClass('is_view') || $this_anchor.hasClass('view');
375         /**
376          * @var question    String containing the question to be asked for confirmation
377          */
378         var question;
379         if (! is_view) {
380             question = PMA_messages.strDropTableStrongWarning + ' ' +
381                 PMA_sprintf(PMA_messages.strDoYouReally, 'DROP TABLE `' + escapeHtml(curr_table_name) + '`');
382         } else {
383             question =
384                 PMA_sprintf(PMA_messages.strDoYouReally, 'DROP VIEW `' + escapeHtml(curr_table_name) + '`');
385         }
386         question += getForeignKeyCheckboxLoader();
388         $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) {
390             var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
392             var params = getJSConfirmCommonParam(this);
393             params.token = PMA_commonParams.get('token');
395             $.post(url, params, function (data) {
396                 if (typeof data !== 'undefined' && data.success === true) {
397                     PMA_ajaxShowMessage(data.message);
398                     $curr_row.hide("medium").remove();
399                     PMA_adjustTotals();
400                     PMA_reloadNavigation();
401                     PMA_ajaxRemoveMessage($msg);
402                 } else {
403                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
404                 }
405             }); // end $.post()
406         }, loadForeignKeyCheckbox); // end $.PMA_confirm()
407     }); //end of Drop Table Ajax action
409     /**
410      * Attach Event Handler for 'Print' link
411      */
412     $(document).on('click', "#printView", function (event) {
413         event.preventDefault();
415         // Take to preview mode
416         printPreview();
417     }); //end of Print View action
419     //Calculate Real End for InnoDB
420     /**
421      * Ajax Event handler for calculating the real end for a InnoDB table
422      *
423      */
424     $(document).on('click', '#real_end_input', function (event) {
425         event.preventDefault();
427         /**
428          * @var question    String containing the question to be asked for confirmation
429          */
430         var question = PMA_messages.strOperationTakesLongTime;
432         $(this).PMA_confirm(question, '', function () {
433             return true;
434         });
435         return false;
436     }); //end Calculate Real End for InnoDB
438     // Add tooltip to favorite icons.
439     $(".favorite_table_anchor").each(function () {
440         PMA_tooltip(
441             $(this),
442             'a',
443             $(this).attr("title")
444         );
445     });
447     // Get real row count via Ajax.
448     $('a.real_row_count').on('click', function (event) {
449         event.preventDefault();
450         PMA_fetchRealRowCount($(this));
451     });
452     // Get all real row count.
453     $('a.row_count_sum').on('click', function (event) {
454         event.preventDefault();
455         PMA_fetchRealRowCount($(this));
456     });
457 }); // end $()