~drizzle-trunk/drizzle/development

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
/* Copyright (C) 2000-2006 MySQL AB

   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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


/* Insert of records */

#include "config.h"
#include <drizzled/sql_select.h>
#include <drizzled/show.h>
#include <drizzled/error.h>
#include <drizzled/name_resolution_context_state.h>
#include <drizzled/probes.h>
#include <drizzled/sql_base.h>
#include <drizzled/sql_load.h>
#include <drizzled/field/timestamp.h>
#include <drizzled/lock.h>
#include "drizzled/sql_table.h"
#include "drizzled/pthread_globals.h"
#include "drizzled/transaction_services.h"
#include "drizzled/plugin/transactional_storage_engine.h"

namespace drizzled
{

extern plugin::StorageEngine *heap_engine;
extern plugin::StorageEngine *myisam_engine;

/*
  Check if insert fields are correct.

  SYNOPSIS
    check_insert_fields()
    session                         The current thread.
    table                       The table for insert.
    fields                      The insert fields.
    values                      The insert values.
    check_unique                If duplicate values should be rejected.

  NOTE
    Clears TIMESTAMP_AUTO_SET_ON_INSERT from table->timestamp_field_type
    or leaves it as is, depending on if timestamp should be updated or
    not.

  RETURN
    0           OK
    -1          Error
*/

static int check_insert_fields(Session *session, TableList *table_list,
                               List<Item> &fields, List<Item> &values,
                               bool check_unique,
                               table_map *)
{
  Table *table= table_list->table;

  if (fields.elements == 0 && values.elements != 0)
  {
    if (values.elements != table->s->fields)
    {
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
      return -1;
    }
    clear_timestamp_auto_bits(table->timestamp_field_type,
                              TIMESTAMP_AUTO_SET_ON_INSERT);
    /*
      No fields are provided so all fields must be provided in the values.
      Thus we set all bits in the write set.
    */
    table->setWriteSet();
  }
  else
  {						// Part field list
    Select_Lex *select_lex= &session->lex->select_lex;
    Name_resolution_context *context= &select_lex->context;
    Name_resolution_context_state ctx_state;
    int res;

    if (fields.elements != values.elements)
    {
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
      return -1;
    }

    session->dup_field= 0;

    /* 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);
    res= setup_fields(session, 0, fields, MARK_COLUMNS_WRITE, 0, 0);

    /* Restore the current context. */
    ctx_state.restore_state(context, table_list);

    if (res)
      return -1;

    if (check_unique && session->dup_field)
    {
      my_error(ER_FIELD_SPECIFIED_TWICE, MYF(0), session->dup_field->field_name);
      return -1;
    }
    if (table->timestamp_field)	// Don't automaticly set timestamp if used
    {
      if (table->timestamp_field->isWriteSet())
        clear_timestamp_auto_bits(table->timestamp_field_type,
                                  TIMESTAMP_AUTO_SET_ON_INSERT);
      else
      {
        table->setWriteSet(table->timestamp_field->field_index);
      }
    }
  }

  return 0;
}


/*
  Check update fields for the timestamp field.

  SYNOPSIS
    check_update_fields()
    session                         The current thread.
    insert_table_list           The insert table list.
    table                       The table for update.
    update_fields               The update fields.

  NOTE
    If the update fields include the timestamp field,
    remove TIMESTAMP_AUTO_SET_ON_UPDATE from table->timestamp_field_type.

  RETURN
    0           OK
    -1          Error
*/

static int check_update_fields(Session *session, TableList *insert_table_list,
                               List<Item> &update_fields,
                               table_map *)
{
  Table *table= insert_table_list->table;
  bool timestamp_mark= false;

  if (table->timestamp_field)
  {
    /*
      Unmark the timestamp field so that we can check if this is modified
      by update_fields
    */
    timestamp_mark= table->write_set->testAndClear(table->timestamp_field->field_index);
  }

  /* Check the fields we are going to modify */
  if (setup_fields(session, 0, update_fields, MARK_COLUMNS_WRITE, 0, 0))
    return -1;

  if (table->timestamp_field)
  {
    /* Don't set timestamp column if this is modified. */
    if (table->timestamp_field->isWriteSet())
      clear_timestamp_auto_bits(table->timestamp_field_type,
                                TIMESTAMP_AUTO_SET_ON_UPDATE);
    if (timestamp_mark)
      table->setWriteSet(table->timestamp_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(Session *,
                       thr_lock_type *lock_type,
                       enum_duplicates duplic,
                       bool )
{
  if (duplic == DUP_UPDATE ||
      (duplic == DUP_REPLACE && *lock_type == TL_WRITE_CONCURRENT_INSERT))
  {
    *lock_type= TL_WRITE_DEFAULT;
    return;
  }
}


/**
  INSERT statement implementation

  @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(Session *session,TableList *table_list,
                  List<Item> &fields,
                  List<List_item> &values_list,
                  List<Item> &update_fields,
                  List<Item> &update_values,
                  enum_duplicates duplic,
		  bool ignore)
{
  int error;
  bool transactional_table, joins_freed= false;
  bool changed;
  uint32_t value_count;
  ulong counter = 1;
  uint64_t 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;
  thr_lock_type lock_type;
  Item *unused_conds= 0;


  /*
    Upgrade lock type if the requested lock is incompatible with
    the current connection mode or table operation.
  */
  upgrade_lock_type(session, &table_list->lock_type, duplic,
                    values_list.elements > 1);

  if (session->openTablesLock(table_list))
  {
    DRIZZLE_INSERT_DONE(1, 0);
    return true;
  }

  lock_type= table_list->lock_type;

  session->set_proc_info("init");
  session->used_tables=0;
  values= its++;
  value_count= values->elements;

  if (mysql_prepare_insert(session, table_list, table, fields, values,
			   update_fields, update_values, duplic, &unused_conds,
                           false,
                           (fields.elements || !value_count ||
                            (0) != 0), !ignore))
    goto abort;

  /* mysql_prepare_insert set table_list->table if it was not set */
  table= table_list->table;

  context= &session->lex->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.
  */
  assert(!table_list->next_local);
  assert(!context->table_list->next_local);
  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);

  while ((values= its++))
  {
    counter++;
    if (values->elements != value_count)
    {
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), counter);
      goto abort;
    }
    if (setup_fields(session, 0, *values, MARK_COLUMNS_READ, 0, 0))
      goto abort;
  }
  its.rewind ();

