~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000-2006 MySQL AB
2
3
   This program is free software; you can redistribute it and/or modify
4
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6
7
   This program is distributed in the hope that it will be useful,
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
   GNU General Public License for more details.
11
12
   You should have received a copy of the GNU General Public License
13
   along with this program; if not, write to the Free Software
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
16
17
/*
18
  Functions to create a unireg form-file from a FIELD and a fieldname-fieldinfo
19
  struct.
20
  In the following functions FIELD * is an ordinary field-structure with
21
  the following exeptions:
22
    sc_length,typepos,row,kol,dtype,regnr and field need not to be set.
23
    str is a (long) to record position where 0 is the first position.
24
*/
25
26
#include "mysql_priv.h"
27
#include <m_ctype.h>
28
#include <assert.h>
29
30
#define FCOMP			17		/* Bytes for a packed field */
31
32
static uchar * pack_screens(List<Create_field> &create_fields,
33
			    uint *info_length, uint *screens, bool small_file);
34
static uint pack_keys(uchar *keybuff,uint key_count, KEY *key_info,
35
                      ulong data_offset);
36
static bool pack_header(uchar *forminfo,enum legacy_db_type table_type,
37
			List<Create_field> &create_fields,
38
			uint info_length, uint screens, uint table_options,
39
			ulong data_offset, handler *file);
40
static uint get_interval_id(uint *int_count,List<Create_field> &create_fields,
41
			    Create_field *last_field);
42
static bool pack_fields(File file, List<Create_field> &create_fields,
43
                        ulong data_offset);
44
static bool make_empty_rec(THD *thd, int file, enum legacy_db_type table_type,
45
			   uint table_options,
46
			   List<Create_field> &create_fields,
47
			   uint reclength, ulong data_offset,
48
                           handler *handler);
49
50
/**
51
  An interceptor to hijack ER_TOO_MANY_FIELDS error from
52
  pack_screens and retry again without UNIREG screens.
53
54
  XXX: what is a UNIREG  screen?
55
*/
56
57
struct Pack_header_error_handler: public Internal_error_handler
58
{
59
  virtual bool handle_error(uint sql_errno,
60
                            const char *message,
61
                            MYSQL_ERROR::enum_warning_level level,
62
                            THD *thd);
63
  bool is_handled;
64
  Pack_header_error_handler() :is_handled(FALSE) {}
65
};
66
67
68
bool
69
Pack_header_error_handler::
70
handle_error(uint sql_errno,
71
             const char * /* message */,
72
             MYSQL_ERROR::enum_warning_level /* level */,
73
             THD * /* thd */)
74
{
75
  is_handled= (sql_errno == ER_TOO_MANY_FIELDS);
76
  return is_handled;
77
}
78
79
/*
80
  Create a frm (table definition) file
81
82
  SYNOPSIS
83
    mysql_create_frm()
84
    thd			Thread handler
85
    file_name		Path for file (including database and .frm)
86
    db                  Name of database
87
    table               Name of table
88
    create_info		create info parameters
89
    create_fields	Fields to create
90
    keys		number of keys to create
91
    key_info		Keys to create
92
    db_file		Handler to use. May be zero, in which case we use
93
			create_info->db_type
94
  RETURN
95
    0  ok
96
    1  error
97
*/
98
99
bool mysql_create_frm(THD *thd, const char *file_name,
100
                      const char *db, const char *table,
101
		      HA_CREATE_INFO *create_info,
102
		      List<Create_field> &create_fields,
103
		      uint keys, KEY *key_info,
104
		      handler *db_file)
