Commit graph

157 commits

Author SHA1 Message Date
Igor Babaev
b3b5d57e78 MDEV-24823 Crash with invalid multi-table update of view in 2nd execution of SP
Before this patch mergeable derived tables / view used in a multi-table
update / delete were merged before the preparation stage.
When the merge of a derived table / view is performed the on expression
attached to it is fixed and ANDed with the where condition of the select S
containing this derived table / view. It happens after the specification of
the derived table / view has been merged into S. If the ON expression refers
to a non existing field an error is reported and some other mergeable derived
tables / views remain unmerged. It's not a problem if the multi-table
update / delete statement is standalone. Yet if it is used in a stored
procedure the select with incompletely merged derived tables / views may
cause a problem for the second call of the procedure. This does not happen
for select queries using derived tables / views, because in this case their
specifications are merged after the preparation stage at which all ON
expressions are fixed.
This patch makes sure that merging of the derived tables / views used in a
multi-table update / delete statement is performed after the preparation
stage.

Approved by Oleksandr Byelkin <sanja@mariadb.com>
2021-04-22 13:56:50 -07:00
Oleksandr Byelkin
50653e021f Merge branch '10.1' into 10.2 2019-06-13 16:42:21 +02:00
Oleksandr Byelkin
5b65d61d93 Merge branch '5.5' into 10.1 2019-06-12 22:54:46 +02:00
Sergei Golubchik
6660c072ad MDEV-19491 update query stopped working after mariadb upgrade 10.2.23 -> 10.2.24
as well as

MDEV-19500 Update with join stopped worked if there is a call to a procedure in a trigger
MDEV-19521 Update Table Fails with Trigger and Stored Function
MDEV-19497 Replication stops because table not found
MDEV-19527 UPDATE + JOIN + TRIGGERS = table doesn't exists error

Reimplement the fix for (5d510fdbf0)

MDEV-18507 can't update temporary table when joined with table with triggers on read-only

instead of calling open_tables() twice, put multi-update
prepare code inside open_tables() loop.

Add a test for a MDL backoff-and-retry loop inside open_tables()
across multi-update prepare code.
2019-06-01 09:43:40 +02:00
Sergei Golubchik
1d4ac3d4d3 cleanup 2019-06-01 09:43:40 +02:00
Oleksandr Byelkin
8cbb14ef5d Merge branch '10.1' into 10.2 2019-05-04 17:04:55 +02:00
Sergei Golubchik
2ce52790ff Merge branch '5.5' into 10.1 2019-04-26 14:02:37 +02:00
Sergei Golubchik
5d510fdbf0 MDEV-18507 can't update temporary table when joined with table with triggers on read-only
triggers are opened and tables used in triggers are prelocked in
open_tables(). But multi-update can detect what tables will actually
be updated only later, after all main tables are opened.

Meaning, if a table is used in multi-update, but is not actually updated,
its on-update treggers will be opened and tables will be prelocked,
even if it's unnecessary. This can cause more tables to be
write-locked than needed, causing read_only errors, privilege errors
and lock waits.

Fix: don't open/prelock triggers unless table->updating is true.
In multi-update after setting table->updating=true, do a second
open_tables() for newly added tables, if any.
2019-04-24 11:15:38 +02:00
Nirbhay Choubey
8b2e642aa2 MDEV-7635: Update tests to adapt to the new default sql_mode 2017-02-10 06:30:42 -05:00
Nirbhay Choubey
3435e8a515 MDEV-7635: Part 1
innodb_autoinc_lock_mode            = 2
innodb_buffer_pool_dump_at_shutdown = ON
innodb_buffer_pool_dump_pct         = 25
innodb_buffer_pool_load_at_startup  = ON
innodb_checksum_algorithm           = CRC32
innodb_file_format                  = Barracuda
innodb_large_prefix                 = ON
innodb_log_compressed_pages         = ON
innodb_purge_threads                = 4
innodb_strict_mode                  = ON
binlog_annotate_row_events          = ON
binlog_format                       = MIXED
binlog-row-event-max-size           = 8192
group_concat_max_len                = 1M
lock_wait_timeout                   = 86400
log_slow_admin_statements           = ON
log_slow_slave_statements           = ON
log_warnings                        = 2
max_allowed_packet                  = 16M
replicate_annotate_row_events       = ON
slave_net_timeout                   = 60
sync_binlog                         = 1
aria_recover                        = BACKUP,QUICK
myisam_recover_options              = BACKUP,QUICK
2017-02-10 06:30:42 -05:00
Sergei Golubchik
ab89359dde enable tests that were skipped because of have_xtradb
* some of these tests run just fine with InnoDB:
   -> s/have_xtradb/have_innodb/