  /* Restore the current context. */
  ctx_state.restore_state(context, table_list);

  /*
    Fill in the given fields and dump it to the table cursor
  */
  memset(&info, 0, sizeof(info));
  info.ignore= ignore;
  info.handle_duplicates=duplic;
  info.update_fields= &update_fields;
  info.update_values= &update_values;

  /*
    Count warnings for all inserts.
    For single line insert, generate an error if try to set a NOT NULL field
    to NULL.
  */
  session->count_cuted_fields= ((values_list.elements == 1 &&
                                 !ignore) ?
                                CHECK_FIELD_ERROR_FOR_NULL :
                                CHECK_FIELD_WARN);
  session->cuted_fields = 0L;
  table->next_number_field=table->found_next_number_field;

  error=0;
  session->set_proc_info("update");
  if (duplic == DUP_REPLACE)
    table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
  if (duplic == DUP_UPDATE)
    table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
  {
    if (duplic != DUP_ERROR || ignore)
      table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
    table->cursor->ha_start_bulk_insert(values_list.elements);
  }


  session->abort_on_warning= !ignore;

  table->mark_columns_needed_for_insert();

  while ((values= its++))
  {
    if (fields.elements || !value_count)
    {
      table->restoreRecordAsDefault();	// Get empty record
      if (fill_record(session, fields, *values))
      {
	if (values_list.elements != 1 && ! session->is_error())
	{
	  info.records++;
	  continue;
	}
	/*
	  TODO: set session->abort_on_warning if values_list.elements == 1
	  and check that all items return warning in case of problem with
	  storing field.
        */
	error=1;
	break;
      }
    }
    else
    {
      table->restoreRecordAsDefault();	// Get empty record

      if (fill_record(session, table->field, *values))
      {
	if (values_list.elements != 1 && ! session->is_error())
	{
	  info.records++;
	  continue;
	}
	error=1;
	break;
      }
    }

    // Release latches in case bulk insert takes a long time
    plugin::TransactionalStorageEngine::releaseTemporaryLatches(session);

    error=write_record(session, table ,&info);
    if (error)
      break;
    session->row_count++;
  }

  free_underlaid_joins(session, &session->lex->select_lex);
  joins_freed= true;

  /*
    Now all rows are inserted.  Time to update logs and sends response to
    user
  */
  {
    /*
      Do not do this release if this is a delayed insert, it would steal
      auto_inc values from the delayed_insert thread as they share Table.
    */
    table->cursor->ha_release_auto_increment();
    if (table->cursor->ha_end_bulk_insert() && !error)
    {
      table->print_error(errno,MYF(0));
      error=1;
    }
    if (duplic != DUP_ERROR || ignore)
      table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);

    transactional_table= table->cursor->has_transactions();

    changed= (info.copied || info.deleted || info.updated);
    if ((changed && error <= 0) || session->transaction.stmt.hasModifiedNonTransData())
    {
      if (session->transaction.stmt.hasModifiedNonTransData())
	session->transaction.all.markModifiedNonTransData();
    }
    assert(transactional_table || !changed || session->transaction.stmt.hasModifiedNonTransData());

  }
  session->set_proc_info("end");
  /*
    We'll report to the client this id:
    - if the table contains an autoincrement column and we successfully
    inserted an autogenerated value, the autogenerated value.
    - if the table contains no autoincrement column and LAST_INSERT_ID(X) was
    called, X.
    - if the table contains an autoincrement column, and some rows were
    inserted, the id of the last "inserted" row (if IGNORE, that value may not
    have been really inserted but ignored).
  */
  id= (session->first_successful_insert_id_in_cur_stmt > 0) ?
    session->first_successful_insert_id_in_cur_stmt :
    (session->arg_of_last_insert_id_function ?
     session->first_successful_insert_id_in_prev_stmt :
     ((table->next_number_field && info.copied) ?
     table->next_number_field->val_int() : 0));
  table->next_number_field=0;
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
  table->auto_increment_field_not_null= false;
  if (duplic == DUP_REPLACE)
    table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);

  if (error)
    goto abort;
  if (values_list.elements == 1 && (!(session->options & OPTION_WARNINGS) ||
				    !session->cuted_fields))
  {
    session->row_count_func= info.copied + info.deleted + info.updated;
    session->my_ok((ulong) session->row_count_func,
                   info.copied + info.deleted + info.touched, id);
  }
  else
  {
    char buff[160];
    if (ignore)
      snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
              (ulong) (info.records - info.copied), (ulong) session->cuted_fields);
    else
      snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
	      (ulong) (info.deleted + info.updated), (ulong) session->cuted_fields);
    session->row_count_func= info.copied + info.deleted + info.updated;
    session->my_ok((ulong) session->row_count_func,
                   info.copied + info.deleted + info.touched, id, buff);
  }
  session->abort_on_warning= 0;
  DRIZZLE_INSERT_DONE(0, session->row_count_func);
  return false;

abort:
  if (table != NULL)
    table->cursor->ha_release_auto_increment();
  if (!joins_freed)
    free_underlaid_joins(session, &session->lex->select_lex);
  session->abort_on_warning= 0;
  DRIZZLE_INSERT_DONE(1, 0);
  return true;
}


/*
  Check if table can be updated

  SYNOPSIS
     mysql_prepare_insert_check_table()
     session		Thread handle
     table_list		Table list
     fields		List of fields to be updated
     where		Pointer to where clause
     select_insert      Check is making for SELECT ... INSERT

   RETURN
     false ok
     true  ERROR
*/