105
{
106
  LEX_STRING str_db_type;
107
  uint reclength, info_length, screens, key_info_length, maxlength, tmp_len;
108
  ulong key_buff_length;
109
  File file;
110
  ulong filepos, data_offset;
111
  uchar fileinfo[64],forminfo[288],*keybuff;
112
  TYPELIB formnames;
113
  uchar *screen_buff;
114
  char buff[128];
115
  const uint format_section_header_size= 8;
116
  uint format_section_len;
117
  Pack_header_error_handler pack_header_error_handler;
118
  int error;
119
51.2.2 by Patrick Galbraith
Removed DBUGs from
120
  assert(*fn_rext((char*)file_name)); // Check .frm extension
1 by brian
clean slate
121
  formnames.type_names=0;
122
  if (!(screen_buff=pack_screens(create_fields,&info_length,&screens,0)))
51.2.2 by Patrick Galbraith
Removed DBUGs from
123
    return(1);
124
  assert(db_file != NULL);
1 by brian
clean slate
125
126
 /* If fixed row records, we need one bit to check for deleted rows */
127
  if (!(create_info->table_options & HA_OPTION_PACK_RECORD))
128
    create_info->null_bits++;
129
  data_offset= (create_info->null_bits + 7) / 8;
130
131
  thd->push_internal_handler(&pack_header_error_handler);
132
133
  error= pack_header(forminfo, ha_legacy_type(create_info->db_type),
134
                     create_fields,info_length,
135
                     screens, create_info->table_options,
136
                     data_offset, db_file);
137
138
  thd->pop_internal_handler();
139
140
  if (error)
141
  {
142
    my_free(screen_buff, MYF(0));
143
    if (! pack_header_error_handler.is_handled)
51.2.2 by Patrick Galbraith
Removed DBUGs from
144
      return(1);
1 by brian
clean slate
145
146
    // Try again without UNIREG screens (to get more columns)
147
    if (!(screen_buff=pack_screens(create_fields,&info_length,&screens,1)))
51.2.2 by Patrick Galbraith
Removed DBUGs from
148
      return(1);
1 by brian
clean slate
149
    if (pack_header(forminfo, ha_legacy_type(create_info->db_type),
150
                    create_fields,info_length,
151
		    screens, create_info->table_options, data_offset, db_file))
152
    {
153
      my_free(screen_buff, MYF(0));
51.2.2 by Patrick Galbraith
Removed DBUGs from
154
      return(1);
1 by brian
clean slate
155
    }
156
  }
157
  reclength=uint2korr(forminfo+266);
158
159
  /* Calculate extra data segment length */
160
  str_db_type.str= (char *) ha_resolve_storage_engine_name(create_info->db_type);
161
  str_db_type.length= strlen(str_db_type.str);
162
  /* str_db_type */
163
  create_info->extra_size= (2 + str_db_type.length +
164
                            2 + create_info->connect_string.length);
165
  /*
166
    Partition:
167
      Length of partition info = 4 byte
168
      Potential NULL byte at end of partition info string = 1 byte
169
      Indicator if auto-partitioned table = 1 byte
170
      => Total 6 byte
171
  */
172
  create_info->extra_size+= 6;
173
174
  /* Add space for storage type and field format array of fields */
175
  format_section_len=
106 by Brian Aker
Tablespace removal.
176
    format_section_header_size + 1 + create_fields.elements;
1 by brian
clean slate
177
  create_info->extra_size+= format_section_len;
178
179
  tmp_len= system_charset_info->cset->charpos(system_charset_info,
180
                                              create_info->comment.str,
181
                                              create_info->comment.str +
182
                                              create_info->comment.length, 
183
                                              TABLE_COMMENT_MAXLEN);
184
185
  if (tmp_len < create_info->comment.length)
186
  {
187
    my_error(ER_WRONG_STRING_LENGTH, MYF(0),
188
             create_info->comment.str,"TABLE COMMENT",
189
             (uint) TABLE_COMMENT_MAXLEN);
190
    my_free(screen_buff,MYF(0));
51.2.2 by Patrick Galbraith
Removed DBUGs from
191
    return(1);
1 by brian
clean slate
192
  }
193
194
  //if table comment is larger than 180 bytes, store into extra segment.
195
  if (create_info->comment.length > 180)
196
  {
197
    forminfo[46]=255;
198
    create_info->extra_size+= 2 + create_info->comment.length;
199
  }
200
  else{
201
    strmake((char*) forminfo+47, create_info->comment.str ?
202
            create_info->comment.str : "", create_info->comment.length);
203
    forminfo[46]=(uchar) create_info->comment.length;
204
#ifdef EXTRA_DEBUG
205
    /*
206
      EXTRA_DEBUG causes strmake() to initialize its buffer behind the
207
      payload with a magic value to detect wrong buffer-sizes. We
208
      explicitly zero that segment again.
209
    */
210
    memset((char*) forminfo+47 + forminfo[46], 0, 61 - forminfo[46]);
211
#endif
212
  }
213
214
  if ((file=create_frm(thd, file_name, db, table, reclength, fileinfo,
215
		       create_info, keys, key_info)) < 0)
216
  {
217
    my_free(screen_buff, MYF(0));
51.2.2 by Patrick Galbraith
Removed DBUGs from
218
    return(1);
1 by brian
clean slate
219
  }
220
221
  key_buff_length= uint4korr(fileinfo+47);
222
  keybuff=(uchar*) my_malloc(key_buff_length, MYF(0));
223
  key_info_length= pack_keys(keybuff, keys, key_info, data_offset);
224
  VOID(get_form_pos(file,fileinfo,&formnames));
225
  if (!(filepos=make_new_entry(file,fileinfo,&formnames,"")))
226
    goto err;
227
  maxlength=(uint) next_io_size((ulong) (uint2korr(forminfo)+1000));
228
  int2store(forminfo+2,maxlength);
229
  int4store(fileinfo+10,(ulong) (filepos+maxlength));
230
  fileinfo[26]= (uchar) test((create_info->max_rows == 1) &&
231
			     (create_info->min_rows == 1) && (keys == 0));
232
  int2store(fileinfo+28,key_info_length);
233
234
235
  int2store(fileinfo+59,db_file->extra_rec_buf_length());
236
31 by Brian Aker
Removed my versions of pread/pwrite from the Kernel
237
  if (pwrite(file, fileinfo, 64, 0L) == 0 ||
238
      pwrite(file, keybuff, key_info_length, (ulong) uint2korr(fileinfo+6)) == 0)
1 by brian
clean slate
239
    goto err;
240
  VOID(my_seek(file,
241
	       (ulong) uint2korr(fileinfo+6)+ (ulong) key_buff_length,
242
	       MY_SEEK_SET,MYF(0)));
243
  if (make_empty_rec(thd,file,ha_legacy_type(create_info->db_type),
244
                     create_info->table_options,
245
		     create_fields,reclength, data_offset, db_file))
246
    goto err;
247
248
  int2store(buff, create_info->connect_string.length);
249
  if (my_write(file, (const uchar*)buff, 2, MYF(MY_NABP)) ||
250
      my_write(file, (const uchar*)create_info->connect_string.str,
251
               create_info->connect_string.length, MYF(MY_NABP)))
252
      goto err;
253
254
  int2store(buff, str_db_type.length);
255
  if (my_write(file, (const uchar*)buff, 2, MYF(MY_NABP)) ||
256
      my_write(file, (const uchar*)str_db_type.str,
257
               str_db_type.length, MYF(MY_NABP)))
258
    goto err;
259
260
  {
261
    bzero((uchar*) buff, 6);
262
    if (my_write(file, (uchar*) buff, 6, MYF_RW))
263
      goto err;
264
  }
265
266
  if (forminfo[46] == (uchar)255)
267
  {
268
    uchar comment_length_buff[2];
269
    int2store(comment_length_buff,create_info->comment.length);
270
    if (my_write(file, comment_length_buff, 2, MYF(MY_NABP)) ||
271
        my_write(file, (uchar*)create_info->comment.str,
272
                  create_info->comment.length, MYF(MY_NABP)))
273
      goto err;
274
  }
275
276
  /* Store storage type and field format array of fields */
277
  {
278
    /* prepare header */
279
    {
280
      uint flags= 0;
281
282
      bzero(buff, format_section_header_size);
283
      /* length of section 2 bytes*/
284
      int2store(buff+0, format_section_len);
285
      /* flags of section 4 bytes*/
286
      int4store(buff+2, flags);
287
      /* 2 bytes left for future use */
288
    }
289
    /* write header */
290
    if (my_write(file, (const uchar*)buff, format_section_header_size, MYF_RW))
291
      goto err;
292
    buff[0]= 0;
293
    if (my_write(file, (const uchar*)buff, 1, MYF_RW))
294
      goto err;
295
    /* write column info, 1 byte per column */
296
    {
297
      List_iterator<Create_field> it(create_fields);
298
      Create_field *field;
101 by Brian Aker
Second pass on storage_type.
299
      uchar column_format, write_byte;
1 by brian
clean slate
300
      while ((field=it++))
301
      {
302
        column_format= (uchar)field->column_format();
101 by Brian Aker
Second pass on storage_type.
303
        write_byte= (column_format << COLUMN_FORMAT_SHIFT);
1 by brian
clean slate
304
        if (my_write(file, &write_byte, 1, MYF_RW))
305
          goto err;
306
      }
307
    }
308
  }
309
  VOID(my_seek(file,filepos,MY_SEEK_SET,MYF(0)));
310
  if (my_write(file, forminfo, 288, MYF_RW) ||
311
      my_write(file, screen_buff, info_length, MYF_RW) ||
312
      pack_fields(file, create_fields, data_offset))
313
    goto err;
314
315
  my_free(screen_buff,MYF(0));
316
  my_free(keybuff, MYF(0));
317
318
  if (opt_sync_frm && !(create_info->options & HA_LEX_CREATE_TMP_TABLE) &&
319
      (my_sync(file, MYF(MY_WME)) ||
320
       my_sync_dir_by_file(file_name, MYF(MY_WME))))
321
      goto err2;
322
323
  if (my_close(file,MYF(MY_WME)))
324
    goto err3;
325
326
  {
327
    /* 
328
      Restore all UCS2 intervals.
329
      HEX representation of them is not needed anymore.
330
    */
331
    List_iterator<Create_field> it(create_fields);
332
    Create_field *field;
333
    while ((field=it++))
334
    {
335
      if (field->save_interval)
336
      {
337
        field->interval= field->save_interval;
338
        field->save_interval= 0;
339
      }
340
    }
341
  }
51.2.2 by Patrick Galbraith
Removed DBUGs from
342
  return(0);
1 by brian
clean slate
343
344
err:
345
  my_free(screen_buff, MYF(0));
346
  my_free(keybuff, MYF(0));
347
err2:
348
  VOID(my_close(file,MYF(MY_WME)));
349
err3:
350
  my_delete(file_name,MYF(0));
51.2.2 by Patrick Galbraith
Removed DBUGs from
351
  return(1);
1 by brian
clean slate
352
} /* mysql_create_frm */
353
354
355
/*
356
  Create a frm (table definition) file and the tables
357
358
  SYNOPSIS
359
    rea_create_table()
360
    thd			Thread handler
361
    path		Name of file (including database, without .frm)
362
    db			Data base name
363
    table_name		Table name
364
    create_info		create info parameters
365
    create_fields	Fields to create
366
    keys		number of keys to create
367
    key_info		Keys to create
368
    file		Handler to use
369
370
  RETURN
371
    0  ok
372
    1  error
373
*/
374
375
int rea_create_table(THD *thd, const char *path,
376
                     const char *db, const char *table_name,
377
                     HA_CREATE_INFO *create_info,
378
                     List<Create_field> &create_fields,
379
                     uint keys, KEY *key_info, handler *file)