* sys_var tests did basic tests for xtradb only variables
   -> remove them, they're useless anyway (sysvar_innodb does it better)
* multi_update had innodb specific tests
   -> move to multi_update_innodb.test
2016-12-29 13:23:49 +01:00
Sergei Golubchik
932646b1ff Merge branch '10.1' into 10.2 2016-06-30 16:38:05 +02:00
Sergei Golubchik
3361aee591 Merge branch '10.0' into 10.1 2016-06-28 22:01:55 +02:00
Oleksandr Byelkin
911af69d1e MDEV-5973: MySQL Bug#11757486:49539: NON-DESCRIPTIVE ERR (ERROR 0 FROM STORAGE ENGINE) WITH MULTI-TABLE UPDATE
Condition in processing IGNORE clause for UPDATE & multi-table UPDATE made the same.
2016-06-21 18:48:14 +02:00
Sergey Vojtovich
282497dd6d MDEV-6720 - enable connection log in mysqltest by default 2016-03-31 10:11:16 +04:00
Alexander Barkov
5c9c8ef1ea MDEV-3929 Add system variable explicit_defaults_for_timestamp for compatibility with MySQL 2015-09-22 14:01:54 +04:00
Oleksandr Byelkin
e3982cead2 MDEV-6066: Merge new defaults from 5.6 and 5.7 (defaults changed, QC can be stopped with no-zero size) 2015-09-04 10:33:56 +02:00
Sergei Golubchik
49c853fb94 Merge branch '5.5' into 10.0 2015-05-04 22:00:24 +02:00
Oleksandr Byelkin
8cbaafd22b MDEV-8018: main.multi_update fails with --ps-protocol
save_prep_leaf_tables() made recursive to work with underlying view

Arena restoiring fixed in case of EOM.
2015-04-22 13:59:18 +02:00
Oleksandr Byelkin
b9a75862ea MDEV-7613: MariaDB 5.5.40 server crash on update table left join with a view
Multi-update do not need full list of leaf tables. It also do not use it on prepare (mysql_multi_update_prepare()).
2015-04-15 09:53:33 +02:00
Sergei Golubchik
d3e2e1243b 5.5 merge 2014-05-09 12:35:11 +02:00
unknown
45a91d8cbb MDEV-6193: Problems with multi-table updates that JOIN against read-only table
All underlying tables should share the same lock type.
2014-05-08 22:56:36 +03:00
Igor Babaev
12eb6d88f7 Fixed the problem of mdev-5970:
back-ported the patch for bug #13256831 from mysql-5.6 code line.

  Here's the comment this patch was provided with:

  Fixed bug#13256831 - ERROR 1032 (HY000): CAN'T FIND RECORD.

  This bug only occurs if a user tries to update a base table using
  an updatable view and this view was created as a join for which
  the clause 'WITH CHECK OPTION' was specified.

  The reason for the bug was that when such an update was
  executed, row positions were not properly handled for tables
  that were not updated but had constraints that had to be
  checked due to the 'WITH CHECK OPTION' clause.

  The reason for the bug was that when such update is executed
  then for tables specified in the view definition and
  also listed in the 'WITH CHECK OPTION' clause the positioning to
  row being updated is not performed.
