Welcome to mirror list, hosted at ThFree Co, Russian Federation.

tbl_structure.js « js - github.com/phpmyadmin/phpmyadmin.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ebcd00a695792a25c04844874b5333a2568de776 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * @fileoverview    functions used on the table structure page
 * @name            Table Structure
 *
 * @requires    jQuery
 * @requires    jQueryUI
 * @required    js/functions.js
 */

/**
 * AJAX scripts for tbl_structure.php
 *
 * Actions ajaxified here:
 * Drop Column
 * Add Primary Key
 * Drop Primary Key/Index
 *
 */

/**
 * This function returns the horizontal space available for the menu in pixels.
 * To calculate this value we start we the width of the main panel, then we
 * substract the margin of the page content, then we substract any cellspacing
 * that the table may have (original theme only) and finally we substract the
 * width of all columns of the table except for the last one (which is where
 * the menu will go). What we should end up with is the distance between the
 * start of the last column on the table and the edge of the page, again this
 * is the space available for the menu.
 *
 * In the case where the table cell where the menu will be displayed is already
 * off-screen (the table is wider than the page), a negative value will be returned,
 * but this will be treated as a zero by the menuResizer plugin.
 *
 * @return int
 */
function PMA_tbl_structure_menu_resizer_callback() {
    var pagewidth = $('body').width();
    var $page = $('#page_content');
    pagewidth -= $page.outerWidth(true) - $page.outerWidth();
    var columnsWidth = 0;
    var $columns = $('#tablestructure').find('tr:eq(1)').find('td,th');
    $columns.not(':last').each(function () {
        columnsWidth += $(this).outerWidth(true);
    });
    var totalCellSpacing = $('#tablestructure').width();
    $columns.each(function () {
        totalCellSpacing -= $(this).outerWidth(true);
    });
    return pagewidth - columnsWidth - totalCellSpacing - 15; // 15px extra margin
}

/**
 * Reload fields table
 */
function reloadFieldForm() {
    $.post($("#fieldsForm").attr('action'), $("#fieldsForm").serialize() + "&ajax_request=true", function (form_data) {
        var $temp_div = $("<div id='temp_div'><div>").append(form_data.message);
        $("#fieldsForm").replaceWith($temp_div.find("#fieldsForm"));
        $("#addColumns").replaceWith($temp_div.find("#addColumns"));
        $('#move_columns_dialog ul').replaceWith($temp_div.find("#move_columns_dialog ul"));
        $("#moveColumns").removeClass("move-active");
        /* reinitialise the more options in table */
        $('#fieldsForm ul.table-structure-actions').menuResizer(PMA_tbl_structure_menu_resizer_callback);
    });
    $('#page_content').show();
}

/**
 * Displays table structure edit page
 *
 * @param data data from AJAX call
 * @param $msg loading message.
 *
 * @returns void
 */
function showTableStructureEditPage(data, $msg) {
    PMA_ajaxRemoveMessage($msg);
    if (data.success) {
        $('#page_content')
            .empty()
            .append(
                $('<div id="change_column_dialog"></div>')
                    .html(data.message)
            );
        PMA_highlightSQL($('#page_content'));
        PMA_showHints();
        PMA_verifyColumnsProperties();
    } else {
        PMA_ajaxShowMessage(data.error);
    }
}

/**
 * Unbind all event handlers before tearing down a page
 */
AJAX.registerTeardown('tbl_structure.js', function () {
    $("a.change_column_anchor.ajax").die('click');
    $("button.change_columns_anchor.ajax, input.change_columns_anchor.ajax").die('click');
    $("a.drop_column_anchor.ajax").die('click');
    $("a.add_primary_key_anchor.ajax").die('click');
    $("a.add_index_anchor.ajax").die('click');
    $("a.add_unique_anchor.ajax").die('click');
    $("#move_columns_anchor").die('click');
    $(".append_fields_form.ajax").unbind('submit');
    $('body').off('click', '#fieldsForm.ajax button[name="submit_mult"], #fieldsForm.ajax input[name="submit_mult"]');
});

