Improve storing columns on designer and add a translation
[phpmyadmin.git] / js / db_structure.js
blob7c0da763b6b6ffb362c2aa3249b8b1f094736fd1
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]').off('change');
33 });
35 /**
36  * Adjust number of rows and total size in the summary
37  * when truncating, creating, dropping or inserting into a table
38  */
39 function PMA_adjustTotals () {
40     var byteUnits = [
41         PMA_messages.strB,
42         PMA_messages.strKiB,
43         PMA_messages.strMiB,
44         PMA_messages.strGiB,
45         PMA_messages.strTiB,
46         PMA_messages.strPiB,
47         PMA_messages.strEiB
48     ];
49     /**
50      * @var $allTr jQuery object that references all the rows in the list of tables
51      */
52     var $allTr = $('#tablesForm').find('table.data tbody:first tr');
53     // New summary values for the table
54     var tableSum = $allTr.size();
55     var rowsSum = 0;
56     var sizeSum = 0;
57     var overheadSum = 0;
58     var rowSumApproximated = false;
60     $allTr.each(function () {
61         var $this = $(this);
62         var i;
63         var 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;
116     var 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.strNTables, tableSum));
132     if (rowSumApproximated) {
133         $summary.find('.row_count_sum').text(strRowSum);
134     } else {
135         $summary.find('.tbl_rows').text(strRowSum);
136     }
137     $summary.find('.tbl_size').text(sizeSum + ' ' + byteUnits[size_magnitude]);
138     $summary.find('.tbl_overhead').text(overheadSum + ' ' + byteUnits[overhead_magnitude]);
142  * Gets the real row count for a table or DB.
143  * @param object $target Target for appending the real count value.
144  */
145 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 class=\'hide\'>' + 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     };
214     /**
215  *  Event handler on select of "Make consistent with central list"
216  */
217     $('select[name=submit_mult]').change(function (event) {
218         if ($(this).val() === 'make_consistent_with_central_list') {
219             event.preventDefault();
220             event.stopPropagation();
221             jqConfirm(
222                 PMA_messages.makeConsistentMessage, function () {
223                     $('#tablesForm').submit();
224                 }
225             );
226             return false;
227         } else if ($(this).val() === 'copy_tbl' || $(this).val() === 'add_prefix_tbl' || $(this).val() === 'replace_prefix_tbl' || $(this).val() === 'copy_tbl_change_prefix') {
228             event.preventDefault();
229             event.stopPropagation();
230             if ($('input[name="selected_tbl[]"]:checked').length === 0) {
231                 return false;
232             }
233             var formData = $('#tablesForm').serialize();
234             var modalTitle = '';
235             if ($(this).val() === 'copy_tbl') {
236                 modalTitle = PMA_messages.strCopyTablesTo;
237             } else if ($(this).val() === 'add_prefix_tbl') {
238                 modalTitle = PMA_messages.strAddPrefix;
239             } else if ($(this).val() === 'replace_prefix_tbl') {
240                 modalTitle = PMA_messages.strReplacePrefix;
241             } else if ($(this).val() === 'copy_tbl_change_prefix') {
242                 modalTitle = PMA_messages.strCopyPrefix;
243             }
244             $.ajax({
245                 type: 'POST',
246                 url: 'db_structure.php',
247                 dataType: 'html',
248                 data: formData
250             }).done(function (data) {
251                 var dialogObj = $('<div class=\'hide\'>' + data + '</div>');
252                 $('body').append(dialogObj);
253                 var buttonOptions = {};
254                 buttonOptions[PMA_messages.strContinue] = function () {
255                     $('#ajax_form').submit();
256                     $(this).dialog('close');
257                 };
258                 buttonOptions[PMA_messages.strCancel] = function () {
259                     $(this).dialog('close');
260                     $('#tablesForm')[0].reset();
261                 };
262                 $(dialogObj).dialog({
263                     minWidth: 500,
264                     resizable: false,
265                     modal: true,
266                     title: modalTitle,
267                     buttons: buttonOptions
268                 });
269             });
270         } else {
271             $('#tablesForm').submit();
272         }
273     });
275     /**
276      * Ajax Event handler for 'Truncate Table'
277      */
278     $(document).on('click', 'a.truncate_table_anchor.ajax', function (event) {
279         event.preventDefault();
281         /**
282          * @var $this_anchor Object  referring to the anchor clicked
283          */
284         var $this_anchor = $(this);
286         // extract current table name and build the question string
287         /**
288          * @var curr_table_name String containing the name of the table to be truncated
289          */
290         var curr_table_name = $this_anchor.parents('tr').children('th').children('a').text();
291         /**
292          * @var question    String containing the question to be asked for confirmation
293          */
294         var question = PMA_messages.strTruncateTableStrongWarning + ' ' +
295             PMA_sprintf(PMA_messages.strDoYouReally, 'TRUNCATE `' + escapeHtml(curr_table_name) + '`') +
296             getForeignKeyCheckboxLoader();
298         $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) {
299             PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
301             var params = getJSConfirmCommonParam(this, $this_anchor.getPostData());
303             $.post(url, params, function (data) {
304                 if (typeof data !== 'undefined' && data.success === true) {
305                     PMA_ajaxShowMessage(data.message);
306                     // Adjust table statistics
307                     var $tr = $this_anchor.closest('tr');
308                     $tr.find('.tbl_rows').text('0');
309                     $tr.find('.tbl_size, .tbl_overhead').text('-');
310                     // Fetch inner span of this anchor
311                     // and replace the icon with its disabled version
312                     var span = $this_anchor.html().replace(/b_empty/, 'bd_empty');
313                     // To disable further attempts to truncate the table,
314                     // replace the a element with its inner span (modified)
315                     $this_anchor
316                         .replaceWith(span)
317                         .removeClass('truncate_table_anchor');
318                     PMA_adjustTotals();
319                 } else {
320                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + ' : ' + data.error, false);
321                 }
322             }); // end $.post()
323         }, loadForeignKeyCheckbox); // end $.PMA_confirm()
324     }); // end of Truncate Table Ajax action
326     /**
327      * Ajax Event handler for 'Drop Table' or 'Drop View'
328      */
329     $(document).on('click', 'a.drop_table_anchor.ajax', function (event) {
330         event.preventDefault();
332         var $this_anchor = $(this);
334         // extract current table name and build the question string
335         /**
336          * @var $curr_row    Object containing reference to the current row
337          */
338         var $curr_row = $this_anchor.parents('tr');
339         /**
340          * @var curr_table_name String containing the name of the table to be truncated
341          */
342         var curr_table_name = $curr_row.children('th').children('a').text();
343         /**
344          * @var is_view Boolean telling if we have a view
345          */
346         var is_view = $curr_row.hasClass('is_view') || $this_anchor.hasClass('view');
347         /**
348          * @var question    String containing the question to be asked for confirmation
349          */
350         var question;
351         if (! is_view) {
352             question = PMA_messages.strDropTableStrongWarning + ' ' +
353                 PMA_sprintf(PMA_messages.strDoYouReally, 'DROP TABLE `' + escapeHtml(curr_table_name) + '`');
354         } else {
355             question =
356                 PMA_sprintf(PMA_messages.strDoYouReally, 'DROP VIEW `' + escapeHtml(curr_table_name) + '`');
357         }
358         question += getForeignKeyCheckboxLoader();
360         $this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) {
361             var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
363             var params = getJSConfirmCommonParam(this, $this_anchor.getPostData());
365             $.post(url, params, function (data) {
366                 if (typeof data !== 'undefined' && data.success === true) {
367                     PMA_ajaxShowMessage(data.message);
368                     $curr_row.hide('medium').remove();
369                     PMA_adjustTotals();
370                     PMA_reloadNavigation();
371                     PMA_ajaxRemoveMessage($msg);
372                 } else {
373                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + ' : ' + data.error, false);
374                 }
375             }); // end $.post()
376         }, loadForeignKeyCheckbox); // end $.PMA_confirm()
377     }); // end of Drop Table Ajax action
379     /**
380      * Attach Event Handler for 'Print' link
381      */
382     $(document).on('click', '#printView', function (event) {
383         event.preventDefault();
385         // Take to preview mode
386         printPreview();
387     }); // end of Print View action
389     // Calculate Real End for InnoDB
390     /**
391      * Ajax Event handler for calculating the real end for a InnoDB table
392      *
393      */
394     $(document).on('click', '#real_end_input', function (event) {
395         event.preventDefault();
397         /**
398          * @var question    String containing the question to be asked for confirmation
399          */
400         var question = PMA_messages.strOperationTakesLongTime;
402         $(this).PMA_confirm(question, '', function () {
403             return true;
404         });
405         return false;
406     }); // end Calculate Real End for InnoDB
408     // Add tooltip to favorite icons.
409     $('.favorite_table_anchor').each(function () {
410         PMA_tooltip(
411             $(this),
412             'a',
413             $(this).attr('title')
414         );
415     });
417     // Get real row count via Ajax.
418     $('a.real_row_count').on('click', function (event) {
419         event.preventDefault();
420         PMA_fetchRealRowCount($(this));
421     });
422     // Get all real row count.
423     $('a.row_count_sum').on('click', function (event) {
424         event.preventDefault();
425         PMA_fetchRealRowCount($(this));
426     });
427 }); // end $()