static bool mysql_prepare_insert_check_table(Session *session, TableList *table_list,
                                             List<Item> &,
                                             bool select_insert)
{


  /*
     first table in list is the one we'll INSERT into, requires INSERT_ACL.
     all others require SELECT_ACL only. the ACL requirement below is for
     new leaves only anyway (view-constituents), so check for SELECT rather
     than INSERT.
  */

  if (setup_tables_and_check_access(session, &session->lex->select_lex.context,
                                    &session->lex->select_lex.top_join_list,
                                    table_list,
                                    &session->lex->select_lex.leaf_tables,
                                    select_insert))
    return(true);

  return(false);
}


/*
  Prepare items in INSERT statement

  SYNOPSIS
    mysql_prepare_insert()
    session			Thread handler
    table_list	        Global/local table list
    table		Table to insert into (can be NULL if table should
			be taken from table_list->table)
    where		Where clause (for insert ... select)
    select_insert	true if INSERT ... SELECT statement
    check_fields        true if need to check that all INSERT fields are
                        given values.
    abort_on_warning    whether to report if some INSERT field is not
                        assigned as an error (true) or as a warning (false).

  TODO (in far future)
    In cases of:
    INSERT INTO t1 SELECT a, sum(a) as sum1 from t2 GROUP BY a
    ON DUPLICATE KEY ...
    we should be able to refer to sum1 in the ON DUPLICATE KEY part

  WARNING
    You MUST set table->insert_values to 0 after calling this function
    before releasing the table object.

  RETURN VALUE
    false OK
    true  error
*/

bool mysql_prepare_insert(Session *session, TableList *table_list,
                          Table *table, List<Item> &fields, List_item *values,
                          List<Item> &update_fields, List<Item> &update_values,
                          enum_duplicates duplic,
                          COND **,
                          bool select_insert,
                          bool check_fields, bool abort_on_warning)
{
  Select_Lex *select_lex= &session->lex->select_lex;
  Name_resolution_context *context= &select_lex->context;
  Name_resolution_context_state ctx_state;
  bool insert_into_view= (0 != 0);
  bool res= 0;
  table_map map= 0;

  /* INSERT should have a SELECT or VALUES clause */
  assert (!select_insert || !values);

  /*
    For subqueries in VALUES() we should not see the table in which we are
    inserting (for INSERT ... SELECT this is done by changing table_list,
    because INSERT ... SELECT share Select_Lex it with SELECT.
  */
  if (!select_insert)
  {
    for (Select_Lex_Unit *un= select_lex->first_inner_unit();
         un;
         un= un->next_unit())
    {
      for (Select_Lex *sl= un->first_select();
           sl;
           sl= sl->next_select())
      {
        sl->context.outer_context= 0;
      }
    }
  }

  if (duplic == DUP_UPDATE)
  {
    /* it should be allocated before Item::fix_fields() */
    if (table_list->set_insert_values(session->mem_root))
      return(true);
  }

  if (mysql_prepare_insert_check_table(session, table_list, fields, select_insert))
    return(true);


  /* Prepare the fields in the statement. */
  if (values)
  {
    /* if we have INSERT ... VALUES () we cannot have a GROUP BY clause */
    assert (!select_lex->group_list.elements);

    /* 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);

    res= check_insert_fields(session, context->table_list, fields, *values,
                             !insert_into_view, &map) ||
      setup_fields(session, 0, *values, MARK_COLUMNS_READ, 0, 0);

    if (!res && check_fields)
    {
      bool saved_abort_on_warning= session->abort_on_warning;
      session->abort_on_warning= abort_on_warning;
      res= check_that_all_fields_are_given_values(session,
                                                  table ? table :
                                                  context->table_list->table,
                                                  context->table_list);
      session->abort_on_warning= saved_abort_on_warning;
    }

    if (!res && duplic == DUP_UPDATE)
    {
      res= check_update_fields(session, context->table_list, update_fields, &map);
    }

    /* Restore the current context. */
    ctx_state.restore_state(context, table_list);

    if (!res)
      res= setup_fields(session, 0, update_values, MARK_COLUMNS_READ, 0, 0);
  }

  if (res)
    return(res);

  if (!table)
    table= table_list->table;

  if (!select_insert)
  {
    TableList *duplicate;
    if ((duplicate= unique_table(table_list, table_list->next_global, true)))
    {
      my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->alias);

      return true;
    }
  }
  if (duplic == DUP_UPDATE || duplic == DUP_REPLACE)
    table->prepare_for_position();

  return false;
}


	/* Check if there is more uniq keys after field */

static int last_uniq_key(Table *table,uint32_t keynr)
{
  while (++keynr < table->s->keys)
    if (table->key_info[keynr].flags & HA_NOSAME)
      return 0;
  return 1;
}


/*
  Write a record to table with optional deleting of conflicting records,
  invoke proper triggers if needed.

  SYNOPSIS
     write_record()
      session   - thread context
      table - table to which record should be written
      info  - COPY_INFO structure describing handling of duplicates
              and which is used for counting number of records inserted
              and deleted.

  NOTE
    Once this record will be written to table after insert trigger will
    be invoked. If instead of inserting new record we will update old one
    then both on update triggers will work instead. Similarly both on
    delete triggers will be invoked if we will delete conflicting records.

    Sets session->transaction.stmt.modified_non_trans_data to true if table which is updated didn't have
    transactions.

  RETURN VALUE
    0     - success
    non-0 - error
*/