2014-04-17 12:53:53 -07:00
unknown
968f4d4e25 MDEV-6139: UPDATE w/ join against MRG_MyISAM table with read-only sub-table failsUPDATE w/ join against MRG_MyISAM table with read-only sub-table fails
The problem was that on opening all tables TL_WRITE, than local tables which is not updated set to TL_READ, but underlying tables of MyISAMmrg left untouched.

Prartition engine has not this problem.

All cases where lock_type assigned is not changed because call of virtual function is not cheap.
2014-04-28 09:13:53 +03:00
Michael Widenius
43f6e118fe Fixes for CREATE_OR_REPLACE
- MDEV-5587 Server crashes in Locked_tables_list::restore_lock on CREATE OR REPLACE .. SELECT under LOCK
- MDEV-5586 Assertion `share->tdc.all_tables.is_empty() || remove_type != TDC_RT_REMOVE_ALL' fails in tdc_remove_table
- MDEV-5588 Strange error on CREATE OR REPLACE table over an existing view

mysql-test/r/create_or_replace.result:
  Added test cases
mysql-test/r/lowercase_view.result:
  New error message
mysql-test/r/merge.result:
  New error message
mysql-test/r/multi_update.result:
  New error message
mysql-test/r/subselect.result:
  New error message
mysql-test/r/subselect_exists_to_in.result:
  New error message
mysql-test/r/subselect_no_mat.result:
  New error message
mysql-test/r/subselect_no_opts.result:
  New error message
mysql-test/r/subselect_no_scache.result:
  New error message
mysql-test/r/subselect_no_semijoin.result:
  New error message
mysql-test/r/view.result:
  New error message
mysql-test/suite/funcs_1/r/myisam_views-big.result:
  New error message
mysql-test/t/create_or_replace.test:
  New tests
mysql-test/t/view.test:
  New error message
sql/share/errmsg-utf8.txt:
  Added new error message
sql/sql_base.cc:
  Updated error message
  Do an automatic UNLOCK TABLES if we don't have any locked tables (safety fix)
sql/sql_db.cc:
  Updated arguments
sql/sql_load.cc:
  New error message
sql/sql_parse.cc:
  Check that we are not using a table we are dropping and re-creating
sql/sql_table.cc:
  Added parameter to mysql_rm_table_no_locks() to not automaticly do UNLOCK TABLES
  Added better error message if trying to drop a view with DROP TABLE
  Don't try to create something we select from
sql/sql_table.h:
  Updated prototypes
2014-01-31 12:06:28 +02:00
Sergei Golubchik
6ae5f0efea MDEV-5115 RBR from MySQL 5.6 to MariaDB 10.0 does not work
Patially merge WL#5917, to understand v2 row events
2013-12-09 12:37:45 +01:00
Sergei Golubchik
13dca0125a more post-merge fixes:
* update results
* don't force HA_CREATE_DELAY_KEY_WRITE on all temp tables,
  (bad for CREATE ... LIKE) instead imply it in myisam/aria
* restore HA_ERR_TABLE_DEF_CHANGED in archive
* increase the default number of rwlock classes in P_S to fit all our rwlocks
2013-07-21 19:24:20 +02:00
unknown
0e7410a154 Merge 10.0-base -> 10.0 (GTID). 2013-04-17 15:17:01 +02:00
Sergei Golubchik
a9035be5b7 10.0-base merge 2013-04-15 15:09:22 +02:00
unknown
665a31af2b MDEV-26: Global transaction ID. First alpha release.
Merge of 10.0-mdev26 feature tree into 10.0-base.

Global transaction ID is prepended to each event group in the binlog.

Slave connect can request to start from GTID position instead of specifying
file name/offset of master binlog. This facilitates easy switch to a new
master.

Slave GTID state is stored in a table mysql.rpl_slave_state, which can be
InnoDB to get crash-safe slave state.

GTID includes a replication domain ID, allowing to keep track of distinct
positions for each of multiple masters.
2013-04-15 10:55:27 +02:00
unknown
d9f975d08b MDEV-26: Global transaction ID
Adjust full test suite to work with GTID.

Huge patch, mainly due to having to update .result file for all SHOW BINLOG
EVENTS and mysqlbinlog outputs, where the new GTID events pop up.

Everything was painstakingly checked to be still correct and valid .result
file updates.
2013-03-26 10:35:34 +01:00
Sergei Golubchik
213f1c76a0 5.3->5.5 merge 2013-02-28 22:47:29 +01:00
unknown
3f36dfe38c MDEV-4123 fix.
Missed update_used_tables() call for multi-update values.
2013-02-11 10:55:58 +02:00
Sergei Golubchik
474fe6d9d9 fixes for test failures
and small collateral changes

mysql-test/lib/My/Test.pm:
  somehow with "print" we get truncated writes sometimes
mysql-test/suite/perfschema/r/digest_table_full.result:
  md5 hashes of statement digests differ, because yacc token codes are different in mariadb
mysql-test/suite/perfschema/r/dml_handler.result:
  host table is not ported over yet
mysql-test/suite/perfschema/r/information_schema.result:
  host table is not ported over yet
mysql-test/suite/perfschema/r/nesting.result:
  this differs, because we don't rewrite general log queries, and multi-statement
  packets are logged as a one entry. this result file is identical to what mysql-5.6.5
  produces with the --log-raw option.
mysql-test/suite/perfschema/r/relaylog.result:
  MariaDB modifies the binlog index file directly, while MySQL 5.6 has a feature "crash-safe binlog index" and modifies a special "crash-safe" shadow copy of the index file and then moves it over. That's why this test shows "NONE" index file writes in MySQL and "MANY" in MariaDB.
mysql-test/suite/perfschema/r/server_init.result:
  MariaDB initializes the "manager" resources from the "manager" thread, and starts this thread only when --flush-time is not 0. MySQL 5.6 initializes "manager" resources unconditionally on server startup.
mysql-test/suite/perfschema/r/stage_mdl_global.result:
  this differs, because MariaDB disables query cache when query_cache_size=0. MySQL does not
  do that, and this causes useless mutex locks and waits.
mysql-test/suite/perfschema/r/statement_digest.result:
  md5 hashes of statement digests differ, because yacc token codes are different in mariadb
mysql-test/suite/perfschema/r/statement_digest_consumers.result:
  md5 hashes of statement digests differ, because yacc token codes are different in mariadb
mysql-test/suite/perfschema/r/statement_digest_long_query.result:
  md5 hashes of statement digests differ, because yacc token codes are different in mariadb
mysql-test/suite/rpl/r/rpl_mixed_drop_create_temp_table.result:
  will be updated to match 5.6 when alfranio.correia@oracle.com-20110512172919-c1b5kmum4h52g0ni and anders.song@greatopensource.com-20110105052107-zoab0bsf5a6xxk2y are merged
mysql-test/suite/rpl/r/rpl_non_direct_mixed_mixing_engines.result:
  will be updated to match 5.6 when anders.song@greatopensource.com-20110105052107-zoab0bsf5a6xxk2y is merged
2012-09-27 20:09:46 +02:00
Sergei Golubchik
20e706689d mysql-5.5.22 merge
mysql-test/suite/innodb/t/group_commit_crash.test:
  remove autoincrement to avoid rbr being used for insert ... select
mysql-test/suite/innodb/t/group_commit_crash_no_optimize_thread.test:
  remove autoincrement to avoid rbr being used for insert ... select
mysys/my_addr_resolve.c:
  a pointer to a buffer is returned to the caller -> the buffer cannot be on the stack
mysys/stacktrace.c:
  my_vsnprintf() is ok here, in 5.5
2012-03-28 01:04:46 +02:00
Rohit Kalhans
ba7d726c48 fixing test failure on pb2. 2012-02-13 15:37:50 +05:30
Rohit Kalhans
701cef2d35 BUG#11758263: Modification of indentation in the added code.
Fixed a typo in the comment.
              Fixing test cases which were previouslyno throwing  due
              disable warnings macro. 

sql/sql_base.cc:
  Change in indentation and fixing a typo in the comment.
2012-02-13 14:12:13 +05:30
Sergei Golubchik
4f435bddfd 5.3 merge 2012-01-13 15:50:02 +01:00
Sergei Golubchik
2ccf247e93 after merge changes:
* rename all debugging related command-line options
  and variables to start from "debug-", and made them all
  OFF by default.
* replace "MySQL" with "MariaDB" in error messages
* "Cast ... converted ... integer to it's ... complement"
  is now a note, not a warning
* @@query_cache_strip_comments now has a session scope,
  not global.
2011-12-12 23:58:40 +01:00
Michael Widenius
24e452a208 Merge with 5.1 & fixes to IGNORE handling 2011-12-11 19:28:05 +02:00
Sergei Golubchik
76f0b94bb0 merge with 5.3
sql/sql_insert.cc:
  CREATE ... IF NOT EXISTS may do nothing, but
  it is still not a failure. don't forget to my_ok it.
  ******
  CREATE ... IF NOT EXISTS may do nothing, but
  it is still not a failure. don't forget to my_ok it.
sql/sql_table.cc:
  small cleanup
  ******
  small cleanup
2011-10-19 21:45:18 +02:00
Jorgen Loland
5a0e7394a5 BUG#11882110: UPDATE REPORTS ER_KEY_NOT_FOUND IF TABLE IS
UPDATED TWICE

For multi update it is not allowed to update a column
of a table if that table is accessed through multiple aliases
and either
1) the updated column is used as partitioning key
2) the updated column is part of the primary key 
   and the primary key is clustered

This check is done in unsafe_key_update().

The bug was that for case 2), it was checked whether
updated_column_number == table_share->primary_key 
However, the primary_key variable is the index number of the 
primary key, not a column number.

Prior to this bugfix, the first column was wrongly believed to be
the primary key. The columns covered by an index is found in
table->key_info[idx_number]->key_part. The bugfix is to check if
any of the columns in the keyparts of the primary key are
updated.

The user-visible effect is that for storage engines with
clustered primary key (e.g. InnoDB but not MyISAM) queries
like 
"UPDATE t1 AS A JOIN t2 AS B SET A.primkey=..."
will now error with 
"ERROR HY000: Primary key/partition key update is not allowed 
since the table is updated both as 'A' and 'B'." 
instead of 
"ERROR 1032 (HY000): Can't find record in 't1_tb'"
even if primkey is not the first column in the table. This 
was the intended behavior of bugfix 11764529.


mysql-test/r/multi_update.result:
  Add test for bug#11882110
mysql-test/r/multi_update_innodb.result:
  Add test for bug#11882110
mysql-test/t/multi_update.test:
  Add test for bug#11882110
mysql-test/t/multi_update_innodb.test:
  Add test for bug#11882110
sql/sql_update.cc:
  unsafe_key_update() wrongly checked if the primary key index
  number was the same as updated column number. Now it is checked
  whether any of the columns making up the primary key is updated.
sql/table.h:
  Fix comment on TABLE_SHARE::primary_key. Incorrect comment
  was introduced by an earlier merge conflict (as per dlenev)
2011-06-16 08:24:00 +02:00
Igor Babaev
078b59f5bc Merge of mwl #106 into 5.3. 2011-06-15 21:48:38 -07:00
Sergei Golubchik
9b98cae4cc merge with 5.1-micro 2011-06-07 18:13:02 +02:00
Igor Babaev
f03a3ee54f Merged the code of mwl 106 into the latest 5.3 with mwl 90 pushed.
Resolved all conflicts and failures.
2011-06-04 19:56:06 -07:00
Michael Widenius
f197991f41 Merge with 5.1-microseconds
A lot of small fixes and new test cases.

client/mysqlbinlog.cc:
  Cast removed
client/mysqltest.cc:
  Added missing DBUG_RETURN
include/my_pthread.h:
  set_timespec_time_nsec() now only takes one argument
mysql-test/t/date_formats.test:
  Remove --disable_ps_protocl as now also ps supports microseconds
mysys/my_uuid.c:
  Changed to use my_interval_timer() instead of my_getsystime()
mysys/waiting_threads.c:
  Changed to use my_hrtime()
sql/field.h:
  Added bool special_const_compare() for fields that may convert values before compare (like year)
sql/field_conv.cc:
  Added test to get optimal copying of identical temporal values.
sql/item.cc:
  Return that item_int is equal if it's positive, even if unsigned flag is different.
  Fixed Item_cache_str::save_in_field() to have identical null check as other similar functions
  Added proper NULL check to Item_cache_int::save_in_field()
sql/item_cmpfunc.cc:
  Don't call convert_constant_item() if there is nothing that is worth converting.
  Simplified test when years should be converted
sql/item_sum.cc:
  Mark cache values in Item_sum_hybrid as not constants to ensure they are not replaced by other cache values in compare_datetime()
sql/item_timefunc.cc:
  Changed sec_to_time() to take a my_decimal argument to ensure we don't loose any sub seconds.
  Added Item_temporal_func::get_time() (This simplifies some things)
sql/mysql_priv.h:
  Added Lazy_string_decimal()
sql/mysqld.cc:
  Added my_decimal constants max_seconds_for_time_type, time_second_part_factor
sql/table.cc:
  Changed expr_arena to be of type CONVENTIONAL_EXECUTION to ensure that we don't loose any items that are created by fix_fields()
sql/tztime.cc:
  TIME_to_gmt_sec() now sets *in_dst_time_gap in case of errors
  This is needed to be able to detect if timestamp is 0
storage/maria/lockman.c:
  Changed from my_getsystime() to set_timespec_time_nsec()
storage/maria/ma_loghandler.c:
  Changed from my_getsystime() to my_hrtime()
storage/maria/ma_recovery.c:
  Changed from my_getsystime() to mmicrosecond_interval_timer()
storage/maria/unittest/trnman-t.c:
  Changed from my_getsystime() to mmicrosecond_interval_timer()
storage/xtradb/handler/ha_innodb.cc:
  Added support for new time,datetime and timestamp
unittest/mysys/thr_template.c:
  my_getsystime() -> my_interval_timer()
unittest/mysys/waiting_threads-t.c:
  my_getsystime() -> my_interval_timer()
2011-05-28 05:11:32 +03:00
Igor Babaev
c9a349488b Applied Sanja's patch to fix LP bug #784297 in the tree for mwl106.
The patch imposes unconditional materialization for derived tables
used in update and multi-update statements.
Fixed a bug with a wrong order of processing derived tables/views
at the prepare stage that caused a crash for the variant of the 
query from test case for bug 52157.
2011-05-27 00:03:55 -07:00
Igor Babaev
704f97035f Merged the code of MWL#106 into 5.3
Resolved all conflicts, bad merges and fixed a few minor bugs in the code.
Commented out the queries from multi_update, view, subselect_sj, func_str,
derived_view, view_grant that failed either with crashes in ps-protocol or
with wrong results.
The failures are clear indications of some bugs in the code and these bugs
are to be fixed.
2011-05-16 22:39:43 -07:00
Jorgen Loland
d1d166875a BUG#11762751: UPDATE STATEMENT THROWS AN ERROR, BUT STILL
UPDATES THE TABLE ENTRIES (formerly 55385)
BUG#11764529: MULTI UPDATE+INNODB REPORTS ER_KEY_NOT_FOUND 
              IF A TABLE IS UPDATED TWICE (formerly 57373)
            
If multiple-table update updates a row through two aliases and
the first update physically moves the row, the second update will
fail to locate the row. This results in different errors
depending on storage engine:
  * MyISAM: Got error 134 from storage engine
  * InnoDB: Can't find record in 'tbl'
None of these errors accurately describe the problem. 
      
Furthermore, since MyISAM is non-transactional, the update
executed first will be performed while the second will not.
In addition, for two equal multiple-table update statements,
one could succeed and the other fail based on whether or not
the record actually moved or not. This was inconsistent.
      
Two update operations may physically move a row:
  1) Update of a column in a clustered primary key
  2) Update of a column used to calculate which partition the 
     row belongs to
           
BUG#11764529 is about case 1) above, BUG#11762751 was about case 2).
      
The fix for these bugs is to return with an error if multiple-table 
update is about to:
  a) Update a table through multiple aliases, and
  b) Perform an update that may physically more the row 
     in at least one of these aliases
    
This avoids 
  * partial updates as described for MyISAM above,
  * provides the same error message that describes the actual problem
    for all SEs
  * inconsistent behavior where a statement fails or succeeds based on
    e.g. the partitioning algorithm of the table.

mysql-test/r/multi_update.result:
  Add test for bug#57373
mysql-test/r/multi_update_innodb.result:
  Add test for bug#57373
mysql-test/r/partition.result:
  Add test for bug#55385
mysql-test/t/multi_update.test:
  Add test for bug#57373
mysql-test/t/multi_update_innodb.test:
  Add test for bug#57373
mysql-test/t/partition.test:
  Add test for bug#55385
sql/handler.cc:
  Translate handler error HA_ERR_RECORD_DELETED to server error
sql/share/errmsg-utf8.txt:
  New error message for multi-table update where the same table is updated multiple times.
sql/sql_update.cc:
  Add function unsafe_key_update()
2011-02-21 16:49:03 +01:00
Sergey Glukhov
fcb83cbf15 Fixed following problems:
--Bug#52157 various crashes and assertions with multi-table update, stored function
--Bug#54475 improper error handling causes cascading crashing failures in innodb/ndb
--Bug#57703 create view cause Assertion failed: 0, file .\item_subselect.cc, line 846
--Bug#57352 valgrind warnings when creating view
--Recently discovered problem when a nested materialized derived table is used
  before being populated and it leads to incorrect result

We have several modes when we should disable subquery evaluation.
The reasons for disabling are different. It could be
uselessness of the evaluation as in case of 'CREATE VIEW'
or 'PREPARE stmt', or we should disable subquery evaluation
if tables are not locked yet as it happens in bug#54475, or
too early evaluation of subqueries can lead to wrong result
as it happened in Bug#19077.
Main problem is that if subquery items are treated as const
they are evaluated in ::fix_fields(), ::fix_length_and_dec()
of the parental items as a lot of these methods have
Item::val_...() calls inside.
We have to make subqueries non-const to prevent unnecessary
subquery evaluation. At the moment we have different methods
for this. Here is a list of these modes:

1. PREPARE stmt;
We use UNCACHEABLE_PREPARE flag.
It is set during parsing in sql_parse.cc, mysql_new_select() for
each SELECT_LEX object and cleared at the end of PREPARE in
sql_prepare.cc, init_stmt_after_parse(). If this flag is set
subquery becomes non-const and evaluation does not happen.

2. CREATE|ALTER VIEW, SHOW CREATE VIEW, I_S tables which
   process FRM files
We use LEX::view_prepare_mode field. We set it before
view preparation and check this flag in
::fix_fields(), ::fix_length_and_dec().
Some bugs are fixed using this approach,
some are not(Bug#57352, Bug#57703). The problem here is
that we have a lot of ::fix_fields(), ::fix_length_and_dec()
where we use Item::val_...() calls for const items.

3. Derived tables with subquery = wrong result(Bug19077)
The reason of this bug is too early subquery evaluation.
It was fixed by adding Item::with_subselect field
The check of this field in appropriate places prevents
const item evaluation if the item have subquery.
The fix for Bug19077 fixes only the problem with
convert_constant_item() function and does not cover
other places(::fix_fields(), ::fix_length_and_dec() again)
where subqueries could be evaluated.

Example:
CREATE TABLE t1 (i INT, j BIGINT);
INSERT INTO t1 VALUES (1, 2), (2, 2), (3, 2);
SELECT * FROM (SELECT MIN(i) FROM t1
WHERE j = SUBSTRING('12', (SELECT * FROM (SELECT MIN(j) FROM t1) t2))) t3;
DROP TABLE t1;

4. Derived tables with subquery where subquery
   is evaluated before table locking(Bug#54475, Bug#52157)

Suggested solution is following:

-Introduce new field LEX::context_analysis_only with the following
 possible flags:
 #define CONTEXT_ANALYSIS_ONLY_PREPARE 1
 #define CONTEXT_ANALYSIS_ONLY_VIEW    2
 #define CONTEXT_ANALYSIS_ONLY_DERIVED 4
-Set/clean these flags when we perform
 context analysis operation
-Item_subselect::const_item() returns
 result depending on LEX::context_analysis_only.
 If context_analysis_only is set then we return
 FALSE that means that subquery is non-const.
 As all subquery types are wrapped by Item_subselect
 it allow as to make subquery non-const when
 it's necessary.


mysql-test/r/derived.result:
  test case
mysql-test/r/multi_update.result:
  test case
mysql-test/r/view.result:
  test case
mysql-test/suite/innodb/r/innodb_multi_update.result:
  test case
mysql-test/suite/innodb/t/innodb_multi_update.test:
  test case
mysql-test/suite/innodb_plugin/r/innodb_multi_update.result:
  test case
mysql-test/suite/innodb_plugin/t/innodb_multi_update.test:
  test case
mysql-test/t/derived.test:
  test case
mysql-test/t/multi_update.test:
  test case
mysql-test/t/view.test:
  test case
sql/item.cc:
  --removed unnecessary code
sql/item_cmpfunc.cc:
  --removed unnecessary checks
  --THD::is_context_analysis_only() is replaced with LEX::is_ps_or_view_context_analysis()
sql/item_func.cc:
  --refactored context analysis checks
sql/item_row.cc:
  --removed unnecessary checks
sql/item_subselect.cc:
  --removed unnecessary code
  --added DBUG_ASSERT into Item_subselect::exec()
    which asserts that subquery execution can not happen
    if LEX::context_analysis_only is set, i.e. at context
    analysis stage.
  --Item_subselect::const_item()
    Return FALSE if LEX::context_analysis_only is set.
    It prevents subquery evaluation in ::fix_fields &
    ::fix_length_and_dec at context analysis stage.
sql/item_subselect.h:
  --removed unnecessary code
sql/mysql_priv.h:
  --Added new set of flags.
sql/sql_class.h:
  --removed unnecessary code
sql/sql_derived.cc:
  --added LEX::context_analysis_only analysis intialization/cleanup
sql/sql_lex.cc:
  --init LEX::context_analysis_only field
sql/sql_lex.h:
  --New LEX::context_analysis_only field
sql/sql_parse.cc:
  --removed unnecessary code
sql/sql_prepare.cc:
  --removed unnecessary code
  --added LEX::context_analysis_only analysis intialization/cleanup
sql/sql_select.cc:
  --refactored context analysis checks
sql/sql_show.cc:
  --added LEX::context_analysis_only analysis intialization/cleanup
sql/sql_view.cc:
  --added LEX::context_analysis_only analysis intialization/cleanup
2010-12-14 12:33:03 +03:00