-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathsql_load.cc
2698 lines (2372 loc) · 87.6 KB
/
sql_load.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, 2024, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
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, version 2.0, 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-1301 USA */
/* Copy data from a text file to table */
#include "sql/sql_load.h"
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
// Execute_load_query_log_event,
// LOG_EVENT_UPDATE_TABLE_MAP_VERSION_F
#include <string.h>
#include <sys/types.h>
#include <algorithm>
#include <atomic>
#include <limits>
#include <sstream>
#include "my_base.h"
#include "my_bitmap.h"
#include "my_dbug.h"
#include "my_dir.h"
#include "my_inttypes.h"
#include "my_io.h"
#include "my_macros.h"
#include "my_sys.h"
#include "my_thread_local.h"
#include "mysql/binlog/event/load_data_events.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/my_loglevel.h"
#include "mysql/psi/mysql_file.h"
#include "mysql/service_mysql_alloc.h"
#include "mysql/strings/m_ctype.h"
#include "mysql/thread_type.h"
#include "mysql_com.h"
#include "mysqld_error.h"
#include "nulls.h"
#include "scope_guard.h"
#include "sql/auth/auth_acls.h"
#include "sql/auth/auth_common.h"
#include "sql/binlog.h"
#include "sql/dd/cache/dictionary_client.h" // dd::cache::Dictionary_client
#include "sql/dd/dd_table.h" // dd::table_storage_engine
#include "sql/dd/types/abstract_table.h"
#include "sql/derror.h"
#include "sql/error_handler.h" // Ignore_error_handler
#include "sql/field.h"
#include "sql/handler.h"
#include "sql/item.h"
#include "sql/item_func.h"
#include "sql/item_timefunc.h" // Item_func_now_local
#include "sql/log.h"
#include "sql/log_event.h" // Delete_file_log_event,
#include "sql/mysqld.h" // mysql_real_data_home
#include "sql/protocol.h"
#include "sql/protocol_classic.h"
#include "sql/psi_memory_key.h"
#include "sql/query_result.h"
#include "sql/rpl_replica.h"
#include "sql/rpl_rli.h" // Relay_log_info
#include "sql/sql_base.h" // fill_record_n_invoke_before_triggers
#include "sql/sql_class.h"
#include "sql/sql_data_change.h"
#include "sql/sql_error.h"
#include "sql/sql_exchange.h"
#include "sql/sql_insert.h" // check_that_all_fields_are_given_values,
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_show.h"
#include "sql/sql_table.h"
#include "sql/sql_view.h" // check_key_in_view
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/table_trigger_dispatcher.h" // Table_trigger_dispatcher
#include "sql/thd_raii.h" // Disable_autocommit_guard
#include "sql/thr_malloc.h"
#include "sql/transaction.h"
#include "sql/transaction_info.h"
#include "sql/trigger_def.h"
#include "sql_string.h"
#include "string_with_len.h"
#include "strxnmov.h"
#include "thr_lock.h"
#include <mysql/components/services/bulk_load_service.h>
class READ_INFO;
using std::max;
using std::min;
class XML_TAG {
public:
int level;
String field;
String value;
XML_TAG(int l, String f, String v);
};
XML_TAG::XML_TAG(int l, String f, String v) {
level = l;
field.append(f);
value.append(v);
}
#define GET (stack_pos != stack ? *--stack_pos : my_b_get(&cache))
#define PUSH(A) *(stack_pos++) = (A)
class READ_INFO {
File file;
uchar *buffer; /* Buffer for read text */
uchar *end_of_buff; /* Data in buffer ends here */
size_t buff_length; /* Length of buffer */
const uchar *field_term_ptr, *line_term_ptr;
const char *line_start_ptr, *line_start_end;
size_t field_term_length, line_term_length, enclosed_length;
int field_term_char, line_term_char, enclosed_char, escape_char;
int *stack, *stack_pos;
bool found_end_of_line, start_of_line, eof;
bool need_end_io_cache;
IO_CACHE cache;
int level; /* for load xml */
size_t max_size() { return std::numeric_limits<size_t>::max() - 1; }
size_t check_length(size_t length, size_t grow) {
// Adding new element to the end of the buffer in amortized constant time is
// possible only if buffer capacity grows geometrically (capacity * 2) when
// buffer is full.
const size_t new_length = length + std::max(length, grow);
return ((new_length < length || new_length > max_size()) ? max_size()
: new_length);
}
public:
bool error, line_truncated, found_null, enclosed;
uchar *row_start, /* Found row starts here */
*row_end; /* Found row ends here */
const CHARSET_INFO *read_charset;
READ_INFO(File file, size_t tot_length, const CHARSET_INFO *cs,
const String &field_term, const String &line_start,
const String &line_term, const String &enclosed, int escape,
bool get_it_from_net, bool is_fifo);
~READ_INFO();
bool read_field();
bool read_fixed_length();
bool next_line();
char unescape(char chr);
bool terminator(const uchar *ptr, size_t length);
bool find_start_of_fields();
/* load xml */
List<XML_TAG> taglist;
int read_value(int delim, String *val);
int read_cdata(String *val, bool *have_cdata);
bool read_xml();
void clear_level(int level);
/*
We need to force cache close before destructor is invoked to log
the last read block
*/
void end_io_cache() {
::end_io_cache(&cache);
need_end_io_cache = false;
}
/*
Either this method, or we need to make cache public
Arg must be set from Sql_cmd_load_table::execute_inner()
since constructor does not see either the table or THD value
*/
void set_io_cache_arg(void *arg) { cache.arg = arg; }
/**
skip all data till the eof.
*/
void skip_data_till_eof() {
while (GET != my_b_EOF)
;
}
};
/**
Truncate to create a new table for BULK LOAD. The transaction is not
committed and rolls back if bulk load fails.
@param thd Current thread
@param table_ref table reference
@param table_def dd table
@returns true if error
*/
bool Sql_cmd_load_table::truncate_table_for_bulk_load(
THD *thd, Table_ref *const table_ref, dd::Table *table_def) {
DBUG_TRACE;
HA_CREATE_INFO dummy_create_info;
// Create a path to the table, but without a extension
char path[FN_REFLEN + 1];
build_table_filename(path, sizeof(path) - 1, table_ref->db,
table_ref->table_name, "", 0);
// Truncate table, attempt to reconstruct the table.
if (ha_create_table(thd, path, table_ref->db, table_ref->table_name,
&dummy_create_info, true, false, table_def) != 0) {
return true;
}
return false;
}
/**
Check bulk load parameters for limits.
@param thd Current thread
@returns true if error
*/
bool Sql_cmd_load_table::check_bulk_load_parameters(THD *thd) {
DBUG_TRACE;
/* On error, this function needs to return true. */
const bool error = true;
/* First check if bulk loader component is available. */
my_h_service svc = nullptr;
if (srv_registry->acquire("bulk_load_driver", &svc)) {
my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Bulk Load");
return error;
}
srv_registry->release(svc);
auto sec_ctx = thd->security_context();
if (m_bulk_source == LOAD_SOURCE_S3) {
if (!sec_ctx->has_global_grant(STRING_WITH_LEN("LOAD_FROM_S3")).first) {
my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), "LOAD_FROM_S3");
return true;
}
}
if (m_bulk_source == LOAD_SOURCE_URL) {
if (!sec_ctx->has_global_grant(STRING_WITH_LEN("LOAD_FROM_URL")).first) {
my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), "LOAD_FROM_URL");
return true;
}
}
const String *escaped = m_exchange.field.escaped;
const String *enclosed = m_exchange.field.enclosed;
/* Check for single byte separator. */
if (escaped->length() > 1 || enclosed->length() > 1) {
my_error(ER_WRONG_FIELD_TERMINATORS, MYF(0));
return true;
}
/* Report problems with non-ASCII separators */
const String *field_term = m_exchange.field.field_term;
const String *line_term = m_exchange.line.line_term;
if (!escaped->is_ascii() || !enclosed->is_ascii() ||
!field_term->is_ascii() || !line_term->is_ascii()) {
push_warning(thd, Sql_condition::SL_WARNING,
WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED,
ER_THD(thd, WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED));
}
return false;
}
/**
Validate table for bulk load operation.
@param thd Thread handle.
@param table_ref Table_ref instance of a table.
@param table_def DD table instance of a table.
@param[out] hton Handlerton instance of table's SE.
@returns false if bulk load can be executed on table.
*/
bool Sql_cmd_load_table::validate_table_for_bulk_load(
THD *thd, Table_ref *const table_ref, dd::Table *table_def,
handlerton **hton) {
// Table belongs to engine supporting bulk load.
(*hton) = nullptr;
if (dd::table_storage_engine(thd, table_def, hton)) {
/* Error is already raised. */
return true;
}
if ((*hton) == nullptr ||
!ha_check_storage_engine_flag(*hton, HTON_SUPPORTS_BULK_LOAD)) {
my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Bulk Load is not supported for SE");
return true;
}
/*
Engine supporting bulk should also supports atomic DDL and
truncate by recreate.
*/
assert((*hton)->flags & HTON_SUPPORTS_ATOMIC_DDL);
assert((*hton)->flags & HTON_CAN_RECREATE);
if (is_temporary_table(table_ref)) {
my_error(ER_NOT_SUPPORTED_YET, MYF(0),
"Temporary Table with LOAD ALGORITHM = BULK");
return true;
}
if (table_ref->is_view() || !table_ref->is_insertable() ||
!table_ref->is_updatable()) {
my_error(ER_NON_INSERTABLE_TABLE, MYF(0), table_ref->alias, "BULK LOAD");
return true;
}
if (table_ref->table->part_info != nullptr) {
my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Partitioned Table");
return true;
}
if (!table_ref->table->file->bulk_load_check(thd)) {
/* SE already raises the error. */
return true;
}
/*
Skip Foreign Key and Secondary Engine check. They would eventually fail
during bulk load execution and rollback.
*/
return false;
}
/**
Execute BULK LOAD DATA
@param thd Current thread.
@returns true if error
*/
bool Sql_cmd_load_table::execute_bulk(THD *thd) {
DBUG_TRACE;
if (check_bulk_load_parameters(thd)) {
return true;
}
/* Disallow Bulk Load if the table is locked with LOCK TABLE. */
if (thd->locked_tables_mode != LTM_NONE) {
my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0));
return true;
}
Table_ref *table_ref = thd->lex->query_tables;
// Acquire MDL lock on table, BACKUP_LOCK and GLOBAL lock objects.
if (lock_table_names(thd, table_ref, nullptr,
thd->variables.lock_wait_timeout, 0)) {
return true;
}
/* Truncate requires disabling auto commit guard. */
const Disable_autocommit_guard autocommit_guard(thd);
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
THD_STAGE_INFO(thd, stage_executing);
// Acquire DD instance for modification. Truncate operation modifies DD
// table instance.
dd::Table *table_def = nullptr;
if (thd->dd_client()->acquire_for_modification(
table_ref->db, table_ref->table_name, &table_def)) {
return true;
}
if (table_def == nullptr) {
my_error(ER_NO_SUCH_TABLE, MYF(0), table_ref->db, table_ref->table_name);
return true;
}
uint counter;
if (open_tables(thd, &table_ref, &counter, MYSQL_OPEN_HAS_MDL_LOCK)) {
return true;
}
handlerton *hton = nullptr;
if (validate_table_for_bulk_load(thd, table_ref, table_def, &hton)) {
return true;
}
/*
We need to close the table and reset the table_ref so that it can be used
to re-open the table after truncate.
*/
close_thread_tables(thd);
tdc_remove_table(thd, TDC_RT_REMOVE_ALL, table_ref->db, table_ref->table_name,
false);
table_ref->table = nullptr;
bool success = false;
// Actions needed to cleanup before leaving scope.
auto cleanup_guard = create_scope_guard([&]() {
THD_STAGE_INFO(thd, stage_end);
close_thread_tables(thd);
// End transaction
if (success) {
success = !(trans_commit_stmt(thd) || trans_commit_implicit(thd));
}
if (!success) {
trans_rollback_stmt(thd);
trans_rollback_implicit(thd);
tdc_remove_table(thd, TDC_RT_REMOVE_ALL, table_ref->db,
table_ref->table_name, false);
}
// Post DDL action for truncate. */
if (hton != nullptr && hton->post_ddl) {
hton->post_ddl(thd);
}
});
/*
We start bulk ingestion by truncating the table. We then continue the same
transaction loading data and finishing with a commit or rollback.
1. At this point the table is validated to not have any user data. It is
thus safe to truncate.
2. Truncate command creates a new space for the data to be loaded and the
atomicity guarantee is provided by the truncate DDL log.
a. Commit (Success case): Old tablespace is removed and we have the new
one loaded with user data. The new space id is committed in DD SE
private data.
b. Rollback (Unsuccessful case): New tablespace with partially loaded
data is removed and old tablespace remains. Rollback brings back the
old tablespace ID in DD SE private data. Cached objects are removed.
*/
if (truncate_table_for_bulk_load(thd, table_ref, table_def)) {
my_error(ER_INTERNAL_ERROR, MYF(0), "BULK LOAD: Truncate failed");
return true;
}
/*
Open the table after truncate. Here we open the destination table, on which
we already have an exclusive metadata lock.
*/
if (open_tables(thd, &table_ref, &counter, MYSQL_OPEN_HAS_MDL_LOCK)) {
return true;
}
size_t affected_rows = 0;
if (!bulk_driver_service(thd, table_ref->table, affected_rows)) {
return true;
}
success = true;
char ok_message[512];
snprintf(
ok_message, sizeof(ok_message), ER_THD(thd, ER_LOAD_INFO),
static_cast<long>(affected_rows), 0L, 0L,
static_cast<long>(thd->get_stmt_da()->current_statement_cond_count()));
my_ok(thd, affected_rows, 0LL, ok_message);
return false;
}
bool Sql_cmd_load_table::bulk_driver_service(THD *thd, const TABLE *table,
size_t &affected_rows) {
Bulk_source src = Bulk_source::LOCAL;
switch (m_bulk_source) {
case LOAD_SOURCE_URL:
src = Bulk_source::OCI;
break;
case LOAD_SOURCE_S3:
src = Bulk_source::S3;
break;
case LOAD_SOURCE_FILE:
src = Bulk_source::LOCAL;
break;
}
std::string lowercase(m_compression_algorithm_string.str,
m_compression_algorithm_string.length);
std::transform(lowercase.begin(), lowercase.end(), lowercase.begin(),
::tolower);
Bulk_compression_algorithm compression_algorithm =
Bulk_compression_algorithm::NONE;
if (m_compression_algorithm_string.length == 0) {
compression_algorithm = Bulk_compression_algorithm::NONE;
} else if (lowercase == "zstd") {
compression_algorithm = Bulk_compression_algorithm::ZSTD;
} else {
std::stringstream ss;
ss << "Invalid compression algorithm: "
<< std::string(m_compression_algorithm_string.str,
m_compression_algorithm_string.length);
my_error(ER_WRONG_USAGE, MYF(0), "LOAD DATA with BULK Algorithm",
ss.str().c_str());
return false;
}
std::string file_name_arg(m_exchange.file_name);
Bulk_load_file_info info(src, file_name_arg, m_file_count);
{
std::string error;
if (!info.parse(error)) {
my_error(ER_BULK_PARSER_ERROR, MYF(0), error.c_str());
return false;
}
}
if (src == Bulk_source::LOCAL) {
char name[FN_REFLEN];
Table_ref *const table_list = thd->lex->query_tables;
const char *db = table_list->db;
const char *tdb = thd->db().str ? thd->db().str : db;
if (!dirname_length(info.m_file_prefix.c_str())) {
strxnmov(name, FN_REFLEN - 1, mysql_real_data_home, tdb, NullS);
(void)fn_format(name, info.m_file_prefix.c_str(), name, "",
MY_RELATIVE_PATH | MY_UNPACK_FILENAME);
} else {
(void)fn_format(
name, info.m_file_prefix.c_str(), mysql_real_data_home, "",
MY_RELATIVE_PATH | MY_UNPACK_FILENAME | MY_RETURN_REAL_PATH);
}
if (!is_secure_file_path(name)) {
/* Read only allowed from within dir specified by secure_file_priv */
my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv");
return false;
}
/* Replace relative path. */
if (!test_if_hard_path(info.m_file_prefix.c_str())) {
info.m_file_prefix.assign(name);
}
}
my_h_service svc = nullptr;
if (srv_registry->acquire("bulk_load_driver", &svc)) {
my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Bulk Load");
return false;
}
auto load_driver = reinterpret_cast<SERVICE_TYPE(bulk_load_driver) *>(svc);
auto load_handle = load_driver->create_bulk_loader(
thd, thd->thread_id(), table, src,
(m_exchange.file_info.cs != nullptr) ? m_exchange.file_info.cs
: thd->variables.collation_database);
/* Set schema, table, file name string options. */
std::string schema_name(table->s->db.str, table->s->db.length);
load_driver->set_string(load_handle, Bulk_string::SCHEMA_NAME, schema_name);
std::string table_name(table->s->table_name.str, table->s->table_name.length);
load_driver->set_string(load_handle, Bulk_string::TABLE_NAME, table_name);
load_driver->set_string(load_handle, Bulk_string::FILE_PREFIX,
info.m_file_prefix);
if (info.m_file_suffix.has_value()) {
load_driver->set_string(load_handle, Bulk_string::FILE_SUFFIX,
info.m_file_suffix.value());
}
if (!info.m_appendtolastprefix.empty()) {
load_driver->set_string(load_handle, Bulk_string::APPENDTOLASTPREFIX,
info.m_appendtolastprefix);
}
/* If not set by user, default is assigned from default_field_term. */
const String *field_term = m_exchange.field.field_term;
std::string col_term(field_term->ptr(), field_term->length());
load_driver->set_string(load_handle, Bulk_string::COLUMN_TERM, col_term);
/* If not set by user, default is assigned from default_line_term. */
const String *line_term = m_exchange.line.line_term;
std::string row_term(line_term->ptr(), line_term->length());
load_driver->set_string(load_handle, Bulk_string::ROW_TERM, row_term);
/* Set boolean options. */
load_driver->set_condition(load_handle, Bulk_condition::ORDERED_DATA,
m_ordered_data);
load_driver->set_condition(load_handle, Bulk_condition::OPTIONAL_ENCLOSE,
m_exchange.field.opt_enclosed);
load_driver->set_condition(load_handle, Bulk_condition::DRYRUN,
info.m_is_dryrun);
/* Set size options. */
load_driver->set_size(load_handle, Bulk_size::CONCURRENCY, m_concurrency);
load_driver->set_size(load_handle, Bulk_size::COUNT_FILES, m_file_count);
load_driver->set_size(load_handle, Bulk_size::START_INDEX,
info.m_start_index);
load_driver->set_size(load_handle, Bulk_size::COUNT_ROW_SKIP,
m_exchange.skip_lines);
load_driver->set_size(load_handle, Bulk_size::COUNT_COLUMNS,
table->s->fields);
load_driver->set_size(load_handle, Bulk_size::MEMORY, m_memory_size);
/* Set escape and enclosing character options */
const String *escaped = m_exchange.field.escaped;
const String *enclosed = m_exchange.field.enclosed;
if (m_exchange.escaped_given() && !escaped->is_empty()) {
load_driver->set_char(load_handle, Bulk_char::ESCAPE_CHAR, (*escaped)[0]);
}
if (!enclosed->is_empty()) {
load_driver->set_char(load_handle, Bulk_char::ENCLOSE_CHAR, (*enclosed)[0]);
}
load_driver->set_compression_algorithm(load_handle, compression_algorithm);
bool success = load_driver->load(load_handle, affected_rows);
load_driver->drop_bulk_loader(thd, load_handle);
srv_registry->release(svc);
return success;
}
/**
Execute LOAD DATA query
@param thd Current thread.
@param handle_duplicates Indicates whenever we should emit error or
replace row if we will meet duplicates.
@returns true if error
*/
bool Sql_cmd_load_table::execute_inner(THD *thd,
enum enum_duplicates handle_duplicates) {
char name[FN_REFLEN];
File file;
bool error = false;
const String *field_term = m_exchange.field.field_term;
const String *escaped = m_exchange.field.escaped;
const String *enclosed = m_exchange.field.enclosed;
bool is_fifo = false;
Query_block *select = thd->lex->query_block;
LOAD_FILE_INFO lf_info;
THD::killed_state killed_status = THD::NOT_KILLED;
bool is_concurrent;
bool transactional_table;
Table_ref *const table_list = thd->lex->query_tables;
const char *db = table_list->db; // This is never null
/*
If path for file is not defined, we will use the current database.
If this is not set, we will use the directory where the table to be
loaded is located
*/
const char *tdb = thd->db().str ? thd->db().str : db; // Result is never null
ulong skip_lines = m_exchange.skip_lines;
DBUG_TRACE;
/*
Bug #34283
mysqlbinlog leaves tmpfile after termination if binlog contains
load data infile, so in mixed mode we go to row-based for
avoiding the problem.
*/
thd->set_current_stmt_binlog_format_row_if_mixed();
if (escaped->length() > 1 || enclosed->length() > 1) {
my_error(ER_WRONG_FIELD_TERMINATORS, MYF(0));
return true;
}
/* Report problems with non-ascii separators */
if (!escaped->is_ascii() || !enclosed->is_ascii() ||
!field_term->is_ascii() || !m_exchange.line.line_term->is_ascii() ||
!m_exchange.line.line_start->is_ascii()) {
push_warning(thd, Sql_condition::SL_WARNING,
WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED,
ER_THD(thd, WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED));
}
if (open_and_lock_tables(thd, table_list, 0)) return true;
THD_STAGE_INFO(thd, stage_executing);
if (select->setup_tables(thd, table_list, false)) return true;
if (run_before_dml_hook(thd)) return true;
if (table_list->is_view() && select->resolve_placeholder_tables(thd, false))
return true; /* purecov: inspected */
Table_ref *const insert_table_ref =
table_list->is_updatable() && // View must be updatable
!table_list
->is_multiple_tables() && // Multi-table view not allowed
!table_list->is_derived()
? // derived tables not allowed
table_list->updatable_base_table()
: nullptr;
if (insert_table_ref == nullptr ||
check_key_in_view(thd, table_list, insert_table_ref)) {
my_error(ER_NON_UPDATABLE_TABLE, MYF(0), table_list->alias, "LOAD");
return true;
}
if (select->derived_table_count &&
select->check_view_privileges(thd, INSERT_ACL, SELECT_ACL))
return true; /* purecov: inspected */
if (table_list->is_merged()) {
if (table_list->prepare_check_option(thd)) return true;
if (handle_duplicates == DUP_REPLACE &&
table_list->prepare_replace_filter(thd))
return true;
}
// Pass the check option down to the underlying table:
insert_table_ref->check_option = table_list->check_option;
/*
Let us emit an error if we are loading data to table which is used
in subselect in SET clause like we do it for INSERT.
The main thing to fix to remove this restriction is to ensure that the
table is marked to be 'used for insert' in which case we should never
mark this table as 'const table' (ie, one that has only one row).
*/
if (unique_table(insert_table_ref, table_list->next_global, false)) {
my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->table_name);
return true;
}
TABLE *const table = insert_table_ref->table;
for (Field **cur_field = table->field; *cur_field; ++cur_field)
(*cur_field)->reset_warnings();
transactional_table = table->file->has_transactions();
is_concurrent =
(table_list->lock_descriptor().type == TL_WRITE_CONCURRENT_INSERT);
if (m_opt_fields_or_vars.empty()) {
Field_iterator_table_ref field_iterator;
field_iterator.set(table_list);
for (; !field_iterator.end_of_fields(); field_iterator.next()) {
// Do not include user hidden fields.
if (field_iterator.field() != nullptr &&
field_iterator.field()->is_hidden())
continue;
Item *item;
if (!(item = field_iterator.create_item(thd))) return true;
if (item->field_for_view_update() == nullptr) {
my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), item->item_name.ptr());
return true;
}
m_opt_fields_or_vars.push_back(item->real_item());
}
bitmap_set_all(table->write_set);
/*
Let us also prepare SET clause, although it is probably empty
in this case.
*/
if (setup_fields(thd, /*want_privilege=*/INSERT_ACL,
/*allow_sum_func=*/false, /*split_sum_funcs=*/false,
/*column_update=*/true, /*typed_items=*/nullptr,
&m_opt_set_fields, Ref_item_array()) ||
setup_fields(thd, /*want_privilege=*/SELECT_ACL,
/*allow_sum_func=*/false, /*split_sum_funcs=*/false,
/*column_update=*/false, /*typed_items=*/nullptr,
&m_opt_set_exprs, Ref_item_array()))
return true;
} else { // Part field list
/*
Because m_opt_fields_or_vars may contain user variables,
pass false for column_update in first call below.
*/
if (setup_fields(thd, /*want_privilege=*/INSERT_ACL,
/*allow_sum_func=*/false, /*split_sum_funcs=*/false,
/*column_update=*/false, /*typed_items=*/nullptr,
&m_opt_fields_or_vars, Ref_item_array()) ||
setup_fields(thd, /*want_privilege=*/INSERT_ACL,
/*allow_sum_func=*/false, /*split_sum_funcs=*/false,
/*column_update=*/true, /*typed_items=*/nullptr,
&m_opt_set_fields, Ref_item_array()))
return true;
/*
Special updatability test is needed because m_opt_fields_or_vars may
contain a mix of column references and user variables.
*/
for (Item *item : m_opt_fields_or_vars) {
if ((item->type() == Item::FIELD_ITEM ||
item->type() == Item::REF_ITEM) &&
item->field_for_view_update() == nullptr) {
my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), item->item_name.ptr());
return true;
}
if (item->type() == Item::STRING_ITEM) {
/*
This item represents a user variable. Create a new item with the
same name that can be added to LEX::set_var_list. This ensures
that corresponding Item_func_get_user_var items are resolved as
non-const items.
*/
Item_func_set_user_var *user_var =
new (thd->mem_root) Item_func_set_user_var(item->item_name, item);
if (user_var == nullptr) return true;
thd->lex->set_var_list.push_back(user_var);
}
}
// Consider the following table:
//
// CREATE TABLE t1 (x DOUBLE, y DOUBLE, g POINT SRID 4326 NOT NULL);
//
// If the user wants to load a file which only contains two values (x and y
// coordinates), it is possible to do it by executing the following
// statement:
//
// LOAD DATA INFILE 'data' (@x, @y)
// SET x = @x, y = @y, g = ST_SRID(POINT(@x, @y));
//
// However, the columns that are specified in the SET clause are only marked
// in the write set, and not in fields_set_during_insert. The latter is the
// bitmap used during check_that_all_fields_are_given_values(), so we need
// to copy the bits from the write set over to said bitmap. If not, the
// server will return an error saying that column 'g' doesn't have a default
// value.
bitmap_union(table->fields_set_during_insert, table->write_set);
if (check_that_all_fields_are_given_values(thd, table, table_list))
return true;
/* Fix the expressions in SET clause */
if (setup_fields(thd, /*want_privilege=*/SELECT_ACL,
/*allow_sum_func=*/false, /*split_sum_funcs=*/false,
/*column_update=*/false, /*typed_items=*/nullptr,
&m_opt_set_exprs, Ref_item_array()))
return true;
}
const int escape_char =
(escaped->length() &&
(m_exchange.escaped_given() ||
!(thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES)))
? (*escaped)[0]
: INT_MAX;
/*
* LOAD DATA INFILE fff INTO TABLE xxx SET columns2
sets all columns, except if file's row lacks some: in that case,
defaults are set by read_fixed_length() and read_sep_field(),
not by COPY_INFO.
* LOAD DATA INFILE fff INTO TABLE xxx (columns1) SET columns2=
may need a default for columns other than columns1 and columns2.
*/
const bool manage_defaults = !m_opt_fields_or_vars.empty();
COPY_INFO info(COPY_INFO::INSERT_OPERATION, &m_opt_fields_or_vars,
&m_opt_set_fields, manage_defaults, handle_duplicates,
escape_char);
if (info.add_function_default_columns(table, table->write_set)) return true;
if (table->triggers) {
if (table->triggers->mark_fields(TRG_EVENT_INSERT)) return true;
}
prepare_triggers_for_insert_stmt(thd, table);
size_t tot_length = 0;
bool use_blobs = false, use_vars = false;
for (Item *item : m_opt_fields_or_vars) {
const Item *real_item = item->real_item();
if (real_item->type() == Item::FIELD_ITEM) {
const Field *field = down_cast<const Item_field *>(real_item)->field;
if (field->is_flag_set(BLOB_FLAG)) {
use_blobs = true;
tot_length += 4096; // Will be extended if needed
} else {
tot_length += field->field_length;
}
} else if (item->type() == Item::STRING_ITEM) {
use_vars = true;
}
}
if (use_blobs && m_exchange.line.line_term->is_empty() &&
field_term->is_empty()) {
my_error(ER_BLOBS_AND_NO_TERMINATED, MYF(0));
return true;
}
if (use_vars && !field_term->length() && !enclosed->length()) {
my_error(ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR, MYF(0));
return true;
}
// Statement is fully prepared:
thd->lex->unit->set_prepared();
// Start execution:
thd->lex->set_exec_started();
if (m_is_local_file) {
(void)net_request_file(thd->get_protocol_classic()->get_net(),
m_exchange.file_name);
file = -1;
} else {
if (!dirname_length(m_exchange.file_name)) {
strxnmov(name, FN_REFLEN - 1, mysql_real_data_home, tdb, NullS);
(void)fn_format(name, m_exchange.file_name, name, "",
MY_RELATIVE_PATH | MY_UNPACK_FILENAME);
} else {
(void)fn_format(
name, m_exchange.file_name, mysql_real_data_home, "",
MY_RELATIVE_PATH | MY_UNPACK_FILENAME | MY_RETURN_REAL_PATH);
}
if ((thd->system_thread &
(SYSTEM_THREAD_SLAVE_SQL | SYSTEM_THREAD_SLAVE_WORKER)) != 0) {
Relay_log_info *rli = thd->rli_slave->get_c_rli();
if (strncmp(rli->slave_patternload_file, name,
rli->slave_patternload_file_size)) {
/*
LOAD DATA INFILE in the slave SQL Thread can only read from
--replica-load-tmpdir". This should never happen. Please, report a
bug.
*/
LogErr(ERROR_LEVEL, ER_LOAD_DATA_INFILE_FAILED_IN_UNEXPECTED_WAY);
my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--replica-load-tmpdir");
return true;
}
} else if (!is_secure_file_path(name)) {
/* Read only allowed from within dir specified by secure_file_priv */
my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv");
return true;
}
#if !defined(_WIN32)
MY_STAT stat_info;
if (!my_stat(name, &stat_info, MYF(MY_WME))) return true;
// if we are not in slave thread, the file must be:
if (!thd->slave_thread &&
!((stat_info.st_mode & S_IFLNK) != S_IFLNK && // symlink
((stat_info.st_mode & S_IFREG) == S_IFREG || // regular file
(stat_info.st_mode & S_IFIFO) == S_IFIFO))) // named pipe
{
my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), name);
return true;
}
if ((stat_info.st_mode & S_IFIFO) == S_IFIFO) is_fifo = true;
#endif
if ((file = mysql_file_open(key_file_load, name, O_RDONLY, MYF(MY_WME))) <
0)
return true;
}
READ_INFO read_info(
file, tot_length,
(m_exchange.file_info.cs != nullptr) ? m_exchange.file_info.cs
: thd->variables.collation_database,
*field_term, *m_exchange.line.line_start, *m_exchange.line.line_term,
*enclosed, info.escape_char, m_is_local_file, is_fifo);
if (read_info.error) {
if (file >= 0) mysql_file_close(file, MYF(0)); // no files in net reading
return true; // Can't allocate buffers
}
if (mysql_bin_log.is_open()) {
lf_info.thd = thd;
lf_info.logged_data_file = false;
lf_info.last_pos_in_file = HA_POS_ERROR;
lf_info.log_delayed = transactional_table;
read_info.set_io_cache_arg((void *)&lf_info);
}