int write_record(Session *session, Table *table,COPY_INFO *info)
{
  int error;
  char *key=0;
  MyBitmap *save_read_set, *save_write_set;
  uint64_t prev_insert_id= table->cursor->next_insert_id;
  uint64_t insert_id_for_cur_row= 0;


  info->records++;
  save_read_set=  table->read_set;
  save_write_set= table->write_set;

  if (info->handle_duplicates == DUP_REPLACE || info->handle_duplicates == DUP_UPDATE)
  {
    while ((error=table->cursor->ha_write_row(table->record[0])))
    {
      uint32_t key_nr;
      /*
        If we do more than one iteration of this loop, from the second one the
        row will have an explicit value in the autoinc field, which was set at
        the first call of handler::update_auto_increment(). So we must save
        the autogenerated value to avoid session->insert_id_for_cur_row to become
        0.
      */
      if (table->cursor->insert_id_for_cur_row > 0)
        insert_id_for_cur_row= table->cursor->insert_id_for_cur_row;
      else
        table->cursor->insert_id_for_cur_row= insert_id_for_cur_row;
      bool is_duplicate_key_error;
      if (table->cursor->is_fatal_error(error, HA_CHECK_DUP))
	goto err;
      is_duplicate_key_error= table->cursor->is_fatal_error(error, 0);
      if (!is_duplicate_key_error)
      {
        /*
          We come here when we had an ignorable error which is not a duplicate
          key error. In this we ignore error if ignore flag is set, otherwise
          report error as usual. We will not do any duplicate key processing.
        */
        if (info->ignore)
          goto gok_or_after_err; /* Ignoring a not fatal error, return 0 */
        goto err;
      }
      if ((int) (key_nr = table->get_dup_key(error)) < 0)
      {
	error= HA_ERR_FOUND_DUPP_KEY;         /* Database can't find key */
	goto err;
      }
      /* Read all columns for the row we are going to replace */
      table->use_all_columns();
      /*
	Don't allow REPLACE to replace a row when a auto_increment column
	was used.  This ensures that we don't get a problem when the
	whole range of the key has been used.
      */
      if (info->handle_duplicates == DUP_REPLACE &&
          table->next_number_field &&
          key_nr == table->s->next_number_index &&
	  (insert_id_for_cur_row > 0))
	goto err;
      if (table->cursor->getEngine()->check_flag(HTON_BIT_DUPLICATE_POS))
      {
	if (table->cursor->rnd_pos(table->record[1],table->cursor->dup_ref))
	  goto err;
      }
      else
      {
	if (table->cursor->extra(HA_EXTRA_FLUSH_CACHE)) /* Not needed with NISAM */
	{
	  error=errno;
	  goto err;
	}

	if (!key)
	{
	  if (!(key=(char*) malloc(table->s->max_unique_length)))
	  {
	    error=ENOMEM;
	    goto err;
	  }
	}
	key_copy((unsigned char*) key,table->record[0],table->key_info+key_nr,0);
	if ((error=(table->cursor->index_read_idx_map(table->record[1],key_nr,
                                                    (unsigned char*) key, HA_WHOLE_KEY,
                                                    HA_READ_KEY_EXACT))))
	  goto err;
      }
      if (info->handle_duplicates == DUP_UPDATE)
      {
        /*
          We don't check for other UNIQUE keys - the first row
          that matches, is updated. If update causes a conflict again,
          an error is returned
        */
	assert(table->insert_values != NULL);
        table->storeRecordAsInsert();
        table->restoreRecord();
        assert(info->update_fields->elements ==
                    info->update_values->elements);
        if (fill_record(session, *info->update_fields,
                                                 *info->update_values,
                                                 info->ignore))
          goto before_err;

        table->cursor->restore_auto_increment(prev_insert_id);
        if (table->next_number_field)
          table->cursor->adjust_next_insert_id_after_explicit_value(
            table->next_number_field->val_int());
        info->touched++;
        if ((table->cursor->getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) &&
             !bitmap_is_subset(table->write_set, table->read_set)) ||
            table->compare_record())
        {
          if ((error=table->cursor->ha_update_row(table->record[1],
                                                table->record[0])) &&
              error != HA_ERR_RECORD_IS_THE_SAME)
          {
            if (info->ignore &&
                !table->cursor->is_fatal_error(error, HA_CHECK_DUP_KEY))
            {
              goto gok_or_after_err;
            }
            goto err;
          }

          if (error != HA_ERR_RECORD_IS_THE_SAME)
            info->updated++;
          else
            error= 0;
          /*
            If ON DUP KEY UPDATE updates a row instead of inserting one, it's
            like a regular UPDATE statement: it should not affect the value of a
            next SELECT LAST_INSERT_ID() or mysql_insert_id().
            Except if LAST_INSERT_ID(#) was in the INSERT query, which is
            handled separately by Session::arg_of_last_insert_id_function.
          */
          insert_id_for_cur_row= table->cursor->insert_id_for_cur_row= 0;
          info->copied++;
        }

        if (table->next_number_field)
          table->cursor->adjust_next_insert_id_after_explicit_value(
            table->next_number_field->val_int());
        info->touched++;

        goto gok_or_after_err;
      }
      else /* DUP_REPLACE */
      {
	/*
	  The manual defines the REPLACE semantics that it is either
	  an INSERT or DELETE(s) + INSERT; FOREIGN KEY checks in
	  InnoDB do not function in the defined way if we allow MySQL
	  to convert the latter operation internally to an UPDATE.
          We also should not perform this conversion if we have
          timestamp field with ON UPDATE which is different from DEFAULT.
          Another case when conversion should not be performed is when
          we have ON DELETE trigger on table so user may notice that
          we cheat here. Note that it is ok to do such conversion for
          tables which have ON UPDATE but have no ON DELETE triggers,
          we just should not expose this fact to users by invoking
          ON UPDATE triggers.
	*/
	if (last_uniq_key(table,key_nr) &&
	    !table->cursor->referenced_by_foreign_key() &&
            (table->timestamp_field_type == TIMESTAMP_NO_AUTO_SET ||
             table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH))
        {
          if ((error=table->cursor->ha_update_row(table->record[1],
					        table->record[0])) &&
              error != HA_ERR_RECORD_IS_THE_SAME)
            goto err;
          if (error != HA_ERR_RECORD_IS_THE_SAME)
            info->deleted++;
          else
            error= 0;
          session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
          /*
            Since we pretend that we have done insert we should call
            its after triggers.
          */
          goto after_n_copied_inc;
        }
        else
        {
          if ((error=table->cursor->ha_delete_row(table->record[1])))
            goto err;
          info->deleted++;
          if (!table->cursor->has_transactions())
            session->transaction.stmt.markModifiedNonTransData();
          /* Let us attempt do write_row() once more */
        }
      }
    }
    session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
    /*
      Restore column maps if they where replaced during an duplicate key
      problem.
    */
    if (table->read_set != save_read_set ||
        table->write_set != save_write_set)
      table->column_bitmaps_set(save_read_set, save_write_set);
  }
  else if ((error=table->cursor->ha_write_row(table->record[0])))
  {
    if (!info->ignore ||
        table->cursor->is_fatal_error(error, HA_CHECK_DUP))
      goto err;
    table->cursor->restore_auto_increment(prev_insert_id);
    goto gok_or_after_err;
  }