AJAX.registerOnload('tbl_structure.js', function () {

    // Re-initialize variables.
    primary_indexes = [];
    unique_indexes = [];
    indexes = [];
    fulltext_indexes = [];

    /**
     *Ajax action for submitting the "Column Change" and "Add Column" form
     */
    $(".append_fields_form.ajax").die().live('submit', function (event) {
        event.preventDefault();
        /**
         * @var    the_form    object referring to the export form
         */
        var $form = $(this);

        /*
         * First validate the form; if there is a problem, avoid submitting it
         *
         * checkTableEditForm() needs a pure element and not a jQuery object,
         * this is why we pass $form[0] as a parameter (the jQuery object
         * is actually an array of DOM elements)
         */
        if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
            // OK, form passed validation step
            PMA_prepareForAjaxRequest($form);
            //User wants to submit the form
            $msg = PMA_ajaxShowMessage();
            $.post($form.attr('action'), $form.serialize() + '&do_save_data=1', function (data) {
                if ($("#sqlqueryresults").length !== 0) {
                    $("#sqlqueryresults").remove();
                } else if ($(".error:not(.tab)").length !== 0) {
                    $(".error:not(.tab)").remove();
                }
                if (typeof data.success != 'undefined' && data.success === true) {
                    $("#page_content")
                        .empty()
                        .append(data.message)
                        .append(data.sql_query)
                        .show();
                    PMA_highlightSQL($('#page_content'));
                    $("#result_query .notice").remove();
                    reloadFieldForm();
                    $form.remove();
                    PMA_ajaxRemoveMessage($msg);
                    PMA_init_slider();
                    PMA_reloadNavigation();
                } else {
                    PMA_ajaxShowMessage(data.error, false);
                }
            }); // end $.post()
        }
    }); // end change table button "do_save_data"

    /**
     * Attach Event Handler for 'Change Column'
     */
    $("a.change_column_anchor.ajax").live('click', function (event) {
        event.preventDefault();
        var $msg = PMA_ajaxShowMessage();
        $.get($(this).attr('href'), {'ajax_request': true}, function (data) {
            showTableStructureEditPage(data, $msg);
        });
    });

    /**
     * Attach Event Handler for 'Change multiple columns'
     */
    $("button.change_columns_anchor.ajax, input.change_columns_anchor.ajax").live('click', function (event) {
        event.preventDefault();
        var $msg = PMA_ajaxShowMessage();
        var $form = $(this).closest('form');
        var params = $form.serialize() + "&ajax_request=true&submit_mult=change";
        $.post($form.prop("action"), params, function (data) {
            showTableStructureEditPage(data, $msg);
        });
    });

    /**
     * Attach Event Handler for 'Drop Column'
     */
    $("a.drop_column_anchor.ajax").live('click', function (event) {
        event.preventDefault();
        /**
         * @var curr_table_name String containing the name of the current table
         */
        var curr_table_name = $(this).closest('form').find('input[name=table]').val();
        /**
         * @var curr_row    Object reference to the currently selected row (i.e. field in the table)
         */
        var $curr_row = $(this).parents('tr');
        /**
         * @var curr_column_name    String containing name of the field referred to by {@link curr_row}
         */
        var curr_column_name = $curr_row.children('th').children('label').text();
        curr_column_name = escapeHtml(curr_column_name);
        /**
         * @var $after_field_item    Corresponding entry in the 'After' field.
         */
        var $after_field_item = $("select[name='after_field'] option[value='" + curr_column_name + "']");
        /**
         * @var question    String containing the question to be asked for confirmation
         */
        var question = PMA_sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` DROP `' + escapeHtml(curr_column_name) + '`;');
        $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
            var $msg = PMA_ajaxShowMessage(PMA_messages.strDroppingColumn, false);
            $.get(url, {'is_js_confirmed' : 1, 'ajax_request' : true, 'ajax_page_request' : true}, function (data) {
                if (typeof data !== 'undefined' && data.success === true) {
                    PMA_ajaxRemoveMessage($msg);
                    if ($('#result_query').length) {
                        $('#result_query').remove();
                    }
                    if (data.sql_query) {
                        $('<div id="result_query"></div>')
                            .html(data.sql_query)
                            .prependTo('#page_content');
                        PMA_highlightSQL($('#page_content'));
                    }
                    toggleRowColors($curr_row.next());
                    // Adjust the row numbers
                    for (var $row = $curr_row.next(); $row.length > 0; $row = $row.next()) {
                        var new_val = parseInt($row.find('td:nth-child(2)').text(), 10) - 1;
                        $row.find('td:nth-child(2)').text(new_val);
                    }
                    $after_field_item.remove();
                    $curr_row.hide("medium").remove();
                    //refresh table stats
                    if (data.tableStat) {
                        $('#tablestatistics').html(data.tableStat);
                    }
                    // refresh the list of indexes (comes from sql.php)
                    $('.index_info').replaceWith(data.indexes_list);
                    PMA_reloadNavigation();
                } else {
                    PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
                }
            }); // end $.get()
        }); // end $.PMA_confirm()
    }); //end of Drop Column Anchor action

    /**
     * Ajax Event handler for 'Add Primary Key'
     */
    $("a.add_primary_key_anchor.ajax").live('click', function (event) {
        event.preventDefault();
        /**
         * @var curr_table_name String containing the name of the current table
         */
        var curr_table_name = $(this).closest('form').find('input[name=table]').val();
        /**
         * @var curr_column_name    String containing name of the field referred to by {@link curr_row}
         */
        var curr_column_name = $(this).parents('tr').children('th').children('label').text();
        /**
         * @var question    String containing the question to be asked for confirmation
         */
        var question = PMA_sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` ADD PRIMARY KEY(`' + escapeHtml(curr_column_name) + '`);');
        $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
            var $msg = PMA_ajaxShowMessage(PMA_messages.strAddingPrimaryKey, false);
            $.get(url,
                {'is_js_confirmed' : 1, 'ajax_request' : true, 'index_change' : true},
                function (data) {
                if (typeof data !== 'undefined' && data.success === true) {
                    PMA_ajaxRemoveMessage($msg);
                    $(this).remove();
                    if (typeof data.reload != 'undefined') {
                        PMA_commonActions.refreshMain(false, function () {
                            if ($('#result_query').length) {
                                $('#result_query').remove();
                            }
                            if (data.sql_query) {
                                $('<div id="result_query"></div>')
                                    .html(data.sql_query)
                                    .prependTo('#page_content');
                                PMA_highlightSQL($('#page_content'));
                            }
                        });
                        PMA_reloadNavigation();
                    }
                    if (data.indexes_list) {
                        $('.index_info').replaceWith(data.indexes_list);
                    }
                } else {
                    PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
                }
            }); // end $.get()
        }); // end $.PMA_confirm()
    }); //end Add Primary Key

    /**
     * Ajax Event handler for 'Add Index'
     */
    $("a.add_index_anchor.ajax").live('click', function (event) {
        event.preventDefault();
        /**
         * @var curr_table_name String containing the name of the current table
         */
        var curr_table_name = $(this).closest('form').find('input[name=table]').val();
        /**
         * @var curr_column_name    String containing name of the field referred to by {@link curr_row}
         */
        var curr_column_name = $(this).parents('tr').children('th').children('label').text();
        /**
         * @var question    String containing the question to be asked for confirmation
         */
        var question = PMA_sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` ADD INDEX(`' + escapeHtml(curr_column_name) + '`);');
        $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
            var $msg = PMA_ajaxShowMessage(PMA_messages.strAddingIndex, false);
            $.get(url,
                {'is_js_confirmed' : 1, 'ajax_request' : true, 'index_change' : true},
                function (data) {
                if (typeof data !== 'undefined' && data.success === true) {
                    PMA_ajaxRemoveMessage($msg);
                    if ($('#result_query').length) {
                        $('#result_query').remove();
                    }
                    if (data.sql_query) {
                        $('<div id="result_query"></div>')
                            .html(data.sql_query)
                            .prependTo('#page_content');
                        PMA_highlightSQL($('#page_content'));
                    }
                    if (data.indexes_list) {
                        $('.index_info').replaceWith(data.indexes_list);
                    }
                    PMA_reloadNavigation();
                } else {
                    PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
                }
            }); // end $.get()
        }); // end $.PMA_confirm()
    }); //end Add Index

    /**
     * Ajax Event handler for 'Add Unique'
     */
    $("a.add_unique_anchor.ajax").live('click', function (event) {
        event.preventDefault();
        /**
         * @var curr_table_name String containing the name of the current table
         */
        var curr_table_name = $(this).closest('form').find('input[name=table]').val();
        /**
         * @var curr_column_name    String containing name of the field referred to by {@link curr_row}
         */
        var curr_column_name = $(this).parents('tr').children('th').children('label').text();
        /**
         * @var question    String containing the question to be asked for confirmation
         */
        var question = PMA_sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` ADD UNIQUE(`' + escapeHtml(curr_column_name) + '`);');
        $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
            var $msg = PMA_ajaxShowMessage(PMA_messages.strAddingUnique, false);
            $.get(url,
                {'is_js_confirmed' : 1, 'ajax_request' : true, 'index_change' : true},
                function (data) {
                if (typeof data !== 'undefined' && data.success === true) {
                    PMA_ajaxRemoveMessage($msg);
                    if ($('#result_query').length) {
                        $('#result_query').remove();
                    }
                    if (data.sql_query) {
                        $('<div id="result_query"></div>')
                            .html(data.sql_query)
                            .prependTo('#page_content');
                        PMA_highlightSQL($('#page_content'));
                    }
                    if (data.indexes_list) {
                        $('.index_info').replaceWith(data.indexes_list);
                    }
                    PMA_reloadNavigation();
                } else {
                    PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
                }
            }); // end $.get()
        }); // end $.PMA_confirm()
    }); //end Add Unique

    /**
     * Inline move columns
    **/
    $("#move_columns_anchor").live('click', function (e) {
        e.preventDefault();

        if ($(this).hasClass("move-active")) {
            return;
        }

        /**
         * @var    button_options  Object that stores the options passed to jQueryUI
         *                          dialog
         */
        var button_options = {};

        button_options[PMA_messages.strGo] = function (event) {
            event.preventDefault();
            var $msgbox = PMA_ajaxShowMessage();
            var $this = $(this);
            var $form = $this.find("form");
            var serialized = $form.serialize();

            // check if any columns were moved at all
            if (serialized == $form.data("serialized-unmoved")) {
                PMA_ajaxRemoveMessage($msgbox);
                $this.dialog('close');
                return;
            }

            $.post($form.prop("action"), serialized + "&ajax_request=true", function (data) {
                if (data.success === false) {
                    PMA_ajaxRemoveMessage($msgbox);
                    $this
                    .clone()
                    .html(data.error)
                    .dialog({
                        title: $(this).prop("title"),
                        height: 230,
                        width: 900,
                        modal: true,
                        buttons: button_options_error
                    }); // end dialog options
                } else {
                    $('#fieldsForm ul.table-structure-actions').menuResizer('destroy');
                    // sort the fields table
                    var $fields_table = $("table#tablestructure tbody");
                    // remove all existing rows and remember them
                    var $rows = $fields_table.find("tr").remove();
                    // loop through the correct order
                    for (var i in data.columns) {
                        var the_column = data.columns[i];
                        var $the_row = $rows
                            .find("input:checkbox[value=" + the_column + "]")
                            .closest("tr");
                        // append the row for this column to the table
                        $fields_table.append($the_row);
                    }
                    var $firstrow = $fields_table.find("tr").eq(0);
                    // Adjust the row numbers and colors
                    for (var $row = $firstrow; $row.length > 0; $row = $row.next()) {
                        $row
                        .find('td:nth-child(2)')
                        .text($row.index() + 1)
                        .end()
                        .removeClass("odd even")
                        .addClass($row.index() % 2 === 0 ? "odd" : "even");
                    }
                    PMA_ajaxShowMessage(data.message);
                    $this.dialog('close');
                    $('#fieldsForm ul.table-structure-actions').menuResizer(PMA_tbl_structure_menu_resizer_callback);
                }
            });
        };
        button_options[PMA_messages.strCancel] = function () {
            $(this).dialog('close');
        };

        var button_options_error = {};
        button_options_error[PMA_messages.strOK] = function () {
            $(this).dialog('close').remove();
        };

        var columns = [];

        $("#tablestructure tbody tr").each(function () {
            var col_name = $(this).find("input:checkbox").eq(0).val();
            var hidden_input = $("<input/>")
                .prop({
                    name: "move_columns[]",
                    type: "hidden"
                })
                .val(col_name);
            columns[columns.length] = $("<li/>")
                .addClass("placeholderDrag")
                .text(col_name)
                .append(hidden_input);
        });

        var col_list = $("#move_columns_dialog ul")
            .find("li").remove().end();
        for (var i in columns) {
            col_list.append(columns[i]);
        }
        col_list.sortable({
            axis: 'y',
            containment: $("#move_columns_dialog div"),
            tolerance: 'pointer'
        }).disableSelection();
        var $form = $("#move_columns_dialog form");
        $form.data("serialized-unmoved", $form.serialize());

        $("#move_columns_dialog").dialog({
            modal: true,
            buttons: button_options,
            open: function () {
                if ($('#move_columns_dialog').parents('.ui-dialog').height() > $(window).height()) {
                    $('#move_columns_dialog').dialog("option", "height", $(window).height());
                }
            },
            beforeClose: function () {
                $("#move_columns_anchor").removeClass("move-active");
            }
        });
    });

    /**
     * Handles multi submits in table structure page such as browse, drop, primary etc.
     * However this does not handle multiple field changes. It is handled by a seperate handler.
     */
    $('body').on('click', '#fieldsForm.ajax button[name="submit_mult"], #fieldsForm.ajax input[name="submit_mult"]', function (e) {
        var $button = $(this);
        if (! $button.is('.change_columns_anchor.ajax')) {
            e.preventDefault();
            var $form = $button.parent('form');
            var submitData = $form.serialize() + '&ajax_request=true&ajax_page_request=true&submit_mult=' + $button.val();
            PMA_ajaxShowMessage();
            $.get($form.attr('action'), submitData, AJAX.responseHandler);
        }
    });
});

/** Handler for "More" dropdown in structure table rows */
AJAX.registerOnload('tbl_structure.js', function () {
    if ($('#fieldsForm').hasClass('HideStructureActions')) {
        $('#fieldsForm ul.table-structure-actions').menuResizer(PMA_tbl_structure_menu_resizer_callback);
    }
});
AJAX.registerTeardown('tbl_structure.js', function () {
    $('#fieldsForm ul.table-structure-actions').menuResizer('destroy');
});
$(function () {
    $(window).resize($.throttle(function () {
        var $list = $('#fieldsForm ul.table-structure-actions');
        if ($list.length) {
            $list.menuResizer('resize');
        }
    }));
});