380
{
51.2.2 by Patrick Galbraith
Removed DBUGs from
381
  
1 by brian
clean slate
382
383
  char frm_name[FN_REFLEN];
384
  strxmov(frm_name, path, reg_ext, NullS);
385
  if (mysql_create_frm(thd, frm_name, db, table_name, create_info,
386
                       create_fields, keys, key_info, file))
387
51.2.2 by Patrick Galbraith
Removed DBUGs from
388
    return(1);
1 by brian
clean slate
389
390
  // Make sure mysql_create_frm din't remove extension
51.2.2 by Patrick Galbraith
Removed DBUGs from
391
  assert(*fn_rext(frm_name));
1 by brian
clean slate
392
  if (thd->variables.keep_files_on_create)
393
    create_info->options|= HA_CREATE_KEEP_FILES;
394
  if (file->ha_create_handler_files(path, NULL, CHF_CREATE_FLAG, create_info))
395
    goto err_handler;
396
  if (!create_info->frm_only && ha_create_table(thd, path, db, table_name,
397
                                                create_info,0))
398
    goto err_handler;
51.2.2 by Patrick Galbraith
Removed DBUGs from
399
  return(0);
1 by brian
clean slate
400
401
err_handler:
402
  VOID(file->ha_create_handler_files(path, NULL, CHF_DELETE_FLAG, create_info));
403
  my_delete(frm_name, MYF(0));
51.2.2 by Patrick Galbraith
Removed DBUGs from
404
  return(1);
1 by brian
clean slate
405
} /* rea_create_table */
406
407
408
	/* Pack screens to a screen for save in a form-file */