after_n_copied_inc:
  info->copied++;
  session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);

gok_or_after_err:
  if (key)
    free(key);
  if (!table->cursor->has_transactions())
    session->transaction.stmt.markModifiedNonTransData();
  return(0);

err:
  info->last_errno= error;
  /* current_select is NULL if this is a delayed insert */
  if (session->lex->current_select)
    session->lex->current_select->no_error= 0;        // Give error
  table->print_error(error,MYF(0));

before_err:
  table->cursor->restore_auto_increment(prev_insert_id);
  if (key)
    free(key);
  table->column_bitmaps_set(save_read_set, save_write_set);
  return(1);
}


/******************************************************************************
  Check that all fields with arn't null_fields are used
******************************************************************************/

int check_that_all_fields_are_given_values(Session *session, Table *entry,
                                           TableList *)
{
  int err= 0;

  for (Field **field=entry->field ; *field ; field++)
  {
    if (((*field)->isWriteSet()) == false)
    {
      /*
       * If the field doesn't have any default value
       * and there is no actual value specified in the
       * INSERT statement, throw error ER_NO_DEFAULT_FOR_FIELD.
       */
      if (((*field)->flags & NO_DEFAULT_VALUE_FLAG) &&
        ((*field)->real_type() != DRIZZLE_TYPE_ENUM))
      {
        my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), (*field)->field_name);
        err= 1;
      }
    }
    else
    {
      /*
       * However, if an actual NULL value was specified
       * for the field and the field is a NOT NULL field, 
       * throw ER_BAD_NULL_ERROR.
       *
       * Per the SQL standard, inserting NULL into a NOT NULL
       * field requires an error to be thrown.
       */
      if (((*field)->flags & NOT_NULL_FLAG) &&
          (*field)->is_null())
      {
        my_error(ER_BAD_NULL_ERROR, MYF(0), (*field)->field_name);
        err= 1;
      }
    }
  }
  return session->abort_on_warning ? err : 0;
}

/***************************************************************************
  Store records in INSERT ... SELECT *
***************************************************************************/


/*
  make insert specific preparation and checks after opening tables

  SYNOPSIS
    mysql_insert_select_prepare()
    session         thread handler

  RETURN
    false OK
    true  Error
*/

bool mysql_insert_select_prepare(Session *session)
{
  LEX *lex= session->lex;
  Select_Lex *select_lex= &lex->select_lex;

  /*
    Select_Lex do not belong to INSERT statement, so we can't add WHERE
    clause if table is VIEW
  */

  if (mysql_prepare_insert(session, lex->query_tables,
                           lex->query_tables->table, lex->field_list, 0,
                           lex->update_list, lex->value_list,
                           lex->duplicates,
                           &select_lex->where, true, false, false))
    return(true);

  /*
    exclude first table from leaf tables list, because it belong to
    INSERT
  */
  assert(select_lex->leaf_tables != 0);
  lex->leaf_tables_insert= select_lex->leaf_tables;
  /* skip all leaf tables belonged to view where we are insert */
  select_lex->leaf_tables= select_lex->leaf_tables->next_leaf;
  return(false);
}


select_insert::select_insert(TableList *table_list_par, Table *table_par,
                             List<Item> *fields_par,
                             List<Item> *update_fields,
                             List<Item> *update_values,
                             enum_duplicates duplic,
                             bool ignore_check_option_errors)
  :table_list(table_list_par), table(table_par), fields(fields_par),
   autoinc_value_of_last_inserted_row(0),
   insert_into_view(table_list_par && 0 != 0)
{
  memset(&info, 0, sizeof(info));
  info.handle_duplicates= duplic;
  info.ignore= ignore_check_option_errors;
  info.update_fields= update_fields;
  info.update_values= update_values;
}


