The display column is shown in pink. To set/unset a column as the display column, click the "Choose column to display" icon, then click on the appropriate column name.
diff --git a/db_search.php b/db_search.php
index c0f2c082af..6242a53d9b 100644
--- a/db_search.php
+++ b/db_search.php
@@ -128,8 +128,7 @@ if (isset($_REQUEST['submit_search'])) {
$sqlstr_delete = 'DELETE';
// Fields to select
- $tblfields = PMA_DBI_fetch_result('SHOW FIELDS FROM ' . PMA_backquote($table) . ' FROM ' . PMA_backquote($GLOBALS['db']),
- null, 'Field');
+ $tblfields = PMA_DBI_get_columns($GLOBALS['db'], $table);
// Table to use
$sqlstr_from = ' FROM ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($table);
@@ -148,8 +147,8 @@ if (isset($_REQUEST['submit_search'])) {
$thefieldlikevalue = array();
foreach ($tblfields as $tblfield) {
- if (! isset($field) || strlen($field) == 0 || $tblfield == $field) {
- $thefieldlikevalue[] = 'CONVERT(' . PMA_backquote($tblfield) . ' USING utf8)'
+ if (! isset($field) || strlen($field) == 0 || $tblfield['Field'] == $field) {
+ $thefieldlikevalue[] = 'CONVERT(' . PMA_backquote($tblfield['Field']) . ' USING utf8)'
. ' ' . $like_or_regex . ' '
. "'" . $automatic_wildcard
. $search_word
diff --git a/js/codemirror/mode/mysql/mysql.js b/js/codemirror/mode/mysql/mysql.js
index 657942d2cd..755e3ec85d 100644
--- a/js/codemirror/mode/mysql/mysql.js
+++ b/js/codemirror/mode/mysql/mysql.js
@@ -1,11 +1,14 @@
CodeMirror.defineMode("mysql", function(config, parserConfig) {
var indentUnit = config.indentUnit,
keywords = parserConfig.keywords,
+ verbs = parserConfig.verbs,
functions = parserConfig.functions,
types = parserConfig.types,
- attributes = parserConfig.attributes,
- multiLineStrings = parserConfig.multiLineStrings;
+ attributes = parserConfig.attributes,
+ multiLineStrings = parserConfig.multiLineStrings,
+ multiPartKeywords= parserConfig.multiPartKeywords;
var isOperatorChar = /[+\-*&%=<>!?:\/|]/;
+
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
@@ -64,14 +67,35 @@ CodeMirror.defineMode("mysql", function(config, parserConfig) {
else {
// get the whole word
stream.eatWhile(/[\w\$_]/);
+ var word = stream.current().toLowerCase();
+ var oldPos = stream.pos;
+ // is it one of the listed verbs?
+ if (verbs && verbs.propertyIsEnumerable(word)) return ret("keyword", "statement-verb");
// is it one of the listed keywords?
- if (keywords && keywords.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "keyword");
+ if (keywords && keywords.propertyIsEnumerable(word)) return ret("keyword", "keyword");
// is it one of the listed functions?
- if (functions && functions.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "builtin");
+ if (functions && functions.propertyIsEnumerable(word)) {
+ // All functions begin with '('
+ stream.eatSpace();
+ if(stream.peek() == '(')
+ return ret("keyword", "builtin");
+ // Not func => restore old pos
+ stream.pos = oldPos;
+ }
// is it one of the listed types?
- if (types && types.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "variable-2");
+ if (types && types.propertyIsEnumerable(word)) return ret("keyword", "variable-2");
// is it one of the listed attributes?
- if (attributes && attributes.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "variable-3");
+ if (attributes && attributes.propertyIsEnumerable(word)) return ret("keyword", "variable-3");
+ // is it a multipart keyword? (currently only checks 2 word parts)
+
+ stream.eatSpace();
+ stream.eatWhile(/[\w\$_]/);
+ var doubleWord = stream.current().toLowerCase();
+ if (multiPartKeywords && multiPartKeywords.propertyIsEnumerable(doubleWord)) return ret("keyword", "keyword");
+
+ // restore old pos
+ stream.pos = oldPos;
+
// default: just a "word"
return ret("word", "mysql-word");
}
@@ -122,11 +146,14 @@ CodeMirror.defineMode("mysql", function(config, parserConfig) {
(function() {
function keywords(str) {
- var obj = {}, words = str.split(" ");
+ var obj = {}, words = str;
+ if(typeof str == 'string') words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
- var cKeywords = "accessible add all alter analyze and as asc asensitive before between bigint binary blob both by call cascade case change char character check collate column condition constraint continue convert create cross current_date current_time current_timestamp current_user cursor database databases day_hour day_microsecond day_minute day_second dec decimal declare default delayed delete desc describe deterministic distinct distinctrow div double drop dual each else elseif enclosed escaped exists exit explain false fetch float float4 float8 for force foreign from fulltext grant group having high_priority hour_microsecond hour_minute hour_second if ignore in index infile inner inout insensitive insert int int1 int2 int3 int4 int8 integer interval into is iterate join key keys kill leading leave left like limit linear lines load localtime localtimestamp lock long longblob longtext loop low_priority master_ssl_verify_server_cert match maxvalue mediumblob mediumint mediumtext middleint minute_microsecond minute_second mod modifies natural not no_write_to_binlog null numeric on optimize option optionally or order out outer outfile precision primary procedure purge range read reads read_write real references regexp release rename repeat replace require resignal restrict return revoke right rlike schema schemas second_microsecond select sensitive separator set show signal smallint spatial specific sql sqlexception sqlstate sqlwarning sql_big_result sql_calc_found_rows sql_small_result ssl starting straight_join table terminated then tinyblob tinyint tinytext to trailing trigger true undo union unique unlock unsigned update usage use using utc_date utc_time utc_timestamp values varbinary varchar varcharacter varying when where while with write xor year_month zerofill";
+ var cKeywords = "accessible add all and as asc asensitive before between bigint binary blob both cascade case char character collate column condition constraint continue convert cross current_date current_time current_timestamp current_user cursor database databases day_hour day_microsecond day_minute day_second dec decimal declare default delayed desc deterministic distinct distinctrow div double dual each else elseif enclosed escaped exists exit explain false fetch float float4 float8 for force foreign fulltext from having high_priority hour_microsecond hour_minute hour_second if ignore in index infile inner inout insensitive int int1 int2 int3 int4 int8 integer interval is iterate join key keys leading leave left like limit linear lines localtime localtimestamp long longblob longtext loop low_priority master_ssl_verify_server_cert match maxvalue mediumblob mediumint mediumtext middleint minute_microsecond minute_second mod modifies natural not no_write_to_binlog null numeric on option optionally or out outer outfile precision primary procedure range read reads read_write real references regexp repeat require restrict return right rlike schema schemas second_microsecond sensitive separator smallint spatial specific sql sqlexception sqlstate sqlwarning sql_big_result sql_calc_found_rows sql_small_result ssl starting straight_join table terminated then tinyblob tinyint tinytext to trailing trigger true undo union unique unsigned usage using utc_date utc_time utc_timestamp values varbinary varchar varcharacter varying when where while with write xor year_month zerofill";
+
+ var cVerbs = "alter analyze begin binlog call change check checksum commit create deallocate describe do drop execute flush grant handler install kill load lock optimize cache partition prepare purge release rename repair replace reset resignal revoke rollback savepoint select set signal show start truncate uninstall unlock update use xa";
var cFunctions = "abs acos adddate addtime aes_decrypt aes_encrypt area asbinary ascii asin astext atan atan2 avg bdmpolyfromtext bdmpolyfromwkb bdpolyfromtext bdpolyfromwkb benchmark bin bit_and bit_count bit_length bit_or bit_xor boundary buffer cast ceil ceiling centroid char character_length charset char_length coalesce coercibility collation compress concat concat_ws connection_id contains conv convert convert_tz convexhull cos cot count crc32 crosses curdate current_date current_time current_timestamp current_user curtime database date datediff date_add date_diff date_format date_sub day dayname dayofmonth dayofweek dayofyear decode default degrees des_decrypt des_encrypt difference dimension disjoint distance elt encode encrypt endpoint envelope equals exp export_set exteriorring extract extractvalue field find_in_set floor format found_rows from_days from_unixtime geomcollfromtext geomcollfromwkb geometrycollection geometrycollectionfromtext geometrycollectionfromwkb geometryfromtext geometryfromwkb geometryn geometrytype geomfromtext geomfromwkb get_format get_lock glength greatest group_concat group_unique_users hex hour if ifnull inet_aton inet_ntoa insert instr interiorringn intersection intersects interval isclosed isempty isnull isring issimple is_free_lock is_used_lock last_day last_insert_id lcase least left length linefromtext linefromwkb linestring linestringfromtext linestringfromwkb ln load_file localtime localtimestamp locate log log10 log2 lower lpad ltrim makedate maketime make_set master_pos_wait max mbrcontains mbrdisjoint mbrequal mbrintersects mbroverlaps mbrtouches mbrwithin md5 microsecond mid min minute mlinefromtext mlinefromwkb mod month monthname mpointfromtext mpointfromwkb mpolyfromtext mpolyfromwkb multilinestring multilinestringfromtext multilinestringfromwkb multipoint multipointfromtext multipointfromwkb multipolygon multipolygonfromtext multipolygonfromwkb name_const now nullif numgeometries numinteriorrings numpoints oct octet_length old_password ord overlaps password period_add period_diff pi point pointfromtext pointfromwkb pointn pointonsurface polyfromtext polyfromwkb polygon polygonfromtext polygonfromwkb position pow power quarter quote radians rand related release_lock repeat replace reverse right round row_count rpad rtrim schema second sec_to_time session_user sha sha1 sign sin sleep soundex space sqrt srid startpoint std stddev stddev_pop stddev_samp strcmp str_to_date subdate substr substring substring_index subtime sum symdifference sysdate system_user tan time timediff timestamp timestampadd timestampdiff time_format time_to_sec touches to_days trim truncate ucase uncompress uncompressed_length unhex unique_users unix_timestamp updatexml upper user utc_date utc_time utc_timestamp uuid variance var_pop var_samp version week weekday weekofyear within x y year yearweek";
@@ -134,11 +161,15 @@ CodeMirror.defineMode("mysql", function(config, parserConfig) {
var cAttributes = "archive ascii auto_increment bdb berkeleydb binary blackhole csv default example federated heap innobase innodb isam maria memory merge mrg_isam mrg_myisam myisam national ndb ndbcluster precision undefined unicode unsigned varying zerofill";
+ var cmultiPartKeywords = ['insert into', 'group by', 'order by', 'delete from'];
+
CodeMirror.defineMIME("text/x-mysql", {
name: "mysql",
keywords: keywords(cKeywords),
+ multiPartKeywords: keywords(cmultiPartKeywords),
+ verbs: keywords(cVerbs),
functions: keywords(cFunctions),
types: keywords(cTypes),
attributes: keywords(cAttributes)
});
-}());
+}());
\ No newline at end of file
diff --git a/js/functions.js b/js/functions.js
index 54a08d5371..022cb808c1 100644
--- a/js/functions.js
+++ b/js/functions.js
@@ -1617,7 +1617,13 @@ function PMA_createProfilingChart(data, options)
},options));
}
-// Formats a profiling duration nicely. Used in PMA_createProfilingChart() and server_status.js
+/**
+ * Formats a profiling duration nicely (in us and ms time). Used in PMA_createProfilingChart() and server_status.js
+ *
+ * @param integer Number to be formatted, should be in the range of microsecond to second
+ * @param integer Acuracy, how many numbers right to the comma should be
+ * @return string The formatted number
+ */
function PMA_prettyProfilingNum(num, acc)
{
if (!acc) {
@@ -1635,6 +1641,150 @@ function PMA_prettyProfilingNum(num, acc)
return num + 's';
}
+
+/**
+ * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
+ *
+ * @param string Query to be formatted
+ * @return string The formatted query
+ */
+function PMA_SQLPrettyPrint(string)
+{
+ var mode = CodeMirror.getMode({},"text/x-mysql");
+ var stream = new CodeMirror.StringStream(string);
+ var state = mode.startState();
+ var token, tokens = [];
+ var output = '';
+ var tabs = function(cnt) {
+ var ret = '';
+ for (var i=0; i<4*cnt; i++)
+ ret += " ";
+ return ret;
+ };
+
+ // "root-level" statements
+ var statements = {
+ 'select': ['select', 'from','on','where','having','limit','order by','group by'],
+ 'update': ['update', 'set','where'],
+ 'insert into': ['insert into', 'values']
+ };
+ // don't put spaces before these tokens
+ var spaceExceptionsBefore = { ';':true, ',': true, '.': true, '(': true };
+ // don't put spaces after these tokens
+ var spaceExceptionsAfter = { '.': true };
+
+ // Populate tokens array
+ var str='';
+ while (! stream.eol()) {
+ stream.start = stream.pos;
+ token = mode.token(stream, state);
+ if(token != null) {
+ tokens.push([token, stream.current().toLowerCase()]);
+ }
+ }
+
+ var currentStatement = tokens[0][1];
+
+ if(! statements[currentStatement]) {
+ return string;
+ }
+ // Holds all currently opened code blocks (statement, function or generic)
+ var blockStack = [];
+ // Holds the type of block from last iteration (the current is in blockStack[0])
+ var previousBlock;
+ // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
+ var newBlock, endBlock;
+ // How much to indent in the current line
+ var indentLevel = 0;
+ // Holds the "root-level" statements
+ var statementPart, lastStatementPart = statements[currentStatement][0];
+
+ blockStack.unshift('statement');
+
+ // Iterate through every token and format accordingly
+ for (var i = 0; i < tokens.length; i++) {
+ previousBlock = blockStack[0];
+
+ // New block => push to stack
+ if (tokens[i][1] == '(') {
+ if (i < tokens.length - 1 && tokens[i+1][0] == 'statement-verb') {
+ blockStack.unshift(newBlock = 'statement');
+ } else if (i > 0 && tokens[i-1][0] == 'builtin') {
+ blockStack.unshift(newBlock = 'function');
+ } else {
+ blockStack.unshift(newBlock = 'generic');
+ }
+ } else {
+ newBlock = null;
+ }
+
+ // Block end => pop from stack
+ if (tokens[i][1] == ')') {
+ endBlock = blockStack[0];
+ blockStack.shift();
+ } else {
+ endBlock = null;
+ }
+
+ // A subquery is starting
+ if (i > 0 && newBlock == 'statement') {
+ indentLevel++;
+ output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i+1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
+ currentStatement = tokens[i+1][1];
+ i++;
+ continue;
+ }
+
+ // A subquery is ending
+ if (endBlock == 'statement' && indentLevel > 0) {
+ output += "\n" + tabs(indentLevel);
+ indentLevel--;
+ }
+
+ // One less indentation for statement parts (from, where, order by, etc.) and a newline
+ statementPart = statements[currentStatement].indexOf(tokens[i][1]);
+ if (statementPart != -1) {
+ if (i > 0) output += "\n";
+ output += tabs(indentLevel) + tokens[i][1].toUpperCase();
+ output += "\n" + tabs(indentLevel + 1);
+ lastStatementPart = tokens[i][1];
+ }
+ // Normal indentatin and spaces for everything else
+ else {
+ if (! spaceExceptionsBefore[tokens[i][1]]
+ && ! (i > 0 && spaceExceptionsAfter[tokens[i-1][1]])
+ && output.charAt(output.length -1) != ' ' ) {
+ output += " ";
+ }
+ if (tokens[i][0] == 'keyword') {
+ output += tokens[i][1].toUpperCase();
+ } else {
+ output += tokens[i][1];
+ }
+ }
+
+ // split columns in select and 'update set' clauses, but only inside statements blocks
+ if (( lastStatementPart == 'select' || lastStatementPart == 'where' || lastStatementPart == 'set')
+ && tokens[i][1]==',' && blockStack[0] == 'statement') {
+
+ output += "\n" + tabs(indentLevel + 1);
+ }
+
+ // split conditions in where clauses, but only inside statements blocks
+ if (lastStatementPart == 'where'
+ && (tokens[i][1]=='and' || tokens[i][1]=='or' || tokens[i][1]=='xor')) {
+
+ if (blockStack[0] == 'statement') {
+ output += "\n" + tabs(indentLevel + 1);
+ }
+ // Todo: Also split and or blocks in newlines & identation++
+ //if(blockStack[0] == 'generic')
+ // output += ...
+ }
+ }
+ return output;
+}
+
/**
* jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
* return a jQuery object yet and hence cannot be chained
@@ -3157,8 +3307,6 @@ function PMA_getCellValue(td) {
return '';
} else if (! $(td).is('.to_be_saved') && $(td).data('original_data')) {
return $(td).data('original_data');
- } else if ($(td).is(':not(.transformed, .relation, .enum, .set, .null)')) {
- return unescape($(td).find('span').html()).replace(/ /g, "\n");
} else {
return $(td).text();
}
diff --git a/js/makegrid.js b/js/makegrid.js
index aabe9b59cd..70e9b9adb1 100644
--- a/js/makegrid.js
+++ b/js/makegrid.js
@@ -564,7 +564,7 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
!g.colRsz && !g.colReorder)
{
if (!g.isCellEditActive) {
- $cell = $(cell);
+ var $cell = $(cell);
// remove all edit area and hide it
$(g.cEdit).find('.edit_area').empty().hide();
// reposition the cEdit element
@@ -573,24 +573,19 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
left: $cell.position().left
})
.show()
- .find('input')
+ .find('.edit_box')
.css({
width: $cell.outerWidth(),
height: $cell.outerHeight()
});
- // fill the cell edit with text from
, if it is not null
- var value = $cell.is(':not(.null)') ? PMA_getCellValue(cell) : '';
- $(g.cEdit).find('input')
- .val(value);
+ // fill the cell edit with text from
+ var value = PMA_getCellValue(cell);
+ $(g.cEdit).find('.edit_box').val(value);
g.currentEditCell = cell;
- $(g.cEdit).find('input[type=text]').focus();
+ $(g.cEdit).find('.edit_box').focus();
$(g.cEdit).find('*').removeAttr('disabled');
}
- } else {
- if (g.isCellEditActive) {
- g.hideEditCell();
- }
}
},
@@ -605,7 +600,7 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
*/
hideEditCell: function(force, data, field) {
if (g.isCellEditActive && !force) {
- // cell is being edited, post the edited data
+ // cell is being edited, save or post the edited data
g.saveOrPostEditedCell();
return;
}
@@ -620,21 +615,19 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
if (g.currentEditCell) { // save value of currently edited cell
// replace current edited field with the new value
var $this_field = $(g.currentEditCell);
- var new_html = $this_field.data('value');
var is_null = $this_field.data('value') == null;
if (is_null) {
$this_field.find('span').html('NULL');
$this_field.addClass('null');
} else {
$this_field.removeClass('null');
+ var new_html = $this_field.data('value');
if ($this_field.is('.truncated')) {
if (new_html.length > g.maxTruncatedLen) {
new_html = new_html.substring(0, g.maxTruncatedLen) + '...';
}
}
- // replace '\n' with
- new_html = new_html.replace(/\n/g, ' ');
- $this_field.find('span').html(new_html);
+ $this_field.find('span').text(new_html);
}
}
if (data.transformations != undefined) {
@@ -657,7 +650,7 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
// hide the cell editing area
$(g.cEdit).hide();
- $(g.cEdit).find('input[type=text]').blur();
+ $(g.cEdit).find('.edit_box').blur();
g.isCellEditActive = false;
g.currentEditCell = null;
// destroy datepicker in edit area, if exist
@@ -671,8 +664,17 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
if (!g.isCellEditActive) { // make sure the edit area has not been shown
g.isCellEditActive = true;
g.isEditCellTextEditable = false;
+ /**
+ * @var $td current edited cell
+ */
var $td = $(g.currentEditCell);
+ /**
+ * @var $editArea the editing area
+ */
var $editArea = $(g.cEdit).find('.edit_area');
+ /**
+ * @var where_clause WHERE clause for the edited cell
+ */
var where_clause = $td.parent('tr').find('.where_clause').val();
/**
* @var field_name String containing the name of this field.
@@ -720,24 +722,24 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
if ($td.is('.enum, .set')) {
$editArea.find('select').live('change', function(e) {
$checkbox.attr('checked', false);
- })
+ });
} else if ($td.is('.relation')) {
$editArea.find('select').live('change', function(e) {
$checkbox.attr('checked', false);
- })
+ });
$editArea.find('.browse_foreign').live('click', function(e) {
$checkbox.attr('checked', false);
- })
+ });
} else {
- $(g.cEdit).find('input[type=text]').live('keypress change', function(e) {
+ $(g.cEdit).find('.edit_box').live('keypress change', function(e) {
$checkbox.attr('checked', false);
- })
+ });
$editArea.find('textarea').live('keydown', function(e) {
$checkbox.attr('checked', false);
- })
+ });
}
- // if 'checkbox_null__' is clicked empty the corresponding select/editor.
+ // if null checkbox is clicked empty the corresponding select/editor.
$checkbox.click(function(e) {
if ($td.is('.enum')) {
$editArea.find('select').attr('value', '');
@@ -745,7 +747,7 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
$editArea.find('select').find('option').each(function() {
var $option = $(this);
$option.attr('selected', false);
- })
+ });
} else if ($td.is('.relation')) {
// if the dropdown is there to select the foreign value
if ($editArea.find('select').length > 0) {
@@ -754,12 +756,11 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
} else {
$editArea.find('textarea').val('');
}
- $(g.cEdit).find('input[type=text]').val('');
- })
+ $(g.cEdit).find('.edit_box').val('');
+ });
}
- if($td.is('.relation')) {
- /** @lends jQuery */
+ if ($td.is('.relation')) {
//handle relations
$editArea.addClass('edit_area_loading');
@@ -770,15 +771,15 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
* @var post_params Object containing parameters for the POST request
*/
var post_params = {
- 'ajax_request' : true,
- 'get_relational_values' : true,
- 'server' : g.server,
- 'db' : g.db,
- 'table' : g.table,
- 'column' : field_name,
- 'token' : g.token,
- 'curr_value' : relation_curr_value,
- 'relation_key_or_display_column' : relation_key_or_display_column
+ 'ajax_request' : true,
+ 'get_relational_values' : true,
+ 'server' : g.server,
+ 'db' : g.db,
+ 'table' : g.table,
+ 'column' : field_name,
+ 'token' : g.token,
+ 'curr_value' : relation_curr_value,
+ 'relation_key_or_display_column' : relation_key_or_display_column
}
g.lastXHR = $.post('sql.php', post_params, function(data) {
@@ -788,18 +789,18 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
var value = $(data.dropdown).val();
$td.data('original_data', value);
// update the text input field, in case where the "Relational display column" is checked
- $(g.cEdit).find('input[type=text]').val(value);
+ $(g.cEdit).find('.edit_box').val(value);
$editArea.append(data.dropdown);
$editArea.append('