409
410
static uchar *pack_screens(List<Create_field> &create_fields,
411
                           uint *info_length, uint *screens,
412
                           bool small_file)
413
{
414
  register uint i;
415
  uint row,start_row,end_row,fields_on_screen;
416
  uint length,cols;
417
  uchar *info,*pos,*start_screen;
418
  uint fields=create_fields.elements;
419
  List_iterator<Create_field> it(create_fields);
51.2.2 by Patrick Galbraith
Removed DBUGs from
420
  
1 by brian
clean slate
421
422
  start_row=4; end_row=22; cols=80; fields_on_screen=end_row+1-start_row;
423
424
  *screens=(fields-1)/fields_on_screen+1;
425
  length= (*screens) * (SC_INFO_LENGTH+ (cols>> 1)+4);
426
427
  Create_field *field;
428
  while ((field=it++))
429
    length+=(uint) strlen(field->field_name)+1+TE_INFO_LENGTH+cols/2;
430
431
  if (!(info=(uchar*) my_malloc(length,MYF(MY_WME))))
51.2.2 by Patrick Galbraith
Removed DBUGs from
432
    return(0);
1 by brian
clean slate
433
434
  start_screen=0;
435
  row=end_row;
436
  pos=info;
437
  it.rewind();
438
  for (i=0 ; i < fields ; i++)
439
  {
440
    Create_field *cfield=it++;
441
    if (row++ == end_row)
442
    {
443
      if (i)
444
      {
445
	length=(uint) (pos-start_screen);
446
	int2store(start_screen,length);
447
	start_screen[2]=(uchar) (fields_on_screen+1);
448
	start_screen[3]=(uchar) (fields_on_screen);
449
      }
450
      row=start_row;
451
      start_screen=pos;
452
      pos+=4;
453
      pos[0]= (uchar) start_row-2;	/* Header string */
454
      pos[1]= (uchar) (cols >> 2);
455
      pos[2]= (uchar) (cols >> 1) +1;
456
      strfill((char *) pos+3,(uint) (cols >> 1),' ');
457
      pos+=(cols >> 1)+4;
458
    }
459
    length=(uint) strlen(cfield->field_name);
460
    if (length > cols-3)
461
      length=cols-3;
462
463
    if (!small_file)
464
    {
465
      pos[0]=(uchar) row;
466
      pos[1]=0;
467
      pos[2]=(uchar) (length+1);
468
      pos=(uchar*) strmake((char*) pos+3,cfield->field_name,length)+1;
469
    }
470
    cfield->row=(uint8) row;
471
    cfield->col=(uint8) (length+1);
472
    cfield->sc_length=(uint8) min(cfield->length,cols-(length+2));
473
  }
474
  length=(uint) (pos-start_screen);
475
  int2store(start_screen,length);
476
  start_screen[2]=(uchar) (row-start_row+2);
477
  start_screen[3]=(uchar) (row-start_row+1);
478
479
  *info_length=(uint) (pos-info);
51.2.2 by Patrick Galbraith
Removed DBUGs from
480
  return(info);
1 by brian
clean slate
481
} /* pack_screens */
482
483
484
	/* Pack keyinfo and keynames to keybuff for save in form-file. */
485
486
static uint pack_keys(uchar *keybuff, uint key_count, KEY *keyinfo,
487
                      ulong data_offset)