int
select_insert::prepare(List<Item> &values, Select_Lex_Unit *u)
{
  LEX *lex= session->lex;
  int res;
  table_map map= 0;
  Select_Lex *lex_current_select_save= lex->current_select;


  unit= u;

  /*
    Since table in which we are going to insert is added to the first
    select, LEX::current_select should point to the first select while
    we are fixing fields from insert list.
  */
  lex->current_select= &lex->select_lex;
  res= check_insert_fields(session, table_list, *fields, values,
                           !insert_into_view, &map) ||
       setup_fields(session, 0, values, MARK_COLUMNS_READ, 0, 0);

  if (!res && fields->elements)
  {
    bool saved_abort_on_warning= session->abort_on_warning;
    session->abort_on_warning= !info.ignore;
    res= check_that_all_fields_are_given_values(session, table_list->table,
                                                table_list);
    session->abort_on_warning= saved_abort_on_warning;
  }

  if (info.handle_duplicates == DUP_UPDATE && !res)
  {
    Name_resolution_context *context= &lex->select_lex.context;
    Name_resolution_context_state ctx_state;

    /* 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'. */
    table_list->next_local= 0;
    context->resolve_in_table_list_only(table_list);

    res= res || check_update_fields(session, context->table_list,
                                    *info.update_fields, &map);
    /*
      When we are not using GROUP BY and there are no ungrouped aggregate functions
      we can refer to other tables in the ON DUPLICATE KEY part.
      We use next_name_resolution_table descructively, so check it first (views?)
    */
    assert (!table_list->next_name_resolution_table);
    if (lex->select_lex.group_list.elements == 0 &&
        !lex->select_lex.with_sum_func)
      /*
        We must make a single context out of the two separate name resolution contexts :
        the INSERT table and the tables in the SELECT part of INSERT ... SELECT.
        To do that we must concatenate the two lists
      */
      table_list->next_name_resolution_table=
        ctx_state.get_first_name_resolution_table();

    res= res || setup_fields(session, 0, *info.update_values,
                             MARK_COLUMNS_READ, 0, 0);
    if (!res)
    {
      /*
        Traverse the update values list and substitute fields from the
        select for references (Item_ref objects) to them. This is done in
        order to get correct values from those fields when the select
        employs a temporary table.
      */
      List_iterator<Item> li(*info.update_values);
      Item *item;

      while ((item= li++))
      {
        item->transform(&Item::update_value_transformer,
                        (unsigned char*)lex->current_select);
      }
    }

    /* Restore the current context. */
    ctx_state.restore_state(context, table_list);
  }

  lex->current_select= lex_current_select_save;
  if (res)
    return(1);
  /*
    if it is INSERT into join view then check_insert_fields already found
    real table for insert
  */
  table= table_list->table;

  /*
    Is table which we are changing used somewhere in other parts of
    query
  */
  if (unique_table(table_list, table_list->next_global))
  {
    /* Using same table for INSERT and SELECT */
    lex->current_select->options|= OPTION_BUFFER_RESULT;
    lex->current_select->join->select_options|= OPTION_BUFFER_RESULT;
  }
  else if (!(lex->current_select->options & OPTION_BUFFER_RESULT))
  {
    /*
      We must not yet prepare the result table if it is the same as one of the
      source tables (INSERT SELECT). The preparation may disable
      indexes on the result table, which may be used during the select, if it
      is the same table (Bug #6034). Do the preparation after the select phase
      in select_insert::prepare2().
      We won't start bulk inserts at all if this statement uses functions or
      should invoke triggers since they may access to the same table too.
    */
    table->cursor->ha_start_bulk_insert((ha_rows) 0);
  }
  table->restoreRecordAsDefault();		// Get empty record
  table->next_number_field=table->found_next_number_field;

  session->cuted_fields=0;
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
    table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
  if (info.handle_duplicates == DUP_REPLACE)
    table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
  if (info.handle_duplicates == DUP_UPDATE)
    table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
  session->abort_on_warning= !info.ignore;
  table->mark_columns_needed_for_insert();


  return(res);
}


/*
  Finish the preparation of the result table.

  SYNOPSIS
    select_insert::prepare2()
    void

  DESCRIPTION
    If the result table is the same as one of the source tables (INSERT SELECT),
    the result table is not finally prepared at the join prepair phase.
    Do the final preparation now.

  RETURN
    0   OK
*/

int select_insert::prepare2(void)
{

  if (session->lex->current_select->options & OPTION_BUFFER_RESULT)
    table->cursor->ha_start_bulk_insert((ha_rows) 0);
  return(0);
}


void select_insert::cleanup()
{
  /* select_insert/select_create are never re-used in prepared statement */
  assert(0);
}

select_insert::~select_insert()
{

  if (table)
  {
    table->next_number_field=0;
    table->auto_increment_field_not_null= false;
    table->cursor->ha_reset();
  }
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
  session->abort_on_warning= 0;
  return;
}


bool select_insert::send_data(List<Item> &values)
{

  bool error=0;

  if (unit->offset_limit_cnt)
  {						// using limit offset,count
    unit->offset_limit_cnt--;
    return(0);
  }

  session->count_cuted_fields= CHECK_FIELD_WARN;	// Calculate cuted fields
  store_values(values);
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
  if (session->is_error())
    return(1);

  // Release latches in case bulk insert takes a long time
  plugin::TransactionalStorageEngine::releaseTemporaryLatches(session);

  error= write_record(session, table, &info);

  if (!error)
  {
    if (info.handle_duplicates == DUP_UPDATE)
    {
      /*
        Restore fields of the record since it is possible that they were
        changed by ON DUPLICATE KEY UPDATE clause.

        If triggers exist then whey can modify some fields which were not
        originally touched by INSERT ... SELECT, so we have to restore
        their original values for the next row.
      */
      table->restoreRecordAsDefault();
    }
    if (table->next_number_field)
    {
      /*
        If no value has been autogenerated so far, we need to remember the
        value we just saw, we may need to send it to client in the end.
      */
      if (session->first_successful_insert_id_in_cur_stmt == 0) // optimization
        autoinc_value_of_last_inserted_row=
          table->next_number_field->val_int();
      /*
        Clear auto-increment field for the next record, if triggers are used
        we will clear it twice, but this should be cheap.
      */
      table->next_number_field->reset();
    }
  }
  return(error);
}


void select_insert::store_values(List<Item> &values)
{
  if (fields->elements)
    fill_record(session, *fields, values, true);
  else
    fill_record(session, table->field, values, true);
}

void select_insert::send_error(uint32_t errcode,const char *err)
{


  my_message(errcode, err, MYF(0));

  return;
}


