You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1183 lines
32 KiB

  1. /* Copyright (c) 2017, 2020, MariaDB
  2. This program is free software; you can redistribute it and/or modify
  3. it under the terms of the GNU General Public License as published by
  4. the Free Software Foundation; version 2 of the License.
  5. This program is distributed in the hope that it will be useful,
  6. but WITHOUT ANY WARRANTY; without even the implied warranty of
  7. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  8. GNU General Public License for more details.
  9. You should have received a copy of the GNU General Public License
  10. along with this program; if not, write to the Free Software
  11. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
  12. #include "mariadb.h"
  13. #include "sql_list.h"
  14. #include "sql_tvc.h"
  15. #include "sql_class.h"
  16. #include "opt_range.h"
  17. #include "sql_select.h"
  18. #include "sql_explain.h"
  19. #include "sql_parse.h"
  20. #include "sql_cte.h"
  21. #include "my_json_writer.h"
  22. /**
  23. @brief
  24. Walk through all VALUES items.
  25. @param
  26. @param processor - the processor to call for each Item
  27. @param walk_qubquery - if should dive into subquery items
  28. @param argument - the argument to pass recursively
  29. @retval
  30. true on error
  31. false on success
  32. */
  33. bool table_value_constr::walk_values(Item_processor processor,
  34. bool walk_subquery,
  35. void *argument)
  36. {
  37. List_iterator_fast<List_item> list_item_it(lists_of_values);
  38. while (List_item *list= list_item_it++)
  39. {
  40. List_iterator_fast<Item> item_it(*list);
  41. while (Item *item= item_it++)
  42. {
  43. if (item->walk(&Item::unknown_splocal_processor, false, argument))
  44. return true;
  45. }
  46. }
  47. return false;
  48. }
  49. /**
  50. @brief
  51. Fix fields for TVC values
  52. @param
  53. @param thd The context of the statement
  54. @param li The iterator on the list of lists
  55. @details
  56. Call fix_fields procedure for TVC values.
  57. @retval
  58. true if an error was reported
  59. false otherwise
  60. */
  61. bool fix_fields_for_tvc(THD *thd, List_iterator_fast<List_item> &li)
  62. {
  63. DBUG_ENTER("fix_fields_for_tvc");
  64. List_item *lst;
  65. li.rewind();
  66. while ((lst= li++))
  67. {
  68. List_iterator<Item> it(*lst);
  69. Item *item;
  70. while ((item= it++))
  71. {
  72. /*
  73. Some items have already been fixed.
  74. For example Item_splocal items get fixed in
  75. Item_splocal::append_for_log(), which is called from subst_spvars()
  76. while replacing their values to NAME_CONST()s.
  77. So fix only those that have not been.
  78. */
  79. if (item->fix_fields_if_needed_for_scalar(thd, it.ref()) ||
  80. item->check_is_evaluable_expression_or_error())
  81. DBUG_RETURN(true);
  82. }
  83. }
  84. DBUG_RETURN(false);
  85. }
  86. /**
  87. @brief
  88. Defines types of matrix columns elements where matrix rows are defined by
  89. some lists of values.
  90. @param
  91. @param thd The context of the statement
  92. @param li The iterator on the list of lists
  93. @param holders The structure where types of matrix columns are stored
  94. @param first_list_el_count Count of the list values. It should be the same
  95. for each list of lists elements. It contains
  96. number of elements of the first list from list of
  97. lists.
  98. @details
  99. For each list list_a from list of lists the procedure gets its elements
  100. types and aggregates them with the previous ones stored in holders. If
  101. list_a is the first one in the list of lists its elements types are put in
  102. holders. The errors can be reported when count of list_a elements is
  103. different from the first_list_el_count. Also error can be reported whe
  104. n aggregation can't be made.
  105. @retval
  106. true if an error was reported
  107. false otherwise
  108. */
  109. bool join_type_handlers_for_tvc(THD *thd, List_iterator_fast<List_item> &li,
  110. Type_holder *holders, uint first_list_el_count)
  111. {
  112. DBUG_ENTER("join_type_handlers_for_tvc");
  113. List_item *lst;
  114. li.rewind();
  115. bool first= true;
  116. while ((lst= li++))
  117. {
  118. List_iterator_fast<Item> it(*lst);
  119. Item *item;
  120. if (first_list_el_count != lst->elements)
  121. {
  122. my_message(ER_WRONG_NUMBER_OF_VALUES_IN_TVC,
  123. ER_THD(thd, ER_WRONG_NUMBER_OF_VALUES_IN_TVC),
  124. MYF(0));
  125. DBUG_RETURN(true);
  126. }
  127. for (uint pos= 0; (item=it++); pos++)
  128. {
  129. const Type_handler *item_type_handler= item->real_type_handler();
  130. if (first)
  131. holders[pos].set_handler(item_type_handler);
  132. else if (holders[pos].aggregate_for_result(item_type_handler))
  133. {
  134. my_error(ER_ILLEGAL_PARAMETER_DATA_TYPES2_FOR_OPERATION, MYF(0),
  135. holders[pos].type_handler()->name().ptr(),
  136. item_type_handler->name().ptr(),
  137. "TABLE VALUE CONSTRUCTOR");
  138. DBUG_RETURN(true);
  139. }
  140. }
  141. first= false;
  142. }
  143. DBUG_RETURN(false);
  144. }
  145. /**
  146. @brief
  147. Define attributes of matrix columns elements where matrix rows are defined
  148. by some lists of values.
  149. @param
  150. @param thd The context of the statement
  151. @param li The iterator on the list of lists
  152. @param holders The structure where names of matrix columns are stored
  153. @param count_of_lists Count of list of lists elements
  154. @param first_list_el_count Count of the list values. It should be the same
  155. for each list of lists elements. It contains
  156. number of elements of the first list from list
  157. of lists.
  158. @details
  159. For each list list_a from list of lists the procedure gets its elements
  160. attributes and aggregates them with the previous ones stored in holders.
  161. The errors can be reported when aggregation can't be made.
  162. @retval
  163. true if an error was reported
  164. false otherwise
  165. */
  166. bool get_type_attributes_for_tvc(THD *thd,
  167. List_iterator_fast<List_item> &li,
  168. Type_holder *holders, uint count_of_lists,
  169. uint first_list_el_count)
  170. {
  171. DBUG_ENTER("get_type_attributes_for_tvc");
  172. List_item *lst;
  173. li.rewind();
  174. for (uint pos= 0; pos < first_list_el_count; pos++)
  175. {
  176. if (holders[pos].alloc_arguments(thd, count_of_lists))
  177. DBUG_RETURN(true);
  178. }
  179. while ((lst= li++))
  180. {
  181. List_iterator_fast<Item> it(*lst);
  182. Item *item;
  183. for (uint holder_pos= 0 ; (item= it++); holder_pos++)
  184. {
  185. DBUG_ASSERT(item->fixed());
  186. holders[holder_pos].add_argument(item);
  187. }
  188. }
  189. for (uint pos= 0; pos < first_list_el_count; pos++)
  190. {
  191. if (holders[pos].aggregate_attributes(thd))
  192. DBUG_RETURN(true);
  193. }
  194. DBUG_RETURN(false);
  195. }
  196. /**
  197. @brief
  198. Prepare of TVC
  199. @param
  200. @param thd The context of the statement
  201. @param sl The select where this TVC is defined
  202. @param tmp_result Structure that contains the information
  203. about where to send the result of the query
  204. @param unit_arg The union where sl is defined
  205. @details
  206. Gets types and attributes of values of this TVC that will be used
  207. for temporary table creation for this TVC. It creates Item_type_holders
  208. for each element of the first list from list of lists (VALUES from tvc),
  209. using its elements name, defined type and attribute.
  210. @retval
  211. true if an error was reported
  212. false otherwise
  213. */
  214. bool table_value_constr::prepare(THD *thd, SELECT_LEX *sl,
  215. select_result *tmp_result,
  216. st_select_lex_unit *unit_arg)
  217. {
  218. DBUG_ENTER("table_value_constr::prepare");
  219. select_lex->in_tvc= true;
  220. List_iterator_fast<List_item> li(lists_of_values);
  221. List_item *first_elem= li++;
  222. uint cnt= first_elem->elements;
  223. Type_holder *holders;
  224. if (cnt == 0)
  225. {
  226. my_error(ER_EMPTY_ROW_IN_TVC, MYF(0));
  227. DBUG_RETURN(true);
  228. }
  229. if (fix_fields_for_tvc(thd, li))
  230. DBUG_RETURN(true);
  231. if (!(holders= new (thd->stmt_arena->mem_root) Type_holder[cnt]) ||
  232. join_type_handlers_for_tvc(thd, li, holders, cnt) ||
  233. get_type_attributes_for_tvc(thd, li, holders,
  234. lists_of_values.elements, cnt))
  235. DBUG_RETURN(true);
  236. List_iterator_fast<Item> it(*first_elem);
  237. Item *item;
  238. Query_arena *arena, backup;
  239. arena=thd->activate_stmt_arena_if_needed(&backup);
  240. sl->item_list.empty();
  241. for (uint pos= 0; (item= it++); pos++)
  242. {
  243. /* Error's in 'new' will be detected after loop */
  244. Item_type_holder *new_holder= new (thd->mem_root)
  245. Item_type_holder(thd, item, holders[pos].type_handler(),
  246. &holders[pos]/*Type_all_attributes*/,
  247. holders[pos].get_maybe_null());
  248. sl->item_list.push_back(new_holder);
  249. }
  250. if (arena)
  251. thd->restore_active_arena(arena, &backup);
  252. if (unlikely(thd->is_fatal_error))
  253. DBUG_RETURN(true); // out of memory
  254. result= tmp_result;
  255. if (result && result->prepare(sl->item_list, unit_arg))
  256. DBUG_RETURN(true);
  257. /*
  258. setup_order() for a TVC is not called when the following is true
  259. (thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)
  260. */
  261. thd->where="order clause";
  262. ORDER *order= sl->order_list.first;
  263. for (; order; order=order->next)
  264. {
  265. Item *order_item= *order->item;
  266. if (order_item->is_order_clause_position())
  267. {
  268. uint count= 0;
  269. if (order->counter_used)
  270. count= order->counter; // counter was once resolved
  271. else
  272. count= (uint) order_item->val_int();
  273. if (!count || count > first_elem->elements)
  274. {
  275. my_error(ER_BAD_FIELD_ERROR, MYF(0),
  276. order_item->full_name(), thd->where);
  277. DBUG_RETURN(true);
  278. }
  279. order->in_field_list= 1;
  280. order->counter= count;
  281. order->counter_used= 1;
  282. }
  283. }
  284. select_lex->in_tvc= false;
  285. DBUG_RETURN(false);
  286. }
  287. /**
  288. Save Query Plan Footprint
  289. */
  290. int table_value_constr::save_explain_data_intern(THD *thd,
  291. Explain_query *output)
  292. {
  293. const char *message= "No tables used";
  294. DBUG_ENTER("table_value_constr::save_explain_data_intern");
  295. DBUG_PRINT("info", ("Select %p, type %s, message %s",
  296. select_lex, select_lex->type,
  297. message));
  298. DBUG_ASSERT(have_query_plan == QEP_AVAILABLE);
  299. /* There should be no attempts to save query plans for merged selects */
  300. DBUG_ASSERT(!select_lex->master_unit()->derived ||
  301. select_lex->master_unit()->derived->is_materialized_derived() ||
  302. select_lex->master_unit()->derived->is_with_table());
  303. explain= new (output->mem_root) Explain_select(output->mem_root,
  304. thd->lex->analyze_stmt);
  305. if (!explain)
  306. DBUG_RETURN(1);
  307. select_lex->set_explain_type(true);
  308. explain->select_id= select_lex->select_number;
  309. explain->select_type= select_lex->type;
  310. explain->linkage= select_lex->get_linkage();
  311. explain->using_temporary= false;
  312. explain->using_filesort= false;
  313. /* Setting explain->message means that all other members are invalid */
  314. explain->message= message;
  315. if (select_lex->master_unit()->derived)
  316. explain->connection_type= Explain_node::EXPLAIN_NODE_DERIVED;
  317. for (SELECT_LEX_UNIT *unit= select_lex->first_inner_unit();
  318. unit;
  319. unit= unit->next_unit())
  320. {
  321. explain->add_child(unit->first_select()->select_number);
  322. }
  323. output->add_node(explain);
  324. if (select_lex->is_top_level_node())
  325. output->query_plan_ready();
  326. DBUG_RETURN(0);
  327. }
  328. /**
  329. Optimization of TVC
  330. */
  331. bool table_value_constr::optimize(THD *thd)
  332. {
  333. create_explain_query_if_not_exists(thd->lex, thd->mem_root);
  334. have_query_plan= QEP_AVAILABLE;
  335. if (select_lex->select_number != FAKE_SELECT_LEX_ID &&
  336. have_query_plan != QEP_NOT_PRESENT_YET &&
  337. thd->lex->explain && // for "SET" command in SPs.
  338. (!thd->lex->explain->get_select(select_lex->select_number)))
  339. {
  340. if (save_explain_data_intern(thd, thd->lex->explain))
  341. return true;
  342. }
  343. if (select_lex->optimize_unflattened_subqueries(true))
  344. return true;
  345. return false;
  346. }
  347. /**
  348. Execute of TVC
  349. */
  350. bool table_value_constr::exec(SELECT_LEX *sl)
  351. {
  352. DBUG_ENTER("table_value_constr::exec");
  353. List_iterator_fast<List_item> li(lists_of_values);
  354. List_item *elem;
  355. ha_rows send_records= 0;
  356. if (select_options & SELECT_DESCRIBE)
  357. DBUG_RETURN(false);
  358. if (result->send_result_set_metadata(sl->item_list,
  359. Protocol::SEND_NUM_ROWS |
  360. Protocol::SEND_EOF))
  361. {
  362. DBUG_RETURN(true);
  363. }
  364. while ((elem= li++))
  365. {
  366. if (send_records >= sl->master_unit()->lim.get_select_limit())
  367. break;
  368. int rc=
  369. result->send_data_with_check(*elem, sl->master_unit(), send_records);
  370. if (!rc)
  371. send_records++;
  372. else if (rc > 0)
  373. DBUG_RETURN(true);
  374. }
  375. if (result->send_eof())
  376. DBUG_RETURN(true);
  377. DBUG_RETURN(false);
  378. }
  379. /**
  380. @brief
  381. Print list
  382. @param str The reference on the string representation of the list
  383. @param list The list that needed to be print
  384. @param query_type The mode of printing
  385. @details
  386. The method saves a string representation of list in the
  387. string str.
  388. */
  389. void print_list_item(String *str, List_item *list,
  390. enum_query_type query_type)
  391. {
  392. bool is_first_elem= true;
  393. List_iterator_fast<Item> it(*list);
  394. Item *item;
  395. str->append('(');
  396. while ((item= it++))
  397. {
  398. if (is_first_elem)
  399. is_first_elem= false;
  400. else
  401. str->append(',');
  402. item->print(str, query_type);
  403. }
  404. str->append(')');
  405. }
  406. /**
  407. @brief
  408. Print this TVC
  409. @param thd The context of the statement
  410. @param str The reference on the string representation of this TVC
  411. @param query_type The mode of printing
  412. @details
  413. The method saves a string representation of this TVC in the
  414. string str.
  415. */
  416. void table_value_constr::print(THD *thd, String *str,
  417. enum_query_type query_type)
  418. {
  419. DBUG_ASSERT(thd);
  420. str->append(STRING_WITH_LEN("values "));
  421. bool is_first_elem= true;
  422. List_iterator_fast<List_item> li(lists_of_values);
  423. List_item *list;
  424. while ((list= li++))
  425. {
  426. if (is_first_elem)
  427. is_first_elem= false;
  428. else
  429. str->append(',');
  430. print_list_item(str, list, query_type);
  431. }
  432. if (select_lex->order_list.elements)
  433. {
  434. str->append(STRING_WITH_LEN(" order by "));
  435. select_lex->print_order(str, select_lex->order_list.first, query_type);
  436. }
  437. select_lex->print_limit(thd, str, query_type);
  438. }
  439. /**
  440. @brief
  441. Create list of lists for TVC from the list of this IN predicate
  442. @param thd The context of the statement
  443. @param values TVC list of values
  444. @details
  445. The method uses the list of values of this IN predicate to build
  446. an equivalent list of values that can be used in TVC.
  447. E.g.:
  448. <value_list> = 5,2,7
  449. <transformed_value_list> = (5),(2),(7)
  450. <value_list> = (5,2),(7,1)
  451. <transformed_value_list> = (5,2),(7,1)
  452. @retval
  453. false if the method succeeds
  454. true otherwise
  455. */
  456. bool Item_func_in::create_value_list_for_tvc(THD *thd,
  457. List< List<Item> > *values)
  458. {
  459. bool is_list_of_rows= args[1]->type() == Item::ROW_ITEM;
  460. for (uint i=1; i < arg_count; i++)
  461. {
  462. char col_name[8];
  463. List<Item> *tvc_value;
  464. if (!(tvc_value= new (thd->mem_root) List<Item>()))
  465. return true;
  466. if (is_list_of_rows)
  467. {
  468. Item_row *row_list= (Item_row *)(args[i]);
  469. for (uint j=0; j < row_list->cols(); j++)
  470. {
  471. if (i == 1)
  472. {
  473. sprintf(col_name, "_col_%i", j+1);
  474. row_list->element_index(j)->set_name(thd, col_name, strlen(col_name),
  475. thd->charset());
  476. }
  477. if (tvc_value->push_back(row_list->element_index(j),
  478. thd->mem_root))
  479. return true;
  480. }
  481. }
  482. else
  483. {
  484. if (i == 1)
  485. {
  486. sprintf(col_name, "_col_%i", 1);
  487. args[i]->set_name(thd, col_name, strlen(col_name), thd->charset());
  488. }
  489. if (tvc_value->push_back(args[i]->real_item()))
  490. return true;
  491. }
  492. if (values->push_back(tvc_value, thd->mem_root))
  493. return true;
  494. }
  495. return false;
  496. }
  497. /**
  498. @brief
  499. Create name for the derived table defined by TVC
  500. @param thd The context of the statement
  501. @param parent_select The SELECT where derived table is used
  502. @param alias The returned created name
  503. @details
  504. Create name for the derived table using current TVC number
  505. for this parent_select stored in parent_select
  506. @retval
  507. true if creation fails
  508. false otherwise
  509. */
  510. static bool create_tvc_name(THD *thd, st_select_lex *parent_select,
  511. LEX_CSTRING *alias)
  512. {
  513. char buff[6];
  514. alias->length= my_snprintf(buff, sizeof(buff),
  515. "tvc_%u",
  516. parent_select ? parent_select->curr_tvc_name : 0);
  517. alias->str= thd->strmake(buff, alias->length);
  518. if (!alias->str)
  519. return true;
  520. return false;
  521. }
  522. /**
  523. @brief
  524. Check whether TVC used in unit is to be wrapped into select
  525. @details
  526. TVC used in unit that contains more than one members is to be wrapped
  527. into select if it is tailed with ORDER BY ... LIMIT n [OFFSET m]
  528. @retval
  529. true if TVC is to be wrapped
  530. false otherwise
  531. */
  532. bool table_value_constr::to_be_wrapped_as_with_tail()
  533. {
  534. return select_lex->master_unit()->first_select()->next_select() &&
  535. select_lex->order_list.elements &&
  536. select_lex->limit_params.explicit_limit;
  537. }
  538. /**
  539. @brief
  540. Wrap table value constructor into a select
  541. @param thd The context handler
  542. @param tvc_sl The TVC to wrap
  543. @parent_select The parent select if tvc_sl used in a subquery
  544. @details
  545. The function wraps the TVC tvc_sl into a select:
  546. the function transforms the TVC of the form VALUES (v1), ... (vn) into
  547. the select of the form
  548. SELECT * FROM (VALUES (v1), ... (vn)) tvc_x
  549. @retval pointer to the result of of the transformation if successful
  550. NULL - otherwise
  551. */
  552. static
  553. st_select_lex *wrap_tvc(THD *thd, st_select_lex *tvc_sl,
  554. st_select_lex *parent_select)
  555. {
  556. LEX *lex= thd->lex;
  557. select_result *save_result= lex->result;
  558. uint8 save_derived_tables= lex->derived_tables;
  559. thd->lex->result= NULL;
  560. Query_arena backup;
  561. Query_arena *arena= thd->activate_stmt_arena_if_needed(&backup);
  562. Item *item;
  563. SELECT_LEX *wrapper_sl;
  564. SELECT_LEX_UNIT *derived_unit;
  565. /*
  566. Create SELECT_LEX wrapper_sl of the select used in the result
  567. of the transformation
  568. */
  569. if (!(wrapper_sl= new (thd->mem_root) SELECT_LEX()))
  570. goto err;
  571. wrapper_sl->select_number= ++thd->lex->stmt_lex->current_select_number;
  572. wrapper_sl->parent_lex= lex; /* Used in init_query. */
  573. wrapper_sl->init_query();
  574. wrapper_sl->init_select();
  575. wrapper_sl->nest_level= tvc_sl->nest_level;
  576. wrapper_sl->parsing_place= tvc_sl->parsing_place;
  577. wrapper_sl->set_linkage(tvc_sl->get_linkage());
  578. wrapper_sl->exclude_from_table_unique_test=
  579. tvc_sl->exclude_from_table_unique_test;
  580. lex->current_select= wrapper_sl;
  581. item= new (thd->mem_root) Item_field(thd, &wrapper_sl->context,
  582. star_clex_str);
  583. if (item == NULL || add_item_to_list(thd, item))
  584. goto err;
  585. (wrapper_sl->with_wild)++;
  586. /* Include the newly created select into the global list of selects */
  587. wrapper_sl->include_global((st_select_lex_node**)&lex->all_selects_list);
  588. /* Substitute select node used of TVC for the newly created select */
  589. tvc_sl->substitute_in_tree(wrapper_sl);
  590. /*
  591. Create a unit for the substituted select used for TVC and attach it
  592. to the the wrapper select wrapper_sl as the only unit. The created
  593. unit is the unit for the derived table tvc_x of the transformation.
  594. */
  595. if (!(derived_unit= new (thd->mem_root) SELECT_LEX_UNIT()))
  596. goto err;
  597. derived_unit->init_query();
  598. derived_unit->thd= thd;
  599. derived_unit->include_down(wrapper_sl);
  600. /*
  601. Attach the select used of TVC as the only slave to the unit for
  602. the derived table tvc_x of the transformation
  603. */
  604. derived_unit->add_slave(tvc_sl);
  605. tvc_sl->set_linkage(DERIVED_TABLE_TYPE);
  606. /*
  607. Generate the name of the derived table created for TVC and
  608. add it to the FROM list of the wrapping select
  609. */
  610. Table_ident *ti;
  611. LEX_CSTRING alias;
  612. TABLE_LIST *derived_tab;
  613. if (!(ti= new (thd->mem_root) Table_ident(derived_unit)) ||
  614. create_tvc_name(thd, parent_select, &alias))
  615. goto err;
  616. if (!(derived_tab=
  617. wrapper_sl->add_table_to_list(thd,
  618. ti, &alias, 0,
  619. TL_READ, MDL_SHARED_READ)))
  620. goto err;
  621. wrapper_sl->add_joined_table(derived_tab);
  622. wrapper_sl->add_where_field(derived_unit->first_select());
  623. wrapper_sl->context.table_list= wrapper_sl->table_list.first;
  624. wrapper_sl->context.first_name_resolution_table= wrapper_sl->table_list.first;
  625. wrapper_sl->table_list.first->derived_type= DTYPE_TABLE | DTYPE_MATERIALIZE;
  626. lex->derived_tables|= DERIVED_SUBQUERY;
  627. if (arena)
  628. thd->restore_active_arena(arena, &backup);
  629. lex->result= save_result;
  630. return wrapper_sl;
  631. err:
  632. if (arena)
  633. thd->restore_active_arena(arena, &backup);
  634. lex->result= save_result;
  635. lex->derived_tables= save_derived_tables;
  636. return 0;
  637. }
  638. /**
  639. @brief
  640. Wrap TVC with ORDER BY ... LIMIT tail into a select
  641. @param thd The context handler
  642. @param tvc_sl The TVC to wrap
  643. @details
  644. The function wraps the TVC tvc_sl into a select:
  645. the function transforms the TVC with tail of the form
  646. VALUES (v1), ... (vn) ORDER BY ... LIMIT n [OFFSET m]
  647. into the select with the same tail of the form
  648. SELECT * FROM (VALUES (v1), ... (vn)) tvc_x
  649. ORDER BY ... LIMIT n [OFFSET m]
  650. @retval pointer to the result of of the transformation if successful
  651. NULL - otherwise
  652. */
  653. st_select_lex *wrap_tvc_with_tail(THD *thd, st_select_lex *tvc_sl)
  654. {
  655. st_select_lex *wrapper_sl= wrap_tvc(thd, tvc_sl, NULL);
  656. if (!wrapper_sl)
  657. return NULL;
  658. wrapper_sl->order_list= tvc_sl->order_list;
  659. wrapper_sl->limit_params= tvc_sl->limit_params;
  660. wrapper_sl->braces= tvc_sl->braces;
  661. tvc_sl->order_list.empty();
  662. tvc_sl->limit_params.clear();
  663. tvc_sl->braces= 0;
  664. if (tvc_sl->select_number == 1)
  665. {
  666. tvc_sl->select_number= wrapper_sl->select_number;
  667. wrapper_sl->select_number= 1;
  668. }
  669. if (tvc_sl->master_unit()->union_distinct == tvc_sl)
  670. {
  671. wrapper_sl->master_unit()->union_distinct= wrapper_sl;
  672. }
  673. wrapper_sl->distinct= tvc_sl->distinct;
  674. thd->lex->current_select= wrapper_sl;
  675. return wrapper_sl;
  676. }
  677. /**
  678. @brief
  679. Wrap TVC in a subselect into a select
  680. @param thd The context handler
  681. @param tvc_sl The TVC to wrap
  682. @details
  683. The function wraps the TVC tvc_sl used in a subselect into a select
  684. the function transforms the TVC of the form VALUES (v1), ... (vn)
  685. into the select the form
  686. SELECT * FROM (VALUES (v1), ... (vn)) tvc_x
  687. and replaces the subselect with the result of the transformation.
  688. @retval wrapping select if successful
  689. 0 otherwise
  690. */
  691. st_select_lex *
  692. Item_subselect::wrap_tvc_into_select(THD *thd, st_select_lex *tvc_sl)
  693. {
  694. LEX *lex= thd->lex;
  695. /* SELECT_LEX object where the transformation is performed */
  696. SELECT_LEX *parent_select= lex->current_select;
  697. SELECT_LEX *wrapper_sl= wrap_tvc(thd, tvc_sl, parent_select);
  698. if (wrapper_sl)
  699. {
  700. if (engine->engine_type() == subselect_engine::SINGLE_SELECT_ENGINE)
  701. ((subselect_single_select_engine *) engine)->change_select(wrapper_sl);
  702. }
  703. lex->current_select= parent_select;
  704. return wrapper_sl;
  705. }
  706. /*
  707. @brief
  708. Check whether the items are of comparable type or not
  709. @details
  710. This check are done because materialization is not performed
  711. if the left expr and right expr are of the same types.
  712. @see subquery_types_allow_materialization()
  713. @retval
  714. 0 comparable
  715. 1 not comparable
  716. */
  717. static bool cmp_row_types(Item* item1, Item* item2)
  718. {
  719. uint n= item1->cols();
  720. if (item2->check_cols(n))
  721. return true;
  722. for (uint i=0; i < n; i++)
  723. {
  724. Item *inner= item1->element_index(i);
  725. Item *outer= item2->element_index(i);
  726. if (!inner->type_handler()->subquery_type_allows_materialization(inner,
  727. outer,
  728. true))
  729. return true;
  730. }
  731. return false;
  732. }
  733. /**
  734. @brief
  735. Transform IN predicate into IN subquery
  736. @param thd The context of the statement
  737. @param arg Not used
  738. @details
  739. The method transforms this IN predicate into in equivalent IN subquery:
  740. <left_expr> IN (<value_list>)
  741. =>
  742. <left_expr> IN (SELECT * FROM (VALUES <transformed_value_list>) AS tvc_#)
  743. E.g.:
  744. <value_list> = 5,2,7
  745. <transformed_value_list> = (5),(2),(7)
  746. <value_list> = (5,2),(7,1)
  747. <transformed_value_list> = (5,2),(7,1)
  748. If the transformation succeeds the method returns the result IN subquery,
  749. otherwise this IN predicate is returned.
  750. @retval
  751. pointer to the result of transformation if succeeded
  752. pointer to this IN predicate otherwise
  753. */
  754. Item *Item_func_in::in_predicate_to_in_subs_transformer(THD *thd,
  755. uchar *arg)
  756. {
  757. if (!transform_into_subq)
  758. return this;
  759. Json_writer_object trace_wrapper(thd);
  760. Json_writer_object trace_conv(thd, "in_to_subquery_conversion");
  761. trace_conv.add("item", this);
  762. transform_into_subq= false;
  763. List<List_item> values;
  764. LEX *lex= thd->lex;
  765. /* SELECT_LEX object where the transformation is performed */
  766. SELECT_LEX *parent_select= lex->current_select;
  767. uint8 save_derived_tables= lex->derived_tables;
  768. /*
  769. Make sure that create_tmp_table will not fail due to too long keys.
  770. Here the strategy would mainly use materialization, so we need to make
  771. sure that the materialized table can be created.
  772. The checks here are the same as in subquery_type_allows_materialization()
  773. */
  774. uint32 length= max_length_of_left_expr();
  775. if (!length || length > tmp_table_max_key_length() ||
  776. args[0]->cols() > tmp_table_max_key_parts())
  777. {
  778. trace_conv.add("done", false);
  779. trace_conv.add("reason", "key is too long");
  780. return this;
  781. }
  782. for (uint i=1; i < arg_count; i++)
  783. {
  784. if (!args[i]->const_item())
  785. {
  786. trace_conv.add("done", false);
  787. trace_conv.add("reason", "non-constant element in the IN-list");
  788. return this;
  789. }
  790. if (cmp_row_types(args[i], args[0]))
  791. {
  792. trace_conv.add("done", false);
  793. trace_conv.add("reason", "type mismatch");
  794. return this;
  795. }
  796. }
  797. Json_writer_array trace_nested_obj(thd, "conversion");
  798. Query_arena backup;
  799. Query_arena *arena= thd->activate_stmt_arena_if_needed(&backup);
  800. /*
  801. Create SELECT_LEX of the subquery SQ used in the result of transformation
  802. */
  803. if (mysql_new_select(lex, 1, NULL))
  804. goto err;
  805. mysql_init_select(lex);
  806. /* Create item list as '*' for the subquery SQ */
  807. Item *item;
  808. SELECT_LEX *sq_select; // select for IN subquery;
  809. sq_select= lex->current_select;
  810. sq_select->parsing_place= SELECT_LIST;
  811. item= new (thd->mem_root) Item_field(thd, &sq_select->context,
  812. star_clex_str);
  813. if (item == NULL || add_item_to_list(thd, item))
  814. goto err;
  815. (sq_select->with_wild)++;
  816. /*
  817. Create derived table DT that will wrap TVC in the result of transformation
  818. */
  819. SELECT_LEX *tvc_select; // select for tvc
  820. SELECT_LEX_UNIT *derived_unit; // unit for tvc_select
  821. if (mysql_new_select(lex, 1, NULL))
  822. goto err;
  823. mysql_init_select(lex);
  824. tvc_select= lex->current_select;
  825. derived_unit= tvc_select->master_unit();
  826. tvc_select->set_linkage(DERIVED_TABLE_TYPE);
  827. /* Create TVC used in the transformation */
  828. if (create_value_list_for_tvc(thd, &values))
  829. goto err;
  830. if (!(tvc_select->tvc=
  831. new (thd->mem_root)
  832. table_value_constr(values,
  833. tvc_select,
  834. tvc_select->options)))
  835. goto err;
  836. lex->current_select= sq_select;
  837. /*
  838. Create the name of the wrapping derived table and
  839. add it to the FROM list of the subquery SQ
  840. */
  841. Table_ident *ti;
  842. LEX_CSTRING alias;
  843. TABLE_LIST *derived_tab;
  844. if (!(ti= new (thd->mem_root) Table_ident(derived_unit)) ||
  845. create_tvc_name(thd, parent_select, &alias))
  846. goto err;
  847. if (!(derived_tab=
  848. sq_select->add_table_to_list(thd,
  849. ti, &alias, 0,
  850. TL_READ, MDL_SHARED_READ)))
  851. goto err;
  852. sq_select->add_joined_table(derived_tab);
  853. sq_select->add_where_field(derived_unit->first_select());
  854. sq_select->context.table_list= sq_select->table_list.first;
  855. sq_select->context.first_name_resolution_table= sq_select->table_list.first;
  856. sq_select->table_list.first->derived_type= DTYPE_TABLE | DTYPE_MATERIALIZE;
  857. lex->derived_tables|= DERIVED_SUBQUERY;
  858. sq_select->where= 0;
  859. sq_select->set_braces(false);
  860. derived_unit->set_with_clause(0);
  861. /* Create IN subquery predicate */
  862. sq_select->parsing_place= parent_select->parsing_place;
  863. Item_in_subselect *in_subs;
  864. Item *sq;
  865. if (!(in_subs=
  866. new (thd->mem_root) Item_in_subselect(thd, args[0], sq_select)))
  867. goto err;
  868. in_subs->converted_from_in_predicate= TRUE;
  869. sq= in_subs;
  870. if (negated)
  871. sq= negate_expression(thd, in_subs);
  872. else
  873. in_subs->emb_on_expr_nest= emb_on_expr_nest;
  874. if (arena)
  875. thd->restore_active_arena(arena, &backup);
  876. thd->lex->current_select= parent_select;
  877. if (sq->fix_fields(thd, (Item **)&sq))
  878. goto err;
  879. parent_select->curr_tvc_name++;
  880. return sq;
  881. err:
  882. if (arena)
  883. thd->restore_active_arena(arena, &backup);
  884. lex->derived_tables= save_derived_tables;
  885. thd->lex->current_select= parent_select;
  886. return NULL;
  887. }
  888. uint32 Item_func_in::max_length_of_left_expr()
  889. {
  890. uint n= args[0]->cols();
  891. uint32 length= 0;
  892. for (uint i=0; i < n; i++)
  893. length+= args[0]->element_index(i)->max_length;
  894. return length;
  895. }
  896. /**
  897. @brief
  898. Check if this IN-predicate can be transformed in IN-subquery
  899. with TVC
  900. @param thd The context of the statement
  901. @details
  902. Compare the number of elements in the list of
  903. values in this IN-predicate with the
  904. in_subquery_conversion_threshold special variable
  905. @retval
  906. true if transformation can be made
  907. false otherwise
  908. */
  909. bool Item_func_in::to_be_transformed_into_in_subq(THD *thd)
  910. {
  911. uint values_count= arg_count-1;
  912. if (args[1]->type() == Item::ROW_ITEM)
  913. values_count*= ((Item_row *)(args[1]))->cols();
  914. if (thd->variables.in_subquery_conversion_threshold == 0 ||
  915. thd->variables.in_subquery_conversion_threshold > values_count)
  916. return false;
  917. return true;
  918. }
  919. /**
  920. @brief
  921. Transform IN predicates into IN subqueries in WHERE and ON expressions
  922. @param thd The context of the statement
  923. @details
  924. For each IN predicate from AND parts of the WHERE condition and/or
  925. ON expressions of the SELECT for this join the method performs
  926. the intransformation into an equivalent IN sunquery if it's needed.
  927. @retval
  928. false always
  929. */
  930. bool JOIN::transform_in_predicates_into_in_subq(THD *thd)
  931. {
  932. DBUG_ENTER("JOIN::transform_in_predicates_into_in_subq");
  933. if (!select_lex->in_funcs.elements)
  934. DBUG_RETURN(false);
  935. SELECT_LEX *save_current_select= thd->lex->current_select;
  936. enum_parsing_place save_parsing_place= select_lex->parsing_place;
  937. thd->lex->current_select= select_lex;
  938. if (conds)
  939. {
  940. select_lex->parsing_place= IN_WHERE;
  941. conds=
  942. conds->transform(thd,
  943. &Item::in_predicate_to_in_subs_transformer,
  944. (uchar*) 0);
  945. if (!conds)
  946. DBUG_RETURN(true);
  947. select_lex->prep_where= conds ? conds->copy_andor_structure(thd) : 0;
  948. select_lex->where= conds;
  949. }
  950. if (join_list)
  951. {
  952. TABLE_LIST *table;
  953. List_iterator<TABLE_LIST> li(*join_list);
  954. select_lex->parsing_place= IN_ON;
  955. while ((table= li++))
  956. {
  957. if (table->on_expr)
  958. {
  959. table->on_expr=
  960. table->on_expr->transform(thd,
  961. &Item::in_predicate_to_in_subs_transformer,
  962. (uchar*) 0);
  963. if (!table->on_expr)
  964. DBUG_RETURN(true);
  965. table->prep_on_expr= table->on_expr ?
  966. table->on_expr->copy_andor_structure(thd) : 0;
  967. }
  968. }
  969. }
  970. select_lex->in_funcs.empty();
  971. select_lex->parsing_place= save_parsing_place;
  972. thd->lex->current_select= save_current_select;
  973. DBUG_RETURN(false);
  974. }