488
{
489
  uint key_parts,length;
490
  uchar *pos, *keyname_pos;
491
  KEY *key,*end;
492
  KEY_PART_INFO *key_part,*key_part_end;
51.2.2 by Patrick Galbraith
Removed DBUGs from
493
  
1 by brian
clean slate
494
495
  pos=keybuff+6;
496
  key_parts=0;
497
  for (key=keyinfo,end=keyinfo+key_count ; key != end ; key++)
498
  {
499
    int2store(pos, (key->flags ^ HA_NOSAME));
500
    int2store(pos+2,key->key_length);
501
    pos[4]= (uchar) key->key_parts;
502
    pos[5]= (uchar) key->algorithm;
503
    int2store(pos+6, key->block_size);
504
    pos+=8;
505
    key_parts+=key->key_parts;
506
    for (key_part=key->key_part,key_part_end=key_part+key->key_parts ;
507
	 key_part != key_part_end ;
508
	 key_part++)
509
510
    {
511
      uint offset;
512
      int2store(pos,key_part->fieldnr+1+FIELD_NAME_USED);
513
      offset= (uint) (key_part->offset+data_offset+1);
514
      int2store(pos+2, offset);
515
      pos[4]=0;					// Sort order
516
      int2store(pos+5,key_part->key_type);
517
      int2store(pos+7,key_part->length);
518
      pos+=9;
519
    }
520
  }
521
	/* Save keynames */
522
  keyname_pos=pos;
523
  *pos++=(uchar) NAMES_SEP_CHAR;
524
  for (key=keyinfo ; key != end ; key++)
525
  {
526
    uchar *tmp=(uchar*) strmov((char*) pos,key->name);
527
    *tmp++= (uchar) NAMES_SEP_CHAR;
528
    *tmp=0;
529
    pos=tmp;
530
  }
531
  *(pos++)=0;
532
533
  for (key=keyinfo,end=keyinfo+key_count ; key != end ; key++)
534
  {
535
    if (key->flags & HA_USES_COMMENT)
536
    {
537
      int2store(pos, key->comment.length);
538
      uchar *tmp= (uchar*)strnmov((char*) pos+2,key->comment.str,key->comment.length);
539
      pos= tmp;
540
    }
541
  }
542
543
  if (key_count > 127 || key_parts > 127)
544
  {
545
    keybuff[0]= (key_count & 0x7f) | 0x80;
546
    keybuff[1]= key_count >> 7;
547
    int2store(keybuff+2,key_parts);
548
  }
549
  else
550
  {
551
    keybuff[0]=(uchar) key_count;
552
    keybuff[1]=(uchar) key_parts;
553
    keybuff[2]= keybuff[3]= 0;
554
  }
555
  length=(uint) (pos-keyname_pos);
556
  int2store(keybuff+4,length);
51.2.2 by Patrick Galbraith
Removed DBUGs from
557
  return((uint) (pos-keybuff));
1 by brian
clean slate
558
} /* pack_keys */
559
560
561
	/* Make formheader */
562
563
static bool pack_header(uchar *forminfo, enum legacy_db_type table_type,
564
			List<Create_field> &create_fields,
565
                        uint info_length, uint screens, uint table_options,
566
                        ulong data_offset, handler *file)
