-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathsql_insert.cc
5515 lines (4881 loc) · 184 KB
/
sql_insert.cc
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2000, 2016, Oracle and/or its affiliates.
Copyright (c) 2010, 2022, MariaDB Corporation
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA
*/
/* Insert of records */
/*
INSERT DELAYED
Insert delayed is distinguished from a normal insert by lock_type ==
TL_WRITE_DELAYED instead of TL_WRITE. It first tries to open a
"delayed" table (delayed_get_table()), but falls back to
open_and_lock_tables() on error and proceeds as normal insert then.
Opening a "delayed" table means to find a delayed insert thread that
has the table open already. If this fails, a new thread is created and
waited for to open and lock the table.
If accessing the thread succeeded, in
Delayed_insert::get_local_table() the table of the thread is copied
for local use. A copy is required because the normal insert logic
works on a target table, but the other threads table object must not
be used. The insert logic uses the record buffer to create a record.
And the delayed insert thread uses the record buffer to pass the
record to the table handler. So there must be different objects. Also
the copied table is not included in the lock, so that the statement
can proceed even if the real table cannot be accessed at this moment.
Copying a table object is not a trivial operation. Besides the TABLE
object there are the field pointer array, the field objects and the
record buffer. After copying the field objects, their pointers into
the record must be "moved" to point to the new record buffer.
After this setup the normal insert logic is used. Only that for
delayed inserts write_delayed() is called instead of write_record().
It inserts the rows into a queue and signals the delayed insert thread
instead of writing directly to the table.
The delayed insert thread awakes from the signal. It locks the table,
inserts the rows from the queue, unlocks the table, and waits for the
next signal. It does normally live until a FLUSH TABLES or SHUTDOWN.
*/
#include "mariadb.h" /* NO_EMBEDDED_ACCESS_CHECKS */
#include "sql_priv.h"
#include "sql_insert.h"
#include "sql_update.h" // compare_record
#include "sql_base.h" // close_thread_tables
#include "sql_cache.h" // query_cache_*
#include "key.h" // key_copy
#include "lock.h" // mysql_unlock_tables
#include "sp_head.h"
#include "sql_view.h" // check_key_in_view, insert_view_fields
#include "sql_table.h" // mysql_create_table_no_lock
#include "sql_trigger.h"
#include "sql_select.h"
#include "sql_show.h"
#include "slave.h"
#include "sql_parse.h" // end_active_trans
#include "rpl_mi.h"
#include "transaction.h"
#include "sql_audit.h"
#include "sql_derived.h" // mysql_handle_derived
#include "sql_prepare.h"
#include "debug_sync.h" // DEBUG_SYNC
#include "debug.h" // debug_crash_here
#include <my_bit.h>
#include "rpl_rli.h"
#ifdef WITH_WSREP
#include "wsrep_mysqld.h" /* wsrep_append_table_keys() */
#include "wsrep_trans_observer.h" /* wsrep_start_transction() */
#endif /* WITH_WSREP */
#ifndef EMBEDDED_LIBRARY
static bool delayed_get_table(THD *thd, MDL_request *grl_protection_request,
TABLE_LIST *table_list);
static int write_delayed(THD *thd, TABLE *table, enum_duplicates duplic,
LEX_STRING query, bool ignore, bool log_on);
static void end_delayed_insert(THD *thd);
pthread_handler_t handle_delayed_insert(void *arg);
static void unlink_blobs(TABLE *table);
#endif
static bool check_view_insertability(THD *thd, TABLE_LIST *view,
List<Item> &fields);
static int binlog_show_create_table_(THD *thd, TABLE *table,
Table_specification_st *create_info);
/*
Check that insert/update fields are from the same single table of a view.
@param fields The insert/update fields to be checked.
@param values The insert/update values to be checked, NULL if
checking is not wanted.
@param view The view for insert.
@param map [in/out] The insert table map.
This function is called in 2 cases:
1. to check insert fields. In this case *map will be set to 0.
Insert fields are checked to be all from the same single underlying
table of the given view. Otherwise the error is thrown. Found table
map is returned in the map parameter.
2. to check update fields of the ON DUPLICATE KEY UPDATE clause.
In this case *map contains table_map found on the previous call of
the function to check insert fields. Update fields are checked to be
from the same table as the insert fields.
@returns false if success.
*/
static bool check_view_single_update(List<Item> &fields, List<Item> *values,
TABLE_LIST *view, table_map *map,
bool insert)
{
/* it is join view => we need to find the table for update */
List_iterator_fast<Item> it(fields);
Item *item;
TABLE_LIST *tbl= 0; // reset for call to check_single_table()
table_map tables= 0;
while ((item= it++))
tables|= item->used_tables();
/*
Check that table is only one
(we can not rely on check_single_table because it skips some
types of tables)
*/
if (my_count_bits(tables) > 1)
goto error;
if (values)
{
it.init(*values);
while ((item= it++))
tables|= item->view_used_tables(view);
}
/* Convert to real table bits */
tables&= ~PSEUDO_TABLE_BITS;
/* Check found map against provided map */
if (*map)
{
if (tables != *map)
goto error;
return FALSE;
}
if (view->check_single_table(&tbl, tables, view) || tbl == 0)
goto error;
/* view->table should have been set in mysql_derived_merge_for_insert */
DBUG_ASSERT(view->table);
/*
Use buffer for the insert values that was allocated for the merged view.
*/
tbl->table->insert_values= view->table->insert_values;
view->table= tbl->table;
if (!tbl->single_table_updatable())
{
if (insert)
my_error(ER_NON_INSERTABLE_TABLE, MYF(0), view->alias.str, "INSERT");
else
my_error(ER_NON_UPDATABLE_TABLE, MYF(0), view->alias.str, "UPDATE");
return TRUE;
}
*map= tables;
return FALSE;
error:
my_error(ER_VIEW_MULTIUPDATE, MYF(0),
view->view_db.str, view->view_name.str);
return TRUE;
}
/*
Check if insert fields are correct.
@param thd The current thread.
@param table_list The table we are inserting into (may be view)
@param fields The insert fields.
@param values The insert values.
@param check_unique If duplicate values should be rejected.
@param fields_and_values_from_different_maps If 'values' are allowed to
refer to other tables than those of 'fields'
@param map See check_view_single_update
@returns 0 if success, -1 if error
*/
static int check_insert_fields(THD *thd, TABLE_LIST *table_list,
List<Item> &fields, List<Item> &values,
bool check_unique,
bool fields_and_values_from_different_maps,
table_map *map)
{
TABLE *table= table_list->table;
DBUG_ENTER("check_insert_fields");
if (!table_list->single_table_updatable())
{
my_error(ER_NON_INSERTABLE_TABLE, MYF(0), table_list->alias.str, "INSERT");
DBUG_RETURN(-1);
}
if (fields.elements == 0 && values.elements != 0)
{
if (!table)
{
my_error(ER_VIEW_NO_INSERT_FIELD_LIST, MYF(0),
table_list->view_db.str, table_list->view_name.str);
DBUG_RETURN(-1);
}
if (values.elements != table->s->visible_fields)
{
thd->get_stmt_da()->reset_current_row_for_warning(1);
my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
DBUG_RETURN(-1);
}
#ifndef NO_EMBEDDED_ACCESS_CHECKS
Field_iterator_table_ref field_it;
field_it.set(table_list);
if (check_grant_all_columns(thd, INSERT_ACL, &field_it))
DBUG_RETURN(-1);
#endif
/*
No fields are provided so all fields must be provided in the values.
Thus we set all bits in the write set.
*/
bitmap_set_all(table->write_set);
}
else
{ // Part field list
SELECT_LEX *select_lex= thd->lex->first_select_lex();
Name_resolution_context *context= &select_lex->context;
Name_resolution_context_state ctx_state;
int res;
if (fields.elements != values.elements)
{
thd->get_stmt_da()->reset_current_row_for_warning(1);
my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
DBUG_RETURN(-1);
}
thd->dup_field= 0;
select_lex->no_wrap_view_item= TRUE;
/* Save the state of the current name resolution context. */
ctx_state.save_state(context, table_list);
/*
Perform name resolution only in the first table - 'table_list',
which is the table that is inserted into.
*/
table_list->next_local= 0;
context->resolve_in_table_list_only(table_list);
/* 'Unfix' fields to allow correct marking by the setup_fields function. */
if (table_list->is_view())
unfix_fields(fields);
res= setup_fields(thd, Ref_ptr_array(),
fields, MARK_COLUMNS_WRITE, 0, NULL, 0,
THD_WHERE::INSERT_LIST);
/* Restore the current context. */
ctx_state.restore_state(context, table_list);
thd->lex->first_select_lex()->no_wrap_view_item= FALSE;
if (res)
DBUG_RETURN(-1);
if (table_list->is_view() && table_list->is_merged_derived())
{
if (check_view_single_update(fields,
fields_and_values_from_different_maps ?
(List<Item>*) 0 : &values,
table_list, map, true))
DBUG_RETURN(-1);
table= table_list->table;
}
if (check_unique && thd->dup_field)
{
my_error(ER_FIELD_SPECIFIED_TWICE, MYF(0),
thd->dup_field->field_name.str);
DBUG_RETURN(-1);
}
}
// For the values we need select_priv
#ifndef NO_EMBEDDED_ACCESS_CHECKS
table->grant.want_privilege= (SELECT_ACL & ~table->grant.privilege);
#endif
if (check_key_in_view(thd, table_list) ||
(table_list->view &&
check_view_insertability(thd, table_list, fields)))
{
my_error(ER_NON_INSERTABLE_TABLE, MYF(0), table_list->alias.str, "INSERT");
DBUG_RETURN(-1);
}
DBUG_RETURN(0);
}
static bool has_no_default_value(THD *thd, Field *field, TABLE_LIST *table_list)
{
if ((field->flags & (NO_DEFAULT_VALUE_FLAG | VERS_ROW_START | VERS_ROW_END))
== NO_DEFAULT_VALUE_FLAG && field->real_type() != MYSQL_TYPE_ENUM)
{
bool view= false;
if (table_list)
{
table_list= table_list->top_table();
view= table_list->view != NULL;
}
if (view)
{
push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, ER_NO_DEFAULT_FOR_VIEW_FIELD,
ER_THD(thd, ER_NO_DEFAULT_FOR_VIEW_FIELD),
table_list->view_db.str, table_list->view_name.str);
}
else
{
push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, ER_NO_DEFAULT_FOR_FIELD,
ER_THD(thd, ER_NO_DEFAULT_FOR_FIELD),
field->field_name.str);
}
return thd->really_abort_on_warning();
}
return false;
}
/**
Check if update fields are correct.
@param thd The current thread.
@param insert_table_list The table we are inserting into (may be view)
@param update_fields The update fields.
@param update_values The update values.
@param fields_and_values_from_different_maps If 'update_values' are allowed to
refer to other tables than those of 'update_fields'
@param map See check_view_single_update
@note
If the update fields include an autoinc field, set the
table->next_number_field_updated flag.
@returns 0 if success, -1 if error
*/
static int check_update_fields(THD *thd, TABLE_LIST *insert_table_list,
List<Item> &update_fields,
List<Item> &update_values,
bool fields_and_values_from_different_maps,
table_map *map)
{
TABLE *table= insert_table_list->table;
my_bool UNINIT_VAR(autoinc_mark);
enum_sql_command sql_command_save= thd->lex->sql_command;
table->next_number_field_updated= FALSE;
if (table->found_next_number_field)
{
/*
Unmark the auto_increment field so that we can check if this is modified
by update_fields
*/
autoinc_mark= bitmap_test_and_clear(table->write_set,
table->found_next_number_field->
field_index);
}
thd->lex->sql_command= SQLCOM_UPDATE;
/* Check the fields we are going to modify */
if (setup_fields(thd, Ref_ptr_array(),
update_fields, MARK_COLUMNS_WRITE, 0, NULL, 0,
THD_WHERE::UPDATE_CLAUSE))
{
thd->lex->sql_command= sql_command_save;
return -1;
}
thd->lex->sql_command= sql_command_save;
if (insert_table_list->is_view() &&
insert_table_list->is_merged_derived() &&
check_view_single_update(update_fields,
fields_and_values_from_different_maps ?
(List<Item>*) 0 : &update_values,
insert_table_list, map, false))
return -1;
if (table->default_field)
table->mark_default_fields_for_write(FALSE);
if (table->found_next_number_field)
{
if (bitmap_is_set(table->write_set,
table->found_next_number_field->field_index))
table->next_number_field_updated= TRUE;
if (autoinc_mark)
bitmap_set_bit(table->write_set,
table->found_next_number_field->field_index);
}
return 0;
}
/**
Upgrade table-level lock of INSERT statement to TL_WRITE if
a more concurrent lock is infeasible for some reason. This is
necessary for engines without internal locking support (MyISAM).
An engine with internal locking implementation might later
downgrade the lock in handler::store_lock() method.
*/
static
void upgrade_lock_type(THD *thd, thr_lock_type *lock_type,
enum_duplicates duplic)
{
if (duplic == DUP_UPDATE ||
(duplic == DUP_REPLACE && *lock_type == TL_WRITE_CONCURRENT_INSERT))
{
*lock_type= TL_WRITE_DEFAULT;
return;
}
if (*lock_type == TL_WRITE_DELAYED)
{
/*
We do not use delayed threads if:
- we're running in the safe mode or skip-new mode -- the
feature is disabled in these modes
- we're executing this statement on a replication slave --
we need to ensure serial execution of queries on the
slave
- it is INSERT .. ON DUPLICATE KEY UPDATE - in this case the
insert cannot be concurrent
- this statement is directly or indirectly invoked from
a stored function or trigger (under pre-locking) - to
avoid deadlocks, since INSERT DELAYED involves a lock
upgrade (TL_WRITE_DELAYED -> TL_WRITE) which we should not
attempt while keeping other table level locks.
- this statement itself may require pre-locking.
We should upgrade the lock even though in most cases
delayed functionality may work. Unfortunately, we can't
easily identify whether the subject table is not used in
the statement indirectly via a stored function or trigger:
if it is used, that will lead to a deadlock between the
client connection and the delayed thread.
- client explicitly ask to retrieve unitary changes
*/
if (specialflag & (SPECIAL_NO_NEW_FUNC | SPECIAL_SAFE_MODE) ||
thd->variables.max_insert_delayed_threads == 0 ||
thd->locked_tables_mode > LTM_LOCK_TABLES ||
thd->lex->uses_stored_routines() /*||
thd->lex->describe*/)
{
*lock_type= TL_WRITE;
return;
}
/* client explicitly asked to retrieved each affected rows and insert ids */
if (thd->need_report_unit_results())
{
*lock_type= TL_WRITE;
return;
}
if (thd->slave_thread)
{
/* Try concurrent insert */
*lock_type= (duplic == DUP_UPDATE || duplic == DUP_REPLACE) ?
TL_WRITE : TL_WRITE_CONCURRENT_INSERT;
return;
}
bool log_on= (thd->variables.option_bits & OPTION_BIN_LOG);
if (thd->wsrep_binlog_format(global_system_variables.binlog_format) == BINLOG_FORMAT_STMT &&
log_on && mysql_bin_log.is_open())
{
/*
Statement-based binary logging does not work in this case, because:
a) two concurrent statements may have their rows intermixed in the
queue, leading to autoincrement replication problems on slave (because
the values generated used for one statement don't depend only on the
value generated for the first row of this statement, so are not
replicable)
b) if first row of the statement has an error the full statement is
not binlogged, while next rows of the statement may be inserted.
c) if first row succeeds, statement is binlogged immediately with a
zero error code (i.e. "no error"), if then second row fails, query
will fail on slave too and slave will stop (wrongly believing that the
master got no error).
So we fallback to non-delayed INSERT.
Note that to be fully correct, we should test the "binlog format which
the delayed thread is going to use for this row". But in the common case
where the global binlog format is not changed and the session binlog
format may be changed, that is equal to the global binlog format.
We test it without mutex for speed reasons (condition rarely true), and
in the common case (global not changed) it is as good as without mutex;
if global value is changed, anyway there is uncertainty as the delayed
thread may be old and use the before-the-change value.
*/
*lock_type= TL_WRITE;
}
}
}
/**
Find or create a delayed insert thread for the first table in
the table list, then open and lock the remaining tables.
If a table can not be used with insert delayed, upgrade the lock
and open and lock all tables using the standard mechanism.
@param thd thread context
@param table_list list of "descriptors" for tables referenced
directly in statement SQL text.
The first element in the list corresponds to
the destination table for inserts, remaining
tables, if any, are usually tables referenced
by sub-queries in the right part of the
INSERT.
@return Status of the operation. In case of success 'table'
member of every table_list element points to an instance of
class TABLE.
@sa open_and_lock_tables for more information about MySQL table
level locking
*/
static
bool open_and_lock_for_insert_delayed(THD *thd, TABLE_LIST *table_list)
{
MDL_request protection_request;
DBUG_ENTER("open_and_lock_for_insert_delayed");
#ifndef EMBEDDED_LIBRARY
/* INSERT DELAYED is not allowed in a read only transaction. */
if (thd->tx_read_only)
{
my_error(ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION, MYF(0));
DBUG_RETURN(true);
}
/*
In order for the deadlock detector to be able to find any deadlocks
caused by the handler thread waiting for GRL or this table, we acquire
protection against GRL (global IX metadata lock) and metadata lock on
table to being inserted into inside the connection thread.
If this goes ok, the tickets are cloned and added to the list of granted
locks held by the handler thread.
*/
if (thd->has_read_only_protection())
DBUG_RETURN(TRUE);
MDL_REQUEST_INIT(&protection_request, MDL_key::BACKUP, "", "",
MDL_BACKUP_DML, MDL_STATEMENT);
if (thd->mdl_context.acquire_lock(&protection_request,
thd->variables.lock_wait_timeout))
DBUG_RETURN(TRUE);
if (thd->mdl_context.acquire_lock(&table_list->mdl_request,
thd->variables.lock_wait_timeout))
/*
If a lock can't be acquired, it makes no sense to try normal insert.
Therefore we just abort the statement.
*/
DBUG_RETURN(TRUE);
bool error= FALSE;
if (delayed_get_table(thd, &protection_request, table_list))
error= TRUE;
else if (table_list->table)
{
/*
Open tables used for sub-selects or in stored functions, will also
cache these functions.
*/
if (table_list->next_global &&
open_and_lock_tables(thd, table_list->next_global, TRUE,
MYSQL_OPEN_IGNORE_ENGINE_STATS))
{
end_delayed_insert(thd);
error= TRUE;
}
else
{
/*
First table was not processed by open_and_lock_tables(),
we need to set updatability flag "by hand".
*/
if (!table_list->derived && !table_list->view)
table_list->updatable= 1; // usual table
}
}
/*
We can't release protection against GRL and metadata lock on the table
being inserted into here. These locks might be required, for example,
because this INSERT DELAYED calls functions which may try to update
this or another tables (updating the same table is of course illegal,
but such an attempt can be discovered only later during statement
execution).
*/
/*
Reset the ticket in case we end up having to use normal insert and
therefore will reopen the table and reacquire the metadata lock.
*/
table_list->mdl_request.ticket= NULL;
if (error || table_list->table)
DBUG_RETURN(error);
#endif
/*
* This is embedded library and we don't have auxiliary
threads OR
* a lock upgrade was requested inside delayed_get_table
because
- there are too many delayed insert threads OR
- the table has triggers.
Use a normal insert.
*/
table_list->lock_type= TL_WRITE;
DBUG_RETURN(open_and_lock_tables(thd, table_list, TRUE, 0));
}
/**
Create a new query string for removing DELAYED keyword for
multi INSERT DELAYED statement.
@param[in] thd Thread handler
@param[in] buf Query string
@return
0 ok
1 error
*/
static int
create_insert_stmt_from_insert_delayed(THD *thd, String *buf)
{
/* Make a copy of thd->query() and then remove the "DELAYED" keyword */
if (buf->append(thd->query(), thd->query_length()) ||
buf->replace(thd->lex->keyword_delayed_begin_offset,
thd->lex->keyword_delayed_end_offset -
thd->lex->keyword_delayed_begin_offset, NULL, 0))
return 1;
return 0;
}
static void save_insert_query_plan(THD* thd, TABLE_LIST *table_list)
{
Explain_insert* explain= new (thd->mem_root) Explain_insert(thd->mem_root);
explain->table_name.append(table_list->table->alias);
thd->lex->explain->add_insert_plan(explain);
/* Save subquery children */
for (SELECT_LEX_UNIT *unit= thd->lex->first_select_lex()->first_inner_unit();
unit;
unit= unit->next_unit())
{
if (unit->explainable())
explain->add_child(unit->first_select()->select_number);
}
}
Field **TABLE::field_to_fill()
{
return triggers && triggers->nullable_fields() ? triggers->nullable_fields() : field;
}
/**
INSERT statement implementation
SYNOPSIS
mysql_insert()
result NULL if the insert is not outputing results
via 'RETURNING' clause.
@note Like implementations of other DDL/DML in MySQL, this function
relies on the caller to close the thread tables. This is done in the
end of dispatch_command().
*/
bool mysql_insert(THD *thd, TABLE_LIST *table_list,
List<Item> &fields, List<List_item> &values_list,
List<Item> &update_fields, List<Item> &update_values,
enum_duplicates duplic, bool ignore, select_result *result)
{
bool retval= true;
int error, res;
bool transactional_table, joins_freed= FALSE;
bool changed;
const bool was_insert_delayed= (table_list->lock_type == TL_WRITE_DELAYED);
bool using_bulk_insert= 0;
uint value_count;
/* counter of iteration in bulk PS operation*/
ulonglong iteration= 0;
ulonglong last_affected_rows= 0;
ulonglong id;
COPY_INFO info;
TABLE *table= 0;
List_iterator_fast<List_item> its(values_list);
List_item *values;
Name_resolution_context *context;
Name_resolution_context_state ctx_state;
SELECT_LEX *returning= thd->lex->has_returning() ? thd->lex->returning() : 0;
unsigned char *readbuff= NULL;
#ifndef EMBEDDED_LIBRARY
char *query= thd->query();
/*
log_on is about delayed inserts only.
By default, both logs are enabled (this won't cause problems if the server
runs without --log-bin).
*/
bool log_on= (thd->variables.option_bits & OPTION_BIN_LOG);
#endif
thr_lock_type lock_type;
Item *unused_conds= 0;
DBUG_ENTER("mysql_insert");
bzero((char*) &info,sizeof(info));
create_explain_query(thd->lex, thd->mem_root);
/*
Upgrade lock type if the requested lock is incompatible with
the current connection mode or table operation.
*/
upgrade_lock_type(thd, &table_list->lock_type, duplic);
/*
We can't write-delayed into a table locked with LOCK TABLES:
this will lead to a deadlock, since the delayed thread will
never be able to get a lock on the table.
*/
if (table_list->lock_type == TL_WRITE_DELAYED && thd->locked_tables_mode &&
find_locked_table(thd->open_tables, table_list->db.str,
table_list->table_name.str))
{
my_error(ER_DELAYED_INSERT_TABLE_LOCKED, MYF(0),
table_list->table_name.str);
DBUG_RETURN(TRUE);
}
if (table_list->lock_type == TL_WRITE_DELAYED)
{
if (open_and_lock_for_insert_delayed(thd, table_list))
DBUG_RETURN(TRUE);
}
else
{
if (open_and_lock_tables(thd, table_list, TRUE, 0))
DBUG_RETURN(TRUE);
}
THD_STAGE_INFO(thd, stage_init_update);
lock_type= table_list->lock_type;
thd->lex->used_tables=0;
values= its++;
if (bulk_parameters_set(thd))
DBUG_RETURN(TRUE);
value_count= values->elements;
if ((res= mysql_prepare_insert(thd, table_list, fields, values,
update_fields, update_values, duplic, ignore,
&unused_conds, FALSE)))
{
retval= thd->is_error();
if (res < 0)
{
/*
Insert should be ignored but we have to log the query in statement
format in the binary log
*/
if (thd->binlog_current_query_unfiltered())
retval= 1;
}
goto abort;
}
/* mysql_prepare_insert sets table_list->table if it was not set */
table= table_list->table;
/* Prepares LEX::returing_list if it is not empty */
if (returning)
{
result->prepare(returning->item_list, NULL);
if (thd->is_bulk_op())
{
/*
It is RETURNING which needs network buffer to write result set and
it is array binding which needs network buffer to read parameters.
So we allocate yet another network buffer.
The old buffer will be freed at the end of operation.
*/
DBUG_ASSERT(thd->protocol == &thd->protocol_binary);
readbuff= thd->net.buff; // old buffer
if (net_allocate_new_packet(&thd->net, thd, MYF(MY_THREAD_SPECIFIC)))
{
readbuff= NULL; // failure, net_allocate_new_packet keeps old buffer
goto abort;
}
}
}
context= &thd->lex->first_select_lex()->context;
/*
These three asserts test the hypothesis that the resetting of the name
resolution context below is not necessary at all since the list of local
tables for INSERT always consists of one table.
*/
DBUG_ASSERT(!table_list->next_local);
DBUG_ASSERT(!context->table_list->next_local);
DBUG_ASSERT(!context->first_name_resolution_table->next_name_resolution_table);
/* Save the state of the current name resolution context. */
ctx_state.save_state(context, table_list);
/*
Perform name resolution only in the first table - 'table_list',
which is the table that is inserted into.
*/
table_list->next_local= 0;
context->resolve_in_table_list_only(table_list);
switch_to_nullable_trigger_fields(*values, table);
/*
Check assignability for the leftmost () in VALUES:
INSERT INTO t1 (a,b) VALUES (1,2), (3,4);
This checks if the values (1,2) can be assigned to fields (a,b).
The further values, e.g. (3,4) are not checked - they will be
checked during the execution time (when processing actual rows).
This is to preserve the "insert until the very first error"-style
behaviour for non-transactional tables.
*/
if (values->elements &&
table_list->table->check_assignability_opt_fields(fields, *values,
ignore))
goto abort;
while ((values= its++))
{
thd->get_stmt_da()->inc_current_row_for_warning();
if (values->elements != value_count)
{
my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0),
thd->get_stmt_da()->current_row_for_warning());
goto abort;
}
if (setup_fields(thd, Ref_ptr_array(),
*values, MARK_COLUMNS_READ, 0, NULL, 0))
goto abort;
switch_to_nullable_trigger_fields(*values, table);
}
its.rewind ();
thd->get_stmt_da()->reset_current_row_for_warning(0);
/* Restore the current context. */
ctx_state.restore_state(context, table_list);
if (thd->lex->unit.first_select()->optimize_unflattened_subqueries(false))
{
goto abort;
}
save_insert_query_plan(thd, table_list);
if (thd->lex->describe)
{
bool extended= thd->lex->describe & DESCRIBE_EXTENDED;
retval= thd->lex->explain->send_explain(thd, extended);
goto abort;
}
/*
Fill in the given fields and dump it to the table file
*/
info.ignore= ignore;
info.handle_duplicates=duplic;
info.update_fields= &update_fields;
info.update_values= &update_values;
info.view= (table_list->view ? table_list : 0);
info.table_list= table_list;
/*
Count warnings for all inserts.
For single line insert, generate an error if try to set a NOT NULL field
to NULL.
*/
thd->count_cuted_fields= (values_list.elements == 1 && !ignore)
? CHECK_FIELD_ERROR_FOR_NULL : CHECK_FIELD_WARN;
thd->cuted_fields = 0L;
table->next_number_field=table->found_next_number_field;
#ifdef HAVE_REPLICATION
if (thd->rgi_slave &&
(info.handle_duplicates == DUP_UPDATE) &&
(table->next_number_field != NULL) &&
rpl_master_has_bug(thd->rgi_slave->rli, 24432, TRUE, NULL, NULL))
goto abort;
#endif
error=0;
if (duplic == DUP_REPLACE &&
(!table->triggers || !table->triggers->has_delete_triggers()))
table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE);
if (duplic == DUP_UPDATE)
table->file->extra(HA_EXTRA_INSERT_WITH_UPDATE);
thd->abort_on_warning= !ignore && thd->is_strict_mode();
table->reset_default_fields();
table->prepare_triggers_for_insert_stmt_or_event();
table->mark_columns_needed_for_insert();
/*
let's *try* to start bulk inserts. It won't necessary
start them as values_list.elements should be greater than
some - handler dependent - threshold.
We should not start bulk inserts if this statement uses
functions or invokes triggers since they may access
to the same table and therefore should not see its
inconsistent state created by this optimization.
So we call start_bulk_insert to perform necessary checks on
values_list.elements, and - if nothing else - to initialize
the code to make the call of end_bulk_insert() below safe.
*/
#ifndef EMBEDDED_LIBRARY
if (lock_type != TL_WRITE_DELAYED)
#endif /* EMBEDDED_LIBRARY */
{
bool create_lookup_handler= false;
if (duplic != DUP_ERROR || ignore)
{
create_lookup_handler= true;
table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
if (table->file->ha_table_flags() & HA_DUPLICATE_POS)
{
if (table->file->ha_rnd_init_with_error(0))
goto abort;
}
}
if (table->file->prepare_for_modify(true, create_lookup_handler))
goto abort;
/**
This is a simple check for the case when the table has a trigger
that reads from it, or when the statement invokes a stored function
that reads from the table being inserted to.
Engines can't handle a bulk insert in parallel with a read form the
same table in the same connection.
*/
if (thd->locked_tables_mode <= LTM_LOCK_TABLES &&
!table->s->long_unique_table && values_list.elements > 1)
{
using_bulk_insert= 1;
table->file->ha_start_bulk_insert(values_list.elements);
}
else
table->file->ha_reset_copy_info();
}
if (fields.elements || !value_count || table_list->view != 0)
{
if (table->field != table->field_to_fill())
{
/* BEFORE INSERT triggers exist, the check will be done later, per row */
}
else if (check_that_all_fields_are_given_values(thd, table, table_list))
{
error= 1;
goto values_loop_end;