bool select_insert::send_eof()
{
  int error;
  bool const trans_table= table->cursor->has_transactions();
  uint64_t id;
  bool changed;

  error= table->cursor->ha_end_bulk_insert();
  table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
  table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);

  if ((changed= (info.copied || info.deleted || info.updated)))
  {
    /*
      We must invalidate the table in the query cache before binlog writing
      and autocommitOrRollback.
    */
    if (session->transaction.stmt.hasModifiedNonTransData())
      session->transaction.all.markModifiedNonTransData();
  }
  assert(trans_table || !changed ||
              session->transaction.stmt.hasModifiedNonTransData());

  table->cursor->ha_release_auto_increment();

  if (error)
  {
    table->print_error(error,MYF(0));
    DRIZZLE_INSERT_SELECT_DONE(error, 0);
    return 1;
  }
  char buff[160];
  if (info.ignore)
    snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
	    (ulong) (info.records - info.copied), (ulong) session->cuted_fields);
  else
    snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
	    (ulong) (info.deleted+info.updated), (ulong) session->cuted_fields);
  session->row_count_func= info.copied + info.deleted + info.updated;

  id= (session->first_successful_insert_id_in_cur_stmt > 0) ?
    session->first_successful_insert_id_in_cur_stmt :
    (session->arg_of_last_insert_id_function ?
     session->first_successful_insert_id_in_prev_stmt :
     (info.copied ? autoinc_value_of_last_inserted_row : 0));
  session->my_ok((ulong) session->row_count_func,
                 info.copied + info.deleted + info.touched, id, buff);
  DRIZZLE_INSERT_SELECT_DONE(0, session->row_count_func);
  return 0;
}

void select_insert::abort() {


  /*
    If the creation of the table failed (due to a syntax error, for
    example), no table will have been opened and therefore 'table'
    will be NULL. In that case, we still need to execute the rollback
    and the end of the function.
   */
  if (table)
  {
    bool changed, transactional_table;

    table->cursor->ha_end_bulk_insert();

    /*
      If at least one row has been inserted/modified and will stay in
      the table (the table doesn't have transactions) we must write to
      the binlog (and the error code will make the slave stop).

      For many errors (example: we got a duplicate key error while
      inserting into a MyISAM table), no row will be added to the table,
      so passing the error to the slave will not help since there will
      be an error code mismatch (the inserts will succeed on the slave
      with no error).

      If table creation failed, the number of rows modified will also be
      zero, so no check for that is made.
    */
    changed= (info.copied || info.deleted || info.updated);
    transactional_table= table->cursor->has_transactions();
    assert(transactional_table || !changed ||
		session->transaction.stmt.hasModifiedNonTransData());
    table->cursor->ha_release_auto_increment();
  }

  if (DRIZZLE_INSERT_SELECT_DONE_ENABLED())
  {
    DRIZZLE_INSERT_SELECT_DONE(0, info.copied + info.deleted + info.updated);
  }

  return;
}


/***************************************************************************
  CREATE TABLE (SELECT) ...
***************************************************************************/

/*
  Create table from lists of fields and items (or just return Table
  object for pre-opened existing table).

  SYNOPSIS
    create_table_from_items()
      session          in     Thread object
      create_info  in     Create information (like MAX_ROWS, ENGINE or
                          temporary table flag)
      create_table in     Pointer to TableList object providing database
                          and name for table to be created or to be open
      alter_info   in/out Initial list of columns and indexes for the table
                          to be created
      items        in     List of items which should be used to produce rest
                          of fields for the table (corresponding fields will
                          be added to the end of alter_info->create_list)
      lock         out    Pointer to the DRIZZLE_LOCK object for table created
                          (or open temporary table) will be returned in this
                          parameter. Since this table is not included in
                          Session::lock caller is responsible for explicitly
                          unlocking this table.
      hooks

  NOTES
    This function behaves differently for base and temporary tables:
    - For base table we assume that either table exists and was pre-opened
      and locked at openTablesLock() stage (and in this case we just
      emit error or warning and return pre-opened Table object) or special
      placeholder was put in table cache that guarantees that this table
      won't be created or opened until the placeholder will be removed
      (so there is an exclusive lock on this table).
    - We don't pre-open existing temporary table, instead we either open
      or create and then open table in this function.

    Since this function contains some logic specific to CREATE TABLE ...
    SELECT it should be changed before it can be used in other contexts.

  RETURN VALUES
    non-zero  Pointer to Table object for table created or opened
    0         Error
*/

static Table *create_table_from_items(Session *session, HA_CREATE_INFO *create_info,
                                      TableList *create_table,
				      message::Table &table_proto,
                                      AlterInfo *alter_info,
                                      List<Item> *items,
                                      bool is_if_not_exists,
                                      DRIZZLE_LOCK **lock,
				      TableIdentifier &identifier)
{
  Table tmp_table;		// Used during 'CreateField()'
  TableShare share;
  Table *table= 0;
  uint32_t select_field_count= items->elements;
  /* Add selected items to field list */
  List_iterator_fast<Item> it(*items);
  Item *item;
  Field *tmp_field;
  bool not_used;

  if (not (identifier.isTmp()) && create_table->table->db_stat)
  {
    /* Table already exists and was open at openTablesLock() stage. */
    if (is_if_not_exists)
    {
      create_info->table_existed= 1;		// Mark that table existed
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
                          ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR),
                          create_table->table_name);
      return create_table->table;
    }

    my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->table_name);
    return NULL;
  }

  tmp_table.alias= 0;
  tmp_table.timestamp_field= 0;
  tmp_table.s= &share;

  tmp_table.s->db_create_options=0;
  tmp_table.s->blob_ptr_size= portable_sizeof_char_ptr;

  if (not table_proto.engine().name().compare("MyISAM"))
    tmp_table.s->db_low_byte_first= true;
  else if (not table_proto.engine().name().compare("MEMORY"))
    tmp_table.s->db_low_byte_first= true;

  tmp_table.null_row= false;
  tmp_table.maybe_null= false;

  while ((item=it++))
  {
    CreateField *cr_field;
    Field *field, *def_field;
    if (item->type() == Item::FUNC_ITEM)
      if (item->result_type() != STRING_RESULT)
        field= item->tmp_table_field(&tmp_table);
      else
        field= item->tmp_table_field_from_field_type(&tmp_table, 0);
    else
      field= create_tmp_field(session, &tmp_table, item, item->type(),
                              (Item ***) 0, &tmp_field, &def_field, false,
                              false, false, 0);
    if (!field ||
	!(cr_field=new CreateField(field,(item->type() == Item::FIELD_ITEM ?
					   ((Item_field *)item)->field :
					   (Field*) 0))))
      return NULL;
    if (item->maybe_null)
      cr_field->flags &= ~NOT_NULL_FLAG;
    alter_info->create_list.push_back(cr_field);
  }

  /*
    Create and lock table.

    Note that we either creating (or opening existing) temporary table or
    creating base table on which name we have exclusive lock. So code below
    should not cause deadlocks or races.
  */
  {
    if (not mysql_create_table_no_lock(session,
				       identifier,
				       create_info,
				       table_proto,
				       alter_info,
				       false,
				       select_field_count,
				       is_if_not_exists))
    {
      if (create_info->table_existed && not identifier.isTmp())
      {
        /*
          This means that someone created table underneath server
          or it was created via different mysqld front-end to the
          cluster. We don't have much options but throw an error.
        */
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->table_name);
        return NULL;
      }

      if (not identifier.isTmp())
      {
        pthread_mutex_lock(&LOCK_open); /* CREATE TABLE... has found that the table already exists for insert and is adapting to use it */
        if (session->reopen_name_locked_table(create_table, false))
        {
          quick_rm_table(*session, identifier);
        }
        else
          table= create_table->table;
        pthread_mutex_unlock(&LOCK_open);
      }
      else
      {
        if (not (table= session->openTable(create_table, (bool*) 0,
                                           DRIZZLE_OPEN_TEMPORARY_ONLY)) &&
            not create_info->table_existed)
        {
          /*
            This shouldn't happen as creation of temporary table should make
            it preparable for open. But let us do close_temporary_table() here
            just in case.
          */
          session->drop_temporary_table(create_table);
        }
      }
    }
    if (!table)                                   // open failed
      return NULL;
  }

  table->reginfo.lock_type=TL_WRITE;
  if (! ((*lock)= mysql_lock_tables(session, &table, 1,
                                    DRIZZLE_LOCK_IGNORE_FLUSH, &not_used)))
  {
    if (*lock)
    {
      mysql_unlock_tables(session, *lock);
      *lock= 0;
    }

    if (not create_info->table_existed)
      session->drop_open_table(table, identifier);
    return NULL;
  }

  return table;
}