567
{
568
  uint length,int_count,int_length,no_empty, int_parts;
569
  uint time_stamp_pos,null_fields;
570
  ulong reclength, totlength, n_length, com_length;
51.2.2 by Patrick Galbraith
Removed DBUGs from
571
  
1 by brian
clean slate
572
573
  if (create_fields.elements > MAX_FIELDS)
574
  {
575
    my_message(ER_TOO_MANY_FIELDS, ER(ER_TOO_MANY_FIELDS), MYF(0));
51.2.2 by Patrick Galbraith
Removed DBUGs from
576
    return(1);
1 by brian
clean slate
577
  }
578
579
  totlength= 0L;
580
  reclength= data_offset;
581
  no_empty=int_count=int_parts=int_length=time_stamp_pos=null_fields=
582
    com_length=0;
583
  n_length=2L;
584
585
	/* Check fields */
586
587
  List_iterator<Create_field> it(create_fields);
588
  Create_field *field;
589
  while ((field=it++))
590
  {
591
    uint tmp_len= system_charset_info->cset->charpos(system_charset_info,
592
                                                     field->comment.str,
593
                                                     field->comment.str +
594
                                                     field->comment.length,
595
                                                     COLUMN_COMMENT_MAXLEN);
596
597
    if (tmp_len < field->comment.length)
598
    {
599
      my_error(ER_WRONG_STRING_LENGTH, MYF(0),
600
               field->comment.str,"COLUMN COMMENT",
601
               (uint) COLUMN_COMMENT_MAXLEN);
51.2.2 by Patrick Galbraith
Removed DBUGs from
602
      return(1);
1 by brian
clean slate
603
    }
604
605
    totlength+= field->length;
606
    com_length+= field->comment.length;
607
    if (MTYP_TYPENR(field->unireg_check) == Field::NOEMPTY ||
608
	field->unireg_check & MTYP_NOEMPTY_BIT)
609
    {
610
      field->unireg_check= (Field::utype) ((uint) field->unireg_check |
611
					   MTYP_NOEMPTY_BIT);
612
      no_empty++;
613
    }
614
    /* 
615
      We mark first TIMESTAMP field with NOW() in DEFAULT or ON UPDATE 
616
      as auto-update field.
617
    */
618
    if (field->sql_type == MYSQL_TYPE_TIMESTAMP &&
619
        MTYP_TYPENR(field->unireg_check) != Field::NONE &&
620
	!time_stamp_pos)
621
      time_stamp_pos= (uint) field->offset+ (uint) data_offset + 1;
622
    length=field->pack_length;
623
    /* Ensure we don't have any bugs when generating offsets */
51.2.2 by Patrick Galbraith
Removed DBUGs from
624
    assert(reclength == field->offset + data_offset);
1 by brian
clean slate
625
    if ((uint) field->offset+ (uint) data_offset+ length > reclength)
626
      reclength=(uint) (field->offset+ data_offset + length);
627
    n_length+= (ulong) strlen(field->field_name)+1;
628
    field->interval_id=0;
629
    field->save_interval= 0;
630
    if (field->interval)
631
    {
632
      uint old_int_count=int_count;
633
634
      if (field->charset->mbminlen > 1)
635
      {
636
        /* 
637
          Escape UCS2 intervals using HEX notation to avoid
638
          problems with delimiters between enum elements.
639
          As the original representation is still needed in 
640
          the function make_empty_rec to create a record of
641
          filled with default values it is saved in save_interval
642
          The HEX representation is created from this copy.
643
        */
644
        field->save_interval= field->interval;
645
        field->interval= (TYPELIB*) sql_alloc(sizeof(TYPELIB));
646
        *field->interval= *field->save_interval; 
647
        field->interval->type_names= 
648
          (const char **) sql_alloc(sizeof(char*) * 
649
				    (field->interval->count+1));
650
        field->interval->type_names[field->interval->count]= 0;
651
        field->interval->type_lengths=
652
          (uint *) sql_alloc(sizeof(uint) * field->interval->count);
653
 
654
        for (uint pos= 0; pos < field->interval->count; pos++)
655
        {
656
          char *dst;
657
          const char *src= field->save_interval->type_names[pos];
658
          uint hex_length;
659
          length= field->save_interval->type_lengths[pos];
660
          hex_length= length * 2;
661
          field->interval->type_lengths[pos]= hex_length;
662
          field->interval->type_names[pos]= dst= (char*) sql_alloc(hex_length +
663
                                                                   1);
664
          octet2hex(dst, src, length);
665
        }
666
      }
667
668
      field->interval_id=get_interval_id(&int_count,create_fields,field);
669
      if (old_int_count != int_count)
670
      {
671
	for (const char **pos=field->interval->type_names ; *pos ; pos++)
672
	  int_length+=(uint) strlen(*pos)+1;	// field + suffix prefix
673
	int_parts+=field->interval->count+1;
674
      }
675
    }
676
    if (f_maybe_null(field->pack_flag))
677
      null_fields++;
678
  }
679
  int_length+=int_count*2;			// 255 prefix + 0 suffix
680
681
	/* Save values in forminfo */
682
683
  if (reclength > (ulong) file->max_record_length())
684
  {
685
    my_error(ER_TOO_BIG_ROWSIZE, MYF(0), (uint) file->max_record_length());
51.2.2 by Patrick Galbraith
Removed DBUGs from
686
    return(1);
1 by brian
clean slate
687
  }
688
  /* Hack to avoid bugs with small static rows in MySQL */
689
  reclength=max(file->min_record_length(table_options),reclength);
690
  if (info_length+(ulong) create_fields.elements*FCOMP+288+
691
      n_length+int_length+com_length > 65535L || int_count > 255)
692
  {
693
    my_message(ER_TOO_MANY_FIELDS, ER(ER_TOO_MANY_FIELDS), MYF(0));
51.2.2 by Patrick Galbraith
Removed DBUGs from
694
    return(1);
1 by brian
clean slate
695
  }
696
697
  bzero((char*)forminfo,288);
698
  length=(info_length+create_fields.elements*FCOMP+288+n_length+int_length+
699
	  com_length);
700
  int2store(forminfo,length);
701
  forminfo[256] = (uint8) screens;
702
  int2store(forminfo+258,create_fields.elements);
703
  int2store(forminfo+260,info_length);
704
  int2store(forminfo+262,totlength);
705
  int2store(forminfo+264,no_empty);
706
  int2store(forminfo+266,reclength);
707
  int2store(forminfo+268,n_length);
708
  int2store(forminfo+270,int_count);
709
  int2store(forminfo+272,int_parts);
710
  int2store(forminfo+274,int_length);
711
  int2store(forminfo+276,time_stamp_pos);
712
  int2store(forminfo+278,80);			/* Columns needed */
713
  int2store(forminfo+280,22);			/* Rows needed */
714
  int2store(forminfo+282,null_fields);
715
  int2store(forminfo+284,com_length);
716
  /* Up to forminfo+288 is free to use for additional information */
51.2.2 by Patrick Galbraith
Removed DBUGs from
717
  return(0);
1 by brian
clean slate
718
} /* pack_header */
719
720
721
	/* get each unique interval each own id */
722
723
static uint get_interval_id(uint *int_count,List<Create_field> &create_fields,
724
			    Create_field *last_field)