int
select_create::prepare(List<Item> &values, Select_Lex_Unit *u)
{
  DRIZZLE_LOCK *extra_lock= NULL;
  /*
    For replication, the CREATE-SELECT statement is written
    in two pieces: the first transaction messsage contains 
    the CREATE TABLE statement as a CreateTableStatement message
    necessary to create the table.
    
    The second transaction message contains all the InsertStatement
    and associated InsertRecords that should go into the table.
   */

  unit= u;

  if (not (table= create_table_from_items(session, create_info, create_table,
					  table_proto,
					  alter_info, &values,
					  is_if_not_exists,
					  &extra_lock, identifier)))
    return(-1);				// abort() deletes table

  if (extra_lock)
  {
    assert(m_plock == NULL);

    if (identifier.isTmp())
      m_plock= &m_lock;
    else
      m_plock= &session->extra_lock;

    *m_plock= extra_lock;
  }

  if (table->s->fields < values.elements)
  {
    my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1);
    return(-1);
  }

 /* First field to copy */
  field= table->field+table->s->fields - values.elements;

  /* Mark all fields that are given values */
  for (Field **f= field ; *f ; f++)
    table->setWriteSet((*f)->field_index);

  /* Don't set timestamp if used */
  table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
  table->next_number_field=table->found_next_number_field;

  table->restoreRecordAsDefault();      // Get empty record
  session->cuted_fields=0;
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
    table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
  if (info.handle_duplicates == DUP_REPLACE)
    table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
  if (info.handle_duplicates == DUP_UPDATE)
    table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
  table->cursor->ha_start_bulk_insert((ha_rows) 0);
  session->abort_on_warning= !info.ignore;
  if (check_that_all_fields_are_given_values(session, table, table_list))
    return(1);
  table->mark_columns_needed_for_insert();
  table->cursor->extra(HA_EXTRA_WRITE_CACHE);
  return(0);
}

void select_create::store_values(List<Item> &values)
{
  fill_record(session, field, values, true);
}


void select_create::send_error(uint32_t errcode,const char *err)
{
  /*
    This will execute any rollbacks that are necessary before writing
    the transcation cache.

    We disable the binary log since nothing should be written to the
    binary log.  This disabling is important, since we potentially do
    a "roll back" of non-transactional tables by removing the table,
    and the actual rollback might generate events that should not be
    written to the binary log.

  */
  select_insert::send_error(errcode, err);

  return;
}


bool select_create::send_eof()
{
  bool tmp=select_insert::send_eof();
  if (tmp)
    abort();
  else
  {
    /*
      Do an implicit commit at end of statement for non-temporary
      tables.  This can fail, but we should unlock the table
      nevertheless.
    */
    if (!table->s->tmp_table)
    {
      TransactionServices &transaction_services= TransactionServices::singleton();
      transaction_services.autocommitOrRollback(session, 0);
      (void) session->endActiveTransaction();
    }

    table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
    table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
    if (m_plock)
    {
      mysql_unlock_tables(session, *m_plock);
      *m_plock= NULL;
      m_plock= NULL;
    }
  }
  return tmp;
}


void select_create::abort()
{
  /*
    In select_insert::abort() we roll back the statement, including
    truncating the transaction cache of the binary log. To do this, we
    pretend that the statement is transactional, even though it might
    be the case that it was not.

    We roll back the statement prior to deleting the table and prior
    to releasing the lock on the table, since there might be potential
    for failure if the rollback is executed after the drop or after
    unlocking the table.

    We also roll back the statement regardless of whether the creation
    of the table succeeded or not, since we need to reset the binary
    log state.
  */
  select_insert::abort();

  if (m_plock)
  {
    mysql_unlock_tables(session, *m_plock);
    *m_plock= NULL;
    m_plock= NULL;
  }

  if (table)
  {
    table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
    table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
    if (not create_info->table_existed)
      session->drop_open_table(table, identifier);
    table= NULL;                                    // Safety
  }
}

} /* namespace drizzled */