725
{
726
  List_iterator<Create_field> it(create_fields);
727
  Create_field *field;
728
  TYPELIB *interval=last_field->interval;
729
730
  while ((field=it++) != last_field)
731
  {
732
    if (field->interval_id && field->interval->count == interval->count)
733
    {
734
      const char **a,**b;
735
      for (a=field->interval->type_names, b=interval->type_names ;
736
	   *a && !strcmp(*a,*b);
737
	   a++,b++) ;
738
739
      if (! *a)
740
      {
741
	return field->interval_id;		// Re-use last interval
742
      }
743
    }
744
  }
745
  return ++*int_count;				// New unique interval
746
}
747
748
749
	/* Save fields, fieldnames and intervals */
750
751
static bool pack_fields(File file, List<Create_field> &create_fields,
752
                        ulong data_offset)
753
{
754
  register uint i;
755
  uint int_count, comment_length=0;
756
  uchar buff[MAX_FIELD_WIDTH];
757
  Create_field *field;
51.2.2 by Patrick Galbraith
Removed DBUGs from
758
  
1 by brian
clean slate
759
760
	/* Write field info */
761
762
  List_iterator<Create_field> it(create_fields);
763
764
  int_count=0;
765
  while ((field=it++))
766
  {
767
    uint recpos;
768
    buff[0]= (uchar) field->row;
769
    buff[1]= (uchar) field->col;
770
    buff[2]= (uchar) field->sc_length;
771
    int2store(buff+3, field->length);
772
    /* The +1 is here becasue the col offset in .frm file have offset 1 */
773
    recpos= field->offset+1 + (uint) data_offset;
774
    int3store(buff+5,recpos);
775
    int2store(buff+8,field->pack_flag);
776
    int2store(buff+10,field->unireg_check);
777
    buff[12]= (uchar) field->interval_id;
778
    buff[13]= (uchar) field->sql_type; 
779
    if (field->charset) 
780
      buff[14]= (uchar) field->charset->number;
781
    else
782
      buff[14]= 0;				// Numerical
783
    int2store(buff+15, field->comment.length);
784
    comment_length+= field->comment.length;
785
    set_if_bigger(int_count,field->interval_id);
786
    if (my_write(file, buff, FCOMP, MYF_RW))
51.2.2 by Patrick Galbraith
Removed DBUGs from
787
      return(1);
1 by brian
clean slate
788
  }
789
790
	/* Write fieldnames */
791
  buff[0]=(uchar) NAMES_SEP_CHAR;
792
  if (my_write(file, buff, 1, MYF_RW))
51.2.2 by Patrick Galbraith
Removed DBUGs from
793
    return(1);
1 by brian
clean slate
794
  i=0;
795
  it.rewind();
796
  while ((field=it++))
797
  {
798
    char *pos= strmov((char*) buff,field->field_name);
799
    *pos++=NAMES_SEP_CHAR;
800
    if (i == create_fields.elements-1)
801
      *pos++=0;
802
    if (my_write(file, buff, (size_t) (pos-(char*) buff),MYF_RW))
51.2.2 by Patrick Galbraith
Removed DBUGs from
803
      return(1);
1 by brian
clean slate
804
    i++;
805
  }
806
807
	/* Write intervals */
808
  if (int_count)
809
  {
810
    String tmp((char*) buff,sizeof(buff), &my_charset_bin);
811
    tmp.length(0);
812
    it.rewind();
813
    int_count=0;
814
    while ((field=it++))
815
    {
816
      if (field->interval_id > int_count)
817
      {
818
        unsigned char  sep= 0;
819
        unsigned char  occ[256];
820
        uint           i;
821
        unsigned char *val= NULL;
822
823
        bzero(occ, sizeof(occ));
824
825
        for (i=0; (val= (unsigned char*) field->interval->type_names[i]); i++)
826
          for (uint j = 0; j < field->interval->type_lengths[i]; j++)
827
            occ[(unsigned int) (val[j])]= 1;
828
829
        if (!occ[(unsigned char)NAMES_SEP_CHAR])
830
          sep= (unsigned char) NAMES_SEP_CHAR;
831
        else if (!occ[(unsigned int)','])
832
          sep= ',';
833
        else
834
        {
835
          for (uint i=1; i<256; i++)
836
          {
837
            if(!occ[i])
838
            {
839
              sep= i;
840
              break;
841
            }
842
          }
843
844
          if(!sep)    /* disaster, enum uses all characters, none left as separator */
845
          {
846
            my_message(ER_WRONG_FIELD_TERMINATORS,ER(ER_WRONG_FIELD_TERMINATORS),
847
                       MYF(0));
51.2.2 by Patrick Galbraith
Removed DBUGs from
848
            return(1);
1 by brian
clean slate
849
          }
850
        }
851
852
        int_count= field->interval_id;
853
        tmp.append(sep);
854
        for (const char **pos=field->interval->type_names ; *pos ; pos++)
855
        {
856
          tmp.append(*pos);
857
          tmp.append(sep);
858
        }
859
        tmp.append('\0');                      // End of intervall
860
      }
861
    }
862
    if (my_write(file,(uchar*) tmp.ptr(),tmp.length(),MYF_RW))
51.2.2 by Patrick Galbraith
Removed DBUGs from
863
      return(1);
1 by brian
clean slate
864
  }
865
  if (comment_length)
866
  {
867
    it.rewind();
868
    int_count=0;
869
    while ((field=it++))
870
    {
871
      if (field->comment.length)
872
	if (my_write(file, (uchar*) field->comment.str, field->comment.length,
873
		     MYF_RW))
51.2.2 by Patrick Galbraith
Removed DBUGs from
874
	  return(1);
1 by brian
clean slate
875
    }
876
  }
51.2.2 by Patrick Galbraith
Removed DBUGs from
877
  return(0);
1 by brian
clean slate
878
}
879
880
881
	/* save an empty record on start of formfile */
882
883
static bool make_empty_rec(THD *thd, File file,enum legacy_db_type table_type,
884
			   uint table_options,
885
			   List<Create_field> &create_fields,
886
			   uint reclength,
887
                           ulong data_offset,
888
                           handler *handler)
889
{
890
  int error= 0;
891
  Field::utype type;
892
  uint null_count;
893
  uchar *buff,*null_pos;
894
  TABLE table;
895
  TABLE_SHARE share;
896
  Create_field *field;
897
  enum_check_fields old_count_cuted_fields= thd->count_cuted_fields;
51.2.2 by Patrick Galbraith
Removed DBUGs from
898
  
1 by brian
clean slate
899
900
  /* We need a table to generate columns for default values */
901
  bzero((char*) &table, sizeof(table));
902
  bzero((char*) &share, sizeof(share));
903
  table.s= &share;
904
905
  if (!(buff=(uchar*) my_malloc((size_t) reclength,MYF(MY_WME | MY_ZEROFILL))))
906
  {
51.2.2 by Patrick Galbraith
Removed DBUGs from
907
    return(1);
1 by brian
clean slate
908
  }
909
910
  table.in_use= thd;
911
  table.s->db_low_byte_first= handler->low_byte_first();
912
  table.s->blob_ptr_size= portable_sizeof_char_ptr;
913
914
  null_count=0;
915
  if (!(table_options & HA_OPTION_PACK_RECORD))
916
  {
917
    null_count++;			// Need one bit for delete mark
918
    *buff|= 1;
919
  }
920
  null_pos= buff;
921
922
  List_iterator<Create_field> it(create_fields);
923
  thd->count_cuted_fields= CHECK_FIELD_WARN;    // To find wrong default values
924
  while ((field=it++))
925
  {
926
    /*
927
      regfield don't have to be deleted as it's allocated with sql_alloc()
928
    */
929
    Field *regfield= make_field(&share,
930
                                buff+field->offset + data_offset,
931
                                field->length,
932
                                null_pos + null_count / 8,
933
                                null_count & 7,
934
                                field->pack_flag,
935
                                field->sql_type,
936
                                field->charset,
937
                                field->unireg_check,
938
                                field->save_interval ? field->save_interval :
939
                                field->interval, 
940
                                field->field_name);
941
    if (!regfield)
942
    {
943
      error= 1;
944
      goto err;                                 // End of memory
945
    }
946
947
    /* save_in_field() will access regfield->table->in_use */
948
    regfield->init(&table);
949
950
    if (!(field->flags & NOT_NULL_FLAG))
951
    {
952
      *regfield->null_ptr|= regfield->null_bit;
953
      null_count++;
954
    }
955
956
    type= (Field::utype) MTYP_TYPENR(field->unireg_check);
957
958
    if (field->def)
959
    {
960
      int res= field->def->save_in_field(regfield, 1);
961
      /* If not ok or warning of level 'note' */
962
      if (res != 0 && res != 3)
963
      {
964
        my_error(ER_INVALID_DEFAULT, MYF(0), regfield->field_name);
965
        error= 1;
966
        delete regfield; //To avoid memory leak
967
        goto err;
968
      }
969
    }
970
    else if (regfield->real_type() == MYSQL_TYPE_ENUM &&
971
	     (field->flags & NOT_NULL_FLAG))
972
    {
973
      regfield->set_notnull();
974
      regfield->store((longlong) 1, TRUE);
975
    }
976
    else if (type == Field::YES)		// Old unireg type
977
      regfield->store(ER(ER_YES),(uint) strlen(ER(ER_YES)),system_charset_info);
978
    else if (type == Field::NO)			// Old unireg type
979
      regfield->store(ER(ER_NO), (uint) strlen(ER(ER_NO)),system_charset_info);
980
    else
981
      regfield->reset();
982
  }
51.2.2 by Patrick Galbraith
Removed DBUGs from
983
  assert(data_offset == ((null_count + 7) / 8));
1 by brian
clean slate
984
985
  /*
986
    We need to set the unused bits to 1. If the number of bits is a multiple
987
    of 8 there are no unused bits.
988
  */
989
  if (null_count & 7)
990
    *(null_pos + null_count / 8)|= ~(((uchar) 1 << (null_count & 7)) - 1);
991
992
  error= my_write(file, buff, (size_t) reclength,MYF_RW) != 0;
993
994
err:
995
  my_free(buff, MYF(MY_FAE));
996
  thd->count_cuted_fields= old_count_cuted_fields;
51.2.2 by Patrick Galbraith
Removed DBUGs from
997
  return(error);
1 by brian
clean slate
998
} /* make_empty_rec */