internals.texi 182 KB
Newer Older
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1
\input texinfo  @c -*-texinfo-*-
2
@c Copyright 2002 MySQL AB
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3 4 5
@c
@c %**start of header
@setfilename internals.info
6

bk@work.mysql.com's avatar
bk@work.mysql.com committed
7 8
@c We want the types in the same index
@synindex cp fn
9

bk@work.mysql.com's avatar
bk@work.mysql.com committed
10 11 12
@iftex
@afourpaper
@end iftex
13

bk@work.mysql.com's avatar
bk@work.mysql.com committed
14 15
@c Get version and other info
@include include.texi
16

bk@work.mysql.com's avatar
bk@work.mysql.com committed
17 18 19 20
@ifclear tex-debug
@c This removes the black squares in the right margin
@finalout
@end ifclear
21

bk@work.mysql.com's avatar
bk@work.mysql.com committed
22 23
@c Set background for HTML
@set _body_tags BGCOLOR=#FFFFFF TEXT=#000000 LINK=#101090 VLINK=#7030B0
24 25
@settitle @strong{MySQL} Internals Manual for version @value{mysql_version}.
@setchapternewpage odd
26
@paragraphindent 0
27

bk@work.mysql.com's avatar
bk@work.mysql.com committed
28 29 30 31 32 33 34 35 36 37 38 39
@c %**end of header

@ifinfo
@format
START-INFO-DIR-ENTRY
* mysql-internals: (mysql-internals).               @strong{MySQL} internals.
END-INFO-DIR-ENTRY
@end format
@end ifinfo

@titlepage
@sp 10
40
@center @titlefont{@strong{MySQL} Internals Manual}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
41
@sp 10
42 43
@center Copyright @copyright{} 1998-2002 MySQL AB
@page
bk@work.mysql.com's avatar
bk@work.mysql.com committed
44 45
@end titlepage

46
@node Top, caching, (dir), (dir)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
47 48 49 50 51 52

@ifinfo
This is a manual about @strong{MySQL} internals.
@end ifinfo

@menu
53
* caching::                     How MySQL Handles Caching
54
* join_buffer_size::
55 56 57 58 59 60
* flush tables::                How MySQL Handles @code{FLUSH TABLES}
* filesort::                    How MySQL Does Sorting (@code{filesort})
* coding guidelines::           Coding Guidelines
* mysys functions::             Functions In The @code{mysys} Library
* DBUG::                        DBUG Tags To Use
* protocol::                    MySQL Client/Server Protocol
61
* Fulltext Search::             Fulltext Search in MySQL
62 63 64
* MyISAM Record Structure::     MyISAM Record Structure
* InnoDB Record Structure::     InnoDB Record Structure
* InnoDB Page Structure::       InnoDB Page Structure
65 66
* Files in MySQL Sources::      Annotated List Of Files in the MySQL Source Code Distribution
* Files in InnoDB Sources::     Annotated List Of Files in the InnoDB Source Code Distribution
bk@work.mysql.com's avatar
bk@work.mysql.com committed
67 68
@end menu

69

70
@node caching, join_buffer_size, Top, Top
71
@chapter How MySQL Handles Caching
bk@work.mysql.com's avatar
bk@work.mysql.com committed
72

73
@strong{MySQL} has the following caches:
74
(Note that the some of the filename have a wrong spelling of cache. :)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
75

76
@table @strong
77

78
@item Key Cache
bk@work.mysql.com's avatar
bk@work.mysql.com committed
79 80 81
A shared cache for all B-tree index blocks in the different NISAM
files. Uses hashing and reverse linked lists for quick caching of the
last used blocks and quick flushing of changed entries for a specific
82
table. (@file{mysys/mf_keycash.c})
bk@work.mysql.com's avatar
bk@work.mysql.com committed
83

84
@item Record Cache
bk@work.mysql.com's avatar
bk@work.mysql.com committed
85
This is used for quick scanning of all records in a table.
86
(@file{mysys/mf_iocash.c} and @file{isam/_cash.c})
bk@work.mysql.com's avatar
bk@work.mysql.com committed
87

88
@item Table Cache
89
This holds the last used tables. (@file{sql/sql_base.cc})
bk@work.mysql.com's avatar
bk@work.mysql.com committed
90

91
@item Hostname Cache
bk@work.mysql.com's avatar
bk@work.mysql.com committed
92
For quick lookup (with reverse name resolving). Is a must when one has a
93 94
slow DNS. 
(@file{sql/hostname.cc})
bk@work.mysql.com's avatar
bk@work.mysql.com committed
95

96
@item Privilege Cache
bk@work.mysql.com's avatar
bk@work.mysql.com committed
97
To allow quick change between databases the last used privileges are
98 99
cached for each user/database combination.
(@file{sql/sql_acl.cc})
bk@work.mysql.com's avatar
bk@work.mysql.com committed
100

101 102 103
@item Heap Table Cache
Many use of @code{GROUP BY} or @code{DISTINCT} caches all found rows in 
a @code{HEAP} table. (This is a very quick in-memory table with hash index.)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
104

105
@item Join buffer Cache
106 107 108 109 110
For every full join in a @code{SELECT} statement (a full join here means
there were no keys that one could use to find the next table in a list), 
the found rows are cached in a join cache.  One @code{SELECT} query can 
use many join caches in the worst case.
@end table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
111

112
@node join_buffer_size, flush tables, caching, Top
113
@chapter How MySQL uses the join_buffer cache
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

Basic information about @code{join_buffer_size}:

@itemize @bullet
@item
It's only used in the case when join type is of type @code{ALL} or
@code{index}; In other words: no possible keys can be used.
@item
A join buffer is never allocated for the first not-const table,
even it it would be of type @code{ALL}/@code{index}.
@item
The buffer is allocated when we need to do a each full join between two
tables and freed after the query is done.
@item
Accepted row combinations of tables before the @code{ALL}/@code{index}
able is stored in the cache and is used to compare against each read
row in the @code{ALL} table.
@item
We only store the used fields in the join_buffer cache, not the
whole rows.
@end itemize

Assume you have the following join:

@example
Table name	Type
t1		range
t2		ref
t3		@code{ALL}
@end example

The join is then done as follows:

@example
- While rows in t1 matching range
 - Read through all rows in t2 according to reference key
  - Store used fields form t1,t2 in cache
  - If cache is full
    - Read through all rows in t3
      - Compare t3 row against all t1,t2 combination in cache
        - If rows satisfying join condition, send it to client
    - Empty cache

- Read through all rows in t3
 - Compare t3 row against all stored t1,t2 combinations in cache
   - If rows satisfying join condition, send it to client
@end example

The above means that table t3 is scanned

@example
(size-of-stored-row(t1,t2) * accepted-row-cominations(t1,t2))/
join_buffer_size+1
@end example
times.

Some conclusions:

@itemize @bullet
@item
The larger the join_buff_size, the fewer scans of t3.
If @code{join_buff_size} is already large enough to hold all previous row
combinations then there is no speed to gain by making it bigger.
@item
If there is several tables of @code{ALL}/@code{index} then the we
allocate one @code{join_buffer_size buffer} for each of them and use the
same algorithm described above to handle it.  (In other words, we store
the same row combination several times into different buffers)
@end itemize
183

184
@node flush tables, filesort, join_buffer_size, Top
185
@chapter How MySQL Handles @code{FLUSH TABLES}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
186 187

@itemize @bullet
188 189

@item
190
Flush tables is handled in @file{sql/sql_base.cc::close_cached_tables()}.
191

bk@work.mysql.com's avatar
bk@work.mysql.com committed
192 193 194
@item
The idea of flush tables is to force all tables to be closed. This
is mainly to ensure that if someone adds a new table outside of
195 196 197 198 199
@strong{MySQL} (for example with @code{cp}) all threads will start using 
the new table. This will also ensure that all table changes are flushed 
to disk (but of course not as optimally as simple calling a sync on
all tables)!

bk@work.mysql.com's avatar
bk@work.mysql.com committed
200
@item
201 202
When one does a @code{FLUSH TABLES}, the variable @code{refresh_version} 
will be incremented. Every time a thread releases a table it checks if
bk@work.mysql.com's avatar
bk@work.mysql.com committed
203
the refresh version of the table (updated at open) is the same as
204 205
the current @code{refresh_version}.  If not it will close it and broadcast
a signal on @code{COND_refresh} (to wait any thread that is waiting for
bk@work.mysql.com's avatar
bk@work.mysql.com committed
206
all instanses of a table to be closed).
207

bk@work.mysql.com's avatar
bk@work.mysql.com committed
208
@item
209 210 211 212 213
The current @code{refresh_version} is also compared to the open 
@code{refresh_version} after a thread gets a lock on a table.  If the 
refresh version is different the thread will free all locks, reopen the
table and try to get the locks again;  This is just to quickly get all 
tables to use the newest version.  This is handled by
214 215
@file{sql/lock.cc::mysql_lock_tables()} and 
@file{sql/sql_base.cc::wait_for_tables()}.
216

bk@work.mysql.com's avatar
bk@work.mysql.com committed
217
@item
218 219 220
When all tables has been closed @code{FLUSH TABLES} will return an ok 
to client.

bk@work.mysql.com's avatar
bk@work.mysql.com committed
221
@item
222 223 224 225 226
If the thread that is doing @code{FLUSH TABLES} has a lock on some tables,
it will first close the locked tables, then wait until all other threads
have also closed them, and then reopen them and get the locks.
After this it will give other threads a chance to open the same tables.

bk@work.mysql.com's avatar
bk@work.mysql.com committed
227 228
@end itemize

229 230
@node filesort, coding guidelines, flush tables, Top
@chapter How MySQL Does Sorting (@code{filesort})
231

232 233 234 235 236 237 238 239 240
@itemize @bullet

@item
Read all rows according to key or by table scanning.

@item
Store the sort-key in a buffer (@code{sort_buffer}).

@item
241
When the buffer gets full, run a @code{qsort} on it and store the result
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
in a temporary file.  Save a pointer to the sorted block.

@item
Repeat the above until all rows have been read.

@item
Repeat the following until there is less than @code{MERGEBUFF2} (15) 
blocks left.

@item
Do a multi-merge of up to @code{MERGEBUFF} (7) regions to one block in
another temporary file.  Repeat until all blocks from the first file
are in the second file.

@item
On the last multi-merge, only the pointer to the row (last part of
the sort-key) is written to a result file.

@item
Now the code in @file{sql/records.cc} will be used to read through them
in sorted order by using the row pointers in the result file.
To optimize this, we read in a big block of row pointers, sort these
and then we read the rows in the sorted order into a row buffer
265
(@code{record_buffer}).
266 267

@end itemize
268

269 270 271

@node coding guidelines, mysys functions, filesort, Top
@chapter Coding Guidelines
272

273 274 275
@itemize @bullet

@item
276
We use @uref{http://www.bitkeeper.com/, BitKeeper} for source management.
277 278

@item
279
You should use the @strong{MySQL} 4.0 source for all developments.
280 281 282

@item
If you have any questions about the @strong{MySQL} source, you can post these
283 284
to @email{dev-public@@mysql.com} and we will answer them.  Please
remember to not use this internal email list in public!
285 286

@item
287 288
Try to write code in a lot of black boxes that can be reused or use at
least a clean, easy to change interface.
289 290 291 292 293

@item
Reuse code;  There is already a lot of algorithms in MySQL for list handling,
queues, dynamic and hashed arrays, sorting, etc. that can be reused.

294 295 296 297 298 299
@item
Use the @code{my_*} functions like @code{my_read()}/@code{my_write()}/
@code{my_malloc()} that you can find in the @code{mysys} library instead 
of the direct system calls;  This will make your code easier to debug and 
more portable.

300 301 302 303 304 305 306 307 308 309 310 311 312 313
@item
Try to always write optimized code, so that you don't have to
go back and rewrite it a couple of months later.  It's better to
spend 3 times as much time designing and writing an optimal function than
having to do it all over again later on.

@item
Avoid CPU wasteful code, even where it does not matter, so that
you will not develop sloppy coding habits.

@item
If you can write it in fewer lines, do it (as long as the code will not
be slower or much harder to read).

314 315 316
@item
Don't use two commands on the same line.

317 318 319 320
@item
Do not check the same pointer for @code{NULL} more than once.

@item
321
Use long function and variable names in English.  This makes your code
322 323 324
easier to read. 

@item
325 326
Use @code{my_var} as opposed to @code{myVar} or @code{MyVar} (@samp{_} 
rather than dancing SHIFT to seperate words in identifiers).
327 328 329 330 331 332

@item
Think assembly - make it easier for the compiler to optimize your code.

@item
Comment your code when you do something that someone else may think
333
is not ``trivial''.
334 335

@item
336 337
Use @code{libstring} functions (in the @file{strings} directory)
instead of standard @code{libc} string functions whenever possible.
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

@item
Avoid using @code{malloc()} (its REAL slow);  For memory allocations 
that only need to live for the lifetime of one thread, one should use
@code{sql_alloc()} instead.

@item
Before making big design decisions, please first post a summary of
what you want to do, why you want to do it, and how you plan to do
it.  This way we can easily provide you with feedback and also
easily discuss it thoroughly if some other developer thinks there is better
way to do the same thing!

@item
Class names start with a capital letter.

@item
Structure types are @code{typedef}'ed to an all-caps identifier.

@item
Any @code{#define}'s are in all-caps.

@item
Matching @samp{@{} are in the same column.

363
@item
364 365
Put the @samp{@{} after a @code{switch} on the same line, as this gives 
better overall indentation for the switch statement:
366 367

@example
368
switch (arg) @{
369 370 371
@end example

@item
372 373
In all other cases, @samp{@{} and @samp{@}} should be on their own line, except
if there is nothing inside @samp{@{} and @samp{@}}.
374 375

@item
376
Have a space after @code{if}
377 378

@item
379
Put a space after @samp{,} for function arguments
380

381
@item
382
Functions return @samp{0} on success, and non-zero on error, so you can do:
383 384

@example
385
if(a() || b() || c()) @{ error("something went wrong"); @}
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
@end example

@item
Using @code{goto} is okay if not abused.

@item
Avoid default variable initalizations, use @code{LINT_INIT()} if the
compiler complains after making sure that there is really no way
the variable can be used uninitialized.

@item
Do not instantiate a class if you do not have to.

@item
Use pointers rather than array indexing when operating on strings.

@end itemize

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
Suggested mode in emacs:

@example
(load "cc-mode")
(setq c-mode-common-hook '(lambda ()
			    (turn-on-font-lock)
			    (setq comment-column 48)))
(setq c-style-alist
      (cons
       '("MY"
	 (c-basic-offset . 2)
	 (c-comment-only-line-offset . 0)
	 (c-offsets-alist . ((statement-block-intro . +)
			     (knr-argdecl-intro . 0)
			     (substatement-open . 0)
			     (label . -)
			     (statement-cont . +)
			     (arglist-intro . c-lineup-arglist-intro-after-paren)
			     (arglist-close . c-lineup-arglist)
			     ))
	 )
       c-style-alist))
(c-set-style "MY")
(setq c-default-style "MY")
@end example

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

@node mysys functions, DBUG, coding guidelines, Top
@chapter Functions In The @code{mysys} Library

Functions in @code{mysys}: (For flags see @file{my_sys.h})

@table @code
@item int my_copy _A((const char *from, const char *to, myf MyFlags));
Copy file from @code{from} to @code{to}.

@item int my_delete _A((const char *name, myf MyFlags));
Delete file @code{name}.

@item int my_getwd _A((string buf, uint size, myf MyFlags));
@item int my_setwd _A((const char *dir, myf MyFlags));
Get and set working directory.

@item string my_tempnam _A((const char *pfx, myf MyFlags));
Make a unique temporary file name by using dir and adding something after
@code{pfx} to make name unique.  The file name is made by adding a unique
six character string and @code{TMP_EXT} after @code{pfx}.
Returns pointer to @code{malloc()}'ed area for filename. Should be freed by
@code{free()}.

@item File my_open _A((const char *FileName,int Flags,myf MyFlags));
@item File my_create _A((const char *FileName, int CreateFlags, int AccsesFlags, myf MyFlags));
@item int my_close _A((File Filedes, myf MyFlags));
@item uint my_read _A((File Filedes, byte *Buffer, uint Count, myf MyFlags));
@item uint my_write _A((File Filedes, const byte *Buffer, uint Count, myf MyFlags));
@item ulong my_seek _A((File fd,ulong pos,int whence,myf MyFlags));
@item ulong my_tell _A((File fd,myf MyFlags));
Use instead of open, open-with-create-flag, close, read, and write
to get automatic error messages (flag @code{MYF_WME}) and only have
to test for != 0 if error (flag @code{MY_NABP}).

@item int my_rename _A((const char *from, const char *to, myf MyFlags));
Rename file from @code{from} to @code{to}.

@item FILE *my_fopen _A((const char *FileName,int Flags,myf MyFlags));
@item FILE *my_fdopen _A((File Filedes,int Flags,myf MyFlags));
@item int my_fclose _A((FILE *fd,myf MyFlags));
@item uint my_fread _A((FILE *stream,byte *Buffer,uint Count,myf MyFlags));
@item uint my_fwrite _A((FILE *stream,const byte *Buffer,uint Count, myf MyFlags));
@item ulong my_fseek _A((FILE *stream,ulong pos,int whence,myf MyFlags));
@item ulong my_ftell _A((FILE *stream,myf MyFlags));
Same read-interface for streams as for files.

@item gptr _mymalloc _A((uint uSize,const char *sFile,uint uLine, myf MyFlag));
@item gptr _myrealloc _A((string pPtr,uint uSize,const char *sFile,uint uLine, myf MyFlag));
@item void _myfree _A((gptr pPtr,const char *sFile,uint uLine));
@item int _sanity _A((const char *sFile,unsigned int uLine));
@item gptr _myget_copy_of_memory _A((const byte *from,uint length,const char *sFile, uint uLine,myf MyFlag));
@code{malloc(size,myflag)} is mapped to these functions if not compiled 
with @code{-DSAFEMALLOC}.

@item void TERMINATE _A((void));
Writes @code{malloc()} info on @code{stdout} if compiled with 
@code{-DSAFEMALLOC}.

@item int my_chsize _A((File fd, ulong newlength, myf MyFlags));
Change size of file @code{fd} to @code{newlength}.

@item void my_error _D((int nr, myf MyFlags, ...));
Writes message using error number (see @file{mysys/errors.h}) on @code{stdout},
or using curses, if @code{MYSYS_PROGRAM_USES_CURSES()} has been called.

@item void my_message _A((const char *str, myf MyFlags));
Writes @code{str} on @code{stdout}, or using curses, if 
@code{MYSYS_PROGRAM_USES_CURSES()} has been called.

@item void my_init _A((void ));
Start each program (in @code{main()}) with this.

@item void my_end _A((int infoflag));
Gives info about program.
If @code{infoflag & MY_CHECK_ERROR}, prints if some files are left open.
If @code{infoflag & MY_GIVE_INFO}, prints timing info and malloc info
about program.

@item int my_redel _A((const char *from, const char *to, int MyFlags));
Delete @code{from} before rename of @code{to} to @code{from}.  Copies state
from old file to new file. If @code{MY_COPY_TIME} is set, sets old time.

@item int my_copystat _A((const char *from, const char *to, int MyFlags));
Copy state from old file to new file.  If @code{MY_COPY_TIME} is set,
sets old time.

@item string my_filename _A((File fd));
Returns filename of open file.

@item int dirname _A((string to, const char *name));
Copy name of directory from filename.

@item int test_if_hard_path _A((const char *dir_name));
Test if @code{dir_name} is a hard path (starts from root).

@item void convert_dirname _A((string name));
Convert dirname according to system.
In MSDOS, changes all characters to capitals and changes @samp{/} to @samp{\}.

@item string fn_ext _A((const char *name));
Returns pointer to extension in filename.

@item string fn_format _A((string to,const char *name,const char *dsk,const char *form,int flag));
534 535 536 537 538 539 540 541 542 543 544 545 546
	format a filename with replace of library and extension and
	converts between different systems.
	params to and name may be identicall
	function dosn't change name if name != to
	Flag may be:	1   force replace filnames library with 'dsk'
			2   force replace extension with 'form' */
			4   force Unpack filename (replace ~ with home)
			8   Pack filename as short as possibly for output to
			    user.
	All open requests should allways use at least:
	"open(fn_format(temp_buffe,name,"","",4),...)" to unpack home and
	convert filename to system-form.

547 548 549 550 551 552 553 554
@item string fn_same _A((string toname, const char *name, int flag));
Copys directory and extension from @code{name} to @code{toname} if neaded.
Copying can be forced by same flags used in @code{fn_format()}.

@item int wild_compare _A((const char *str, const char *wildstr));
Compare if @code{str} matches @code{wildstr}. @code{wildstr} can contain 
@samp{*} and @samp{?} as wildcard characters.
Returns 0 if @code{str} and @code{wildstr} match.
555

556 557
@item void get_date _A((string to, int timeflag));
Get current date in a form ready for printing.
558

559 560 561
@item void soundex _A((string out_pntr, string in_pntr))
Makes @code{in_pntr} to a 5 char long string.  All words that sound
alike have the same string.
562

563 564 565 566
@item int init_key_cache _A((ulong use_mem, ulong leave_this_much_mem));
Use caching of keys in MISAM, PISAM, and ISAM.
@code{KEY_CACHE_SIZE} is a good size.
Remember to lock databases for optimal caching.
567

568 569
@item void end_key_cache _A((void));
End key caching.
570 571
@end table 

572 573


574 575
@node DBUG, protocol, mysys functions, Top
@chapter DBUG Tags To Use
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
576 577 578

Here is some of the tags we now use:
(We should probably add a couple of new ones)
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600

@table @code 
@item enter
Arguments to the function.

@item exit
Results from the function.

@item info
Something that may be interesting.

@item warning
When something doesn't go the usual route or may be wrong.

@item error
When something went wrong.

@item loop
Write in a loop, that is probably only useful when debugging
the loop.  These should normally be deleted when one is
satisfied with the code and it has been in real use for a while.
@end table
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
601 602 603

Some specific to mysqld, because we want to watch these carefully:

604 605 606 607 608 609 610 611 612 613 614 615
@table @code
@item trans
Starting/stopping transactions.

@item quit
@code{info} when mysqld is preparing to die.

@item query
Print query.
@end table


616
@node protocol, Fulltext Search, DBUG, Top
617 618 619 620 621 622 623 624
@chapter MySQL Client/Server Protocol

@menu
* raw packet without compression::  
* raw packet with compression::  
* basic packets::               
* communication::               
* fieldtype codes::             
625 626
* protocol functions::          
* protocol version 2::          
627
@end menu
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
628

629 630
@node raw packet without compression, raw packet with compression, protocol, protocol
@section Raw Packet Without Compression
631

632
@example
633 634 635 636
+-----------------------------------------------+
| Packet Length | Packet no     | Data          |
| 3 Bytes       | 1 Byte        | n Bytes       |
+-----------------------------------------------+
637
@end example
638

639 640 641 642 643
@table @asis
@item 3 Byte packet length
The length is calculated with int3store
See include/global.h for details.
The max packetsize can be 16 MB.
644

645 646 647 648 649
@item 1 Byte packet no
If no compression is used the first 4 bytes of each packet is the header 
of the packet. The packet number is incremented for each sent packet.
The first packet starts with 0.
@item n Byte data 
650

651
@end table
652 653

The packet length can be recalculated with:
654 655

@example
656
length = byte1 + (256 * byte2) + (256 * 256 * byte3)
657 658
@end example

659 660 661 662 663

@node raw packet with compression, basic packets, raw packet without compression, protocol
@section Raw Packet With Compression

@example
664 665 666 667
+---------------------------------------------------+
| Packet Length | Packet no | Uncomp. Packet Length |
| 3 Bytes       | 1 Byte    | 3 Bytes               |
+---------------------------------------------------+
668
@end example
669

670 671 672 673 674 675 676 677 678
@table @asis
@item 3 Byte packet length
The length is calculated with int3store
See include/global.h for details.
The max packetsize can be 16 MB.

@item 1 Byte packet no
@item 3 Byte uncompressed packet length
@end table
679

680 681 682
If compression is used the first 7 bytes of each packet
is the header of the packet.

683

684 685 686 687 688 689 690 691
@node basic packets, communication, raw packet with compression, protocol
@section Basic Packets

@menu
* ok packet::                   
* error packet::                
@end menu

692

693
@node ok packet, error packet, basic packets, basic packets, basic packets
694 695
@subsection OK Packet

696 697
For details, see @file{sql/net_pkg.cc::send_ok()}.

698
@example
699 700 701 702 703 704 705 706 707 708
+-----------------------------------------------+
| Header        | No of Rows    | Affected Rows |
|               | 1 Byte        | 1-8 Byte      |
|-----------------------------------------------|
| ID (last_insert_id)   | Status | Length       |
| 1-8 Byte              | 2 Byte | 1-8 Byte     |
|-----------------------------------------------|
| Messagetext                                   |
| n Byte                                        |
+-----------------------------------------------+
709
@end example
710

711 712 713 714 715 716 717 718 719 720
@table @asis
@item Header
@item 1 byte number of rows ? (always 0 ?)
@item 1-8 bytes affected rows
@item 1-8 byte id (last_insert_id) 
@item 2 byte Status (usually 0)
@item If the OK-packege includes a message:
@item 1-8 bytes length of message
@item n bytes messagetext
@end table
721

722

723
@node error packet,  , ok packet, basic packets, basic packets
724 725 726
@subsection Error Packet	

@example
727 728 729 730 731 732 733
+-----------------------------------------------+
| Header        | Status code   | Error no      |
|               | 1 Byte        | 2 Byte        |
|-----------------------------------------------|
| Messagetext                          | 0x00   |
| n Byte                               | 1 Byte |
+-----------------------------------------------+
734 735
@end example

736 737 738 739 740 741 742
@table @asis
@item Header
@item 1 byte status code (0xFF = ERROR)
@item 2 byte error number (is only sent to new 3.23 clients.
@item n byte errortext
@item 1 byte 0x00
@end table
743 744


745 746
@node communication, fieldtype codes, basic packets, protocol
@section Communication
747

748
@example
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
> Packet from server to client
< Paket from client tor server

	Login
	------
		> 1. packet	
		Header
		1 byte protocolversion
		n byte serverversion
		1 byte 0x00
		4 byte threadnumber 
		8 byte crypt seed 
		1 byte 0x00
		2 byte CLIENT_xxx options (see include/mysql_com.h
			that is supported by the server
		1 byte number of current server charset
		2 byte server status variables (SERVER_STATUS_xxx flags)
		13 byte 0x00 (not used yet).

		< 2. packet	
		Header
		2 byte CLIENT_xxx options
		3 byte max_allowed_packet for the client
		n byte username
		1 byte 0x00
		8 byte crypted password
		1 byte 0x00
		n byte databasename
		1 byte 0x00 

		> 3. packet	
		OK-packet


	Command
	--------
		< 1. packet	
		Header
		1 byte command type (e.g.0x03 = query)
		n byte query

	Result set (after command)
	--------------------------
		> 2. packet	
		Header
		1-8 byte field_count (packed with net_store_length())
		
		If field_count == 0 (command): 
		1-8 byte affected rows
		1-8 byte insert id
		2 bytes server_status (SERVER_STATUS_xx) 		
		
		If field_count == NULL_LENGTH (251)
		LOAD DATA LOCAL INFILE

		If field_count > 0 Result Set:

		> n packets	
		Header Info
		Column description: 5 data object /column
		(See code in unpack_fields())
		
		Columninfo for each column:
			1 data block table_name
			    1 byte length of block
			    n byte data
			1 data block field_name
			    1 byte length of block...
			    n byte data
			1 data block display length of field
			    1 byte length of block
			    3 bytes display length of filed
			1 data block type field of type (enum_field_types)
			    1 byte length of block
			    1 bytexs field of type
			1 data block flags
			    1 byte length of block
			    2 byte flags for the columns (NOT_NULL_FLAG, ZEROFILL_FLAG....)
			    1 byte decimals

		if table definition:
			1 data block default value

		Actual result (one packet per row):
		4 byte header
		1-8 byte length of data
		n data
836
@end example
837
 
838
@node fieldtype codes, protocol functions, communication
839
@section Fieldtype Codes
840

841
@example
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
                display_length  |enum_field_type        |flags
                ----------------------------------------------------
Blob            03 FF FF 00     |01 FC                  |03 90 00 00
Mediumblob      03 FF FF FF     |01 FC                  |03 90 00 00
Tinyblob        03 FF 00 00     |01 FC                  |03 90 00 00
Text            03 FF FF 00     |01 FC                  |03 10 00 00
Mediumtext      03 FF FF FF     |01 FC                  |03 10 00 00
Tinytext        03 FF 00 00     |01 FC                  |03 10 00 00
Integer         03 0B 00 00     |01 03                  |03 03 42 00
Mediumint       03 09 00 00     |01 09                  |03 00 00 00
Smallint        03 06 00 00     |01 02                  |03 00 00 00
Tinyint         03 04 00 00     |01 01                  |03 00 00 00
Varchar         03 XX 00 00     |01 FD                  |03 00 00 00
Enum            03 05 00 00     |01 FE                  |03 00 01 00
Datetime        03 13 00 00     |01 0C                  |03 00 00 00
Timestamp       03 0E 00 00     |01 07                  |03 61 04 00
Time            03 08 00 00     |01 0B                  |03 00 00 00
Date            03 0A 00 00     |01 0A                  |03 00 00 00
860
@end example
861

862
@node protocol functions, protocol version 2, fieldtype codes
863 864
@section Functions used to implement the protocol

865 866 867
@c This should be merged with the above one and changed to texi format

@example
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

Raw packets
-----------

- The my_net_xxxx() functions handles the packaging of a stream of data
  into a raw packet that contains a packet number, length and data.

- This is implemented for the server in sql/net_serv.cc.
  The client file, libmysql/net.c, is symlinked to this file

The important functions are:

my_net_write()		Store a packet (= # number of bytes) to be sent
net_flush()		Send the packets stored in the buffer
net_write_command()	Send a command (1 byte) + packet to the server.
my_net_read()		Read a packet


Include files
-------------

- include/mysql.h is included by all MySQL clients.  It includes the
  MYSQL and MYSQL_RES structures.
- include/mysql_com.h is include by mysql.h and mysql_priv.h (the
  server) and includes a lot of common functions and structures to
  handle the client/server protocol.


Packets from server to client:
-----------------------------

sql/net_pkg.cc:

 - Sending of error packets
 - Sending of OK packets (= end of data)
 - Storing of values in a packet


sql/sql_base.cc:

 - Function send_fields() sends the field description to the client.

sql/sql_show.cc:

 - Sends results for a lot of SHOW commands, including:
   SHOW DATABASES [like 'wildcard']
   SHOW TABLES    [like 'wildcard']


Packets from client to server:
------------------------------

This is done in libmysql/libmysql.c

The important ones are:

- mysql_real_connect()		Connects to a mysqld server
- mysql_real_query()		Sends a query to the server and
				reads the ok packet or columns header.
- mysql_store_result()		Read a result set from the server to memory
- mysql_use_result()		Read a result set row by row from the server.

- net_safe_read()		Read a packet from the server with
				error handling.
- net_field_length()		Reads the length of a packet string.
- simple_command()		Sends a command/query to the server.



Connecting to mysqld (the MySQL server)
---------------------------------------

- On the client side: libmysql/libmysql.c::mysql_real_connect().
- On the server side: sql/sql_parse.cc::check_connections()

The packets sent during a connection are as follows

Server:  Send greeting package (includes server capabilites, server
	 version and a random string of bytes to be used to scramble
	 the password.
Client:  Sends package with client capabilites, user name, scrambled
	 password, database name

Server:  Sends ok package or error package.

Client:  If init command specified, send it t the server and read
	 ok/error package.


Password functions
------------------

The passwords are scrambled to a random number and are stored in hex
format on the server.

The password handling is done in sql/password.c. The important
function is 'scramble()', which takes the a password in clear text
and uses this to 'encrypt' the random string sent by the server
to a new message.

The encrypted message is sent to the server which uses the stored
random number password to encrypt the random string sent to the
client. If this is equal to the new message the client sends to the
server then the password is accepted.
972
@end example
973

974
@node protocol version 2, 4.1 protocol changes, protocol functions
975 976
@section Another description of the protocol

977
@c This should be merged with the above one and changed to texi format.
978

979
@example
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
*****************************
*
* PROTOCOL OVERVIEW
*
*****************************

The MySQL protocol is relatively simple, and is designed for high performance 
through minimisation of overhead, and extensibility through versioning and 
options flags. It is a request-response protocol, and does not allow 
multitasking or multiplexing over a single connection. There are two packet
formats, 'raw' and 'compressed' (which is used when both client and
server support zlib compression, and the client requests that data be
compressed):

* RAW PACKET, shorter than 16 M *

+-----------------------------------------------+
| Packet Length | Packet no     | Data          |
| 3 Bytes       | 1 Byte        | n Bytes       |
+-----------------------------------------------+
^                               ^
|          'HEADER'             |
+-------------------------------+


 * Packet Length: Calculated with int3store. See include/global.h for 
                  details. The basic computation is length = byte1 + 
                  (256 * byte2) + (256 * 256 * byte3). The max packetsize 
                  can be 16 MB.

 * Packet no:     The packet number is incremented for each sent packet.
                  The first packet for each query from the client
		  starts with 0.

 * Data:          Specific to the operation being performed. Most often
                  used to send string data, such as a SQL query.

* COMPRESSED PACKET *

+---------------------------------------------------+-----------------+
| Packet Length | Packet no | Uncomp. Packet Length | Compressed Data |
| 3 Bytes       | 1 Byte    | 3 Bytes               | n bytes         |
+---------------------------------------------------+-----------------+
^                                                   ^
|                   'HEADER'                        |
+---------------------------------------------------+
 
 * Packet Length: Calculated with int3store. See include/my_global.h for 
                  details. The basic computation is length = byte1 + 
                  (256 * byte2) + (256 * 256 * byte3). The max packetsize 
                  can be 16 MB.

 * Packet no:     The packet number is incremented for each sent packet.
                  The first packet starts with 0.

 * Uncomp. Packet Length: The length of the original, uncompressed packet
   If this is zero then the data is not compressed.
   
 * Compressed Data: The original packet, compressed with zlib compression


When using the compressed protocol, the client/server will only compress
send packets where the new packet is smaller than the not compressed one.
In other words, some packets may be compressed while others will not.

The 'compressed data' is one or more packets in *RAW PACKET* format.

*****************************
*
* FLOW OF EVENTS
*
*****************************

To understand how a client communicates with a MySQL server, it is easiest 
to start with a high-level flow of events. Each event section will then be 
followed by details of the exact contents of each type of packet involved
in the event flow.

*                          *
* CONNECTION ESTABLISHMENT *
*                          *

Clients connect to the server via a TCP/IP socket (port 3306 by default), a 
Unix Domain Socket, or named pipes (on Windows). Once connected, the 
following connection establishment sequence is followed:

+--------+                                                           +--------+
| Client |                                                           | Server |
+--------+                                                           +--------+
    |                                                                     |
    |    Handshake initialisation, including MySQL server version,        |
    |    protocol version and options supported, as well as the seed      |
    |    for the password hash                                            |
    |                                                                     |
    |   <--------------------------------------------------------------   |
    |                                                                     |
    |    Client options supported, max packet size for client             |
    |    username, password crypted with seed from server, database       |
    |    name.                                                            |
    |                                                                     |
    |   -------------------------------------------------------------->   |
    |                                                                     |
    |    'OK' packet if authentication succeeds, 'ERROR' packet if        |
    |    authentication fails.                                            |
    |                                                                     |
    |   <--------------------------------------------------------------   |
    |                                                                     |



* HANDSHAKE INITIALISATION PACKET *


+--------------------------------------------------------------------+
| Header        | Prot. Version | Server Version String | 0x00       |  
|               | 1 Byte        | n bytes		| 1 byte     |
|--------------------------------------------------------------------|
| Thread Number | Crypt Seed | 0x00    | CLIENT_xxx options          |
|               |            |         | supported by server         |
| 4 Bytes       | 8 Bytes    | 1 Byte  | 2 Bytes                     |
|--------------------------------------------------------------------|
| Server charset no.  | Server status variables | 0x00 padding       |
| 1 Byte              | 2 Bytes                 | 13 bytes           |
+--------------------------------------------------------------------+

 * Protocol version (currently '10')
 * Server Version String (e.g. '4.0.5-beta-log').  Can be any length as
   it's followed by a 0 byte.
 * Thread Number - ID of server thread handling this connection
 * Crypt seed - seed used to crypt password in auth packet from client
 * CLIENT_xxx options - see include/mysql_com.h
 * Server charset no. - Index of charset in use by server
 * Server status variables - see include/mysql_com.h
 * The padding bytes are reserverd for future extensions to the protocol

* CLIENT AUTH PACKET *


+--------------------------------------------------------------------+
| Header        | CLIENT_xxx options supported | max_allowed_packet  |
|               | by client                    | for client          |
|               | 2 Bytes                      | 3 bytes             |
|--------------------------------------------------------------------|
| User Name | 0x00   | Crypted Password | 0x00   | Database Name     |
| n Bytes   | 1 Byte | 8 Bytes          | 1 Byte | n Bytes           |
|--------------------------------------------------------------------|
| 0x00                                                               |
| 1 Byte                                                             |
+--------------------------------------------------------------------+

 * CLIENT_xxx options that this client supports:

#define CLIENT_LONG_PASSWORD    1       /* new more secure passwords */
#define CLIENT_FOUND_ROWS       2       /* Found instead of affected rows */
#define CLIENT_LONG_FLAG        4       /* Get all column flags */
#define CLIENT_CONNECT_WITH_DB  8       /* One can specify db on connect */
#define CLIENT_NO_SCHEMA        16      /* Don't allow database.table.column */
#define CLIENT_COMPRESS         32      /* Can use compression protocol */
#define CLIENT_ODBC             64      /* Odbc client */
#define CLIENT_LOCAL_FILES      128     /* Can use LOAD DATA LOCAL */
#define CLIENT_IGNORE_SPACE     256     /* Ignore spaces before '(' */
#define CLIENT_INTERACTIVE      1024    /* This is an interactive client */
#define CLIENT_SSL              2048     /* Switch to SSL after handshake */
#define CLIENT_IGNORE_SIGPIPE   4096     /* IGNORE sigpipes */
#define CLIENT_TRANSACTIONS     8192    /* Client knows about transactions */

 * max_allowed_packet for the client (in 'int3store' form)
 * User Name - user to authenticate as.  Is followed by a null byte.
 * Crypted Password - password crypted with seed given in packet from
                      server, see scramble() in sql/password.c
 * Database name (optional) - initial database to use once connected
   Is followed by a null byte

At the end of every client/server exchange there is either an 'OK' packet
or an 'ERROR' packet sent from the server. To determine whether a packet is
an 'OK' packet, or an 'ERROR' packet, check if the first byte (after the 
header) is 0xFF. If it has the value of 0xFF, the packet is an 'ERROR'
packet.


* OK PACKET *

For details, see sql/net_pkg.cc::send_ok()

+-----------------------------------------------+
| Header        | No of Rows    | Affected Rows |
|               | 1 Byte        | 1-9 Byte      |
|-----------------------------------------------|
| ID (last_insert_id)   | Status | Length       |
| 1-9 Byte              | 2 Byte | 1-9 Byte     |
|-----------------------------------------------|
| Messagetext                                   |
| n Byte                                        |
+-----------------------------------------------+

 * Number of rows, always 0 
 * Affected rows
 * ID (last_insert_id) - value for auto_increment column (if any) 
 * Status (usually 0)

In general, in the MySQL protocol, fields in a packet that that 
represent numeric data, such as lengths, that are labeled as '1-9' 
bytes can be decoded by the following logic:

	If the first byte is '251', the
        corresponding column value is NULL (only appropriate in 
        'ROW DATA' packets).

	If the first byte is '252', the value stored can be read
        from the following 2 bytes as a 16-bit integer.
                

        If the first byte is '253' the value stored can be read
        from the following 4 bytes as a 32-bit long integer

          
        If the first byte is '254', the value stored can be read
        from the following 8 bytes as a 64-byte long
                
	Otherwise (values 0-250), the value stored is the value of the
	first byte itself.


If the OK-packet includes a message:

 * Length of message
 * Message Text


* ERROR PACKET *

+-----------------------------------------------+
| Header        | Status code   | Error no      |
|               | 1 Byte        | 2 Byte        |
|-----------------------------------------------|
| Messagetext                          |        |
| n Byte                               |        |
+-----------------------------------------------+

 * Status code (0xFF = ERROR)
 * Error number (is only sent to 3.23 and newer clients)
 * Error message text (ends at end of packet)

Note that the error message is not null terminated.
The client code can however assume that the packet ends with a null
as my_net_read() will always add an end-null to all read packets to
make things easier for the client.

Example:

Packet dump of client connecting to server:

+------------------------- Protocol Version (10)
|
|  +---------------------- Server Version String (0x00 terminated)
|  |
|  |
0a 34 2e 30 2e 35 2d 62     . 4 . 0 . 5 - b 
65 74 61 2d 6c 6f 67 00     e t a - l o g . 
15 00 00 00 2b 5a 65 6c     . . . . + Z e l 
 |           |
 |           +------------ First 4 bytes of crypt seed
 | 
 +------------------------ Thread Number

+------------------------- Last 4 bytes of crypt seed
|
|                +-------- CLIENT_XXX Options supported by server
|                |
|              +-+--+ +--- Server charset index
|              |    | |
6f 69 41 46 00 2c 28 08     o i A F . , ( . 
02 00 00 00 00 00 00 00     . . . . . . . . 
|  |
|  +---------------------- 0x00 padding begins
|
+------------------------- Server status (0x02 = 
                           SERVER_STATUS_AUTOCOMMIT)

00 00 00 00 00 00 00 00     . . . . . . . . 

* Client Authentication Response (Username 'test', no database
  selected) *

    +--------------------- Packet Length (0x13 = 19 bytes)
    |
    |     +--------------- Packet Sequence #
    |     |
    |     |   +----------- CLIENT_XXX Options supported by client 
          |   |
+---+---+ | +-+-+
|       | | |   |
13 00 00 01 03 00 1e 00     . . . . . . . . 
00 74 65 73 74 00 48 5e     . t e s t . H ^
   |          |   |
   +----+-----+   +------- Scrambled password, 0x00 terminated
        |
        +----------------- Username, 0x00 terminated
  
57 4a 4e 41 4a 4e 00 00     W J N A J N . . 
00                          . 


>From this point on, the server waits for 'commands' from the client
which include queries, database shutdown, quit, change user, etc (see
the COM_xxxx values in include/mysql_com.h for the latest 
command codes). 

*                    *
* COMMAND PROCESSING *
*                    *

+--------+                                                           +--------+
| Client |                                                           | Server |
+--------+                                                           +--------+
    |                                                                     |
    |    A command packet, with a command code, and string data           |
    |    when appropriate (e.g. a query), (see the COM_xxxx values        |
    |    in include/mysql_com.h for the command codes)                    |
    |                                                                     |
    |   -------------------------------------------------------------->   |
    |                                                                     |
    |    A 'RESULT' packet if the command completed successfully,         |
    |    an 'ERROR' packet if the command failed. 'RESULT' packets        |
    |    take different forms (see the details following this chart)      |
    |    depending on whether or not the command returns rows.            |
    |                                                                     |
    |   <--------------------------------------------------------------   |
    |                                                                     |
    |    n 'FIELD PACKET's (if rows are returned)                         |
    |                                                                     |
    |   <--------------------------------------------------------------   |
    |                                                                     |
    |    'LAST DATA' packet                                               |
    |                                                                     |
    |   <--------------------------------------------------------------   |
    |                                                                     |
    |    n 'ROW PACKET's (if rows are returned)                           |
    |                                                                     |
    |   <--------------------------------------------------------------   |
    |                                                                     |
    |    'LAST DATA' packet                                               |
    |                                                                     |
    |   <--------------------------------------------------------------   |
    |                                                                     |


* Command Packet *

+------------------------------------------------------+
| Header        | Command type | Query (if applicable) |
|               | 1 Byte       | n Bytes               |
+------------------------------------------------------+

 * Command type:  (e.g.0x03 = query, see the COM_xxxx values in 
                   include/mysql_com.h)
 * Query (if applicable)

Note that my_net_read() null-terminates all packets on the
receiving side of the channel to make it easier for the code
examining the packets.

The current command codes are:

   0x00   COM_SLEEP
   0x01   COM_QUIT
   0x02   COM_INIT_DB
   0x03   COM_QUERY
   0x04   COM_FIELD_LIST
   0x05   COM_CREATE_DB
   0x06   COM_DROP_DB
   0x07   COM_REFRESH
   0x08   COM_SHUTDOWN
   0x09   COM_STATISTICS
   0x0a   COM_PROCESS_INFO
   0x0b   COM_CONNECT
   0x0c   COM_PROCESS_KILL
   0x0d   COM_DEBUG
   0x0e   COM_PING
   0x0f   COM_TIME
   0x10   COM_DELAYED_INSERT
   0x11   COM_CHANGE_USER
   0x12   COM_BINLOG_DUMP
   0x13   COM_TABLE_DUMP 
   0x14   COM_CONNECT_OUT
   0x15   COM_REGISTER_SLAVE

* Result Packet *

Result packet for a command returning _no_ rows:

+-----------------------------------------------+
| Header        | Field Count   | Affected Rows |
|               | 1-9 Bytes     | 1-9 Bytes     |
|-----------------------------------------------|
| ID (last_insert_id)   | Server Status         |
| 1-9 Bytes             | 2 Bytes               |
+-----------------------------------------------+

 * Field Count: Has value of '0' for commands returning _no_ rows
 * Affected rows: Count of rows affected by INSERT/UPDATE/DELETE, etc.
 * ID: value of auto_increment column in row (if any).  0 if 
 * Server Status: Usually 0

Result packet for a command returning rows:

+-------------------------------+
| Header        | Field Count   |
|               | 1-9 Bytes     |
+-------------------------------+

 * Field Count: number of columns/fields in result set,
                 (packed with net_store_length() in sql/net_pkg.cc)

This is followed by as many packets as the number of fields ('Field Count')
that contain the metadata for each column/field (see unpack_fields() in 
libmysql/libmysql.c):


* FIELD PACKET *

+-----------------------------------------------+
| Header        | Table Name		        |
|               | length-coded-string           |
|-----------------------------------------------|
| Field Name					|
| length-code-string				|
|-----------------------------------------------|
| Display length of field
| length-coded-binary (4 bytes)			|
|-----------------------------------------------|
| Field Type (enum_field_types in mysql_com.h)  |
| length-coded-binary (2 bytes)			|
|-----------------------------------------------|
| Field Flags	                | Decimal Places|
| length-coded-binary (3 bytes) | 1 Byte        |
+--------------+-------------+------------------+

 * A length coded string is a string where we first have a packet
   length (1-9 bytes, packed_with net_store_length()) followed
   by a string.
 * A length coded binary is a length (1 byte) followed by an integer
   value in low-byte-first order.  For the moment this type is always
   fixed length in this packet.

 * Table Name - the name of the table the column comes from
 * Field Name - the name of the column/field
 * Display length of field - length of field
 * Field Type - Type of field, see enum_field_types in 
                include/mysql_com.h

   Current field types are:

      0x00   FIELD_TYPE_DECIMAL 
      0x01   FIELD_TYPE_TINY
      0x02   FIELD_TYPE_SHORT  
      0x03   FIELD_TYPE_LONG
      0x04   FIELD_TYPE_FLOAT  
      0x05   FIELD_TYPE_DOUBLE
      0x06   FIELD_TYPE_NULL
      0x07   FIELD_TYPE_TIMESTAMP
      0x08   FIELD_TYPE_LONGLONG
      0x09   FIELD_TYPE_INT24
      0x0a   FIELD_TYPE_DATE   
      0x0b   FIELD_TYPE_TIME
      0x0c   FIELD_TYPE_DATETIME
      0x0d   FIELD_TYPE_YEAR
      0x0e   FIELD_TYPE_NEWDATE
      0xf7   FIELD_TYPE_ENUM
      0xf8   FIELD_TYPE_SET
      0xf9   FIELD_TYPE_TINY_BLOB
      0xfa   FIELD_TYPE_MEDIUM_BLOB
      0xfb   FIELD_TYPE_LONG_BLOB
      0xfc   FIELD_TYPE_BLOB
      0xfd   FIELD_TYPE_VAR_STRING
      0xfe   FIELD_TYPE_STRING
      0xff   FIELD_TYPE_GEOMETRY

 * Field Flags - NOT_NULL_FLAG, PRI_KEY_FLAG, xxx_FLAG in 
                 include/mysql_com.h


Note that the packet format in 4.1 has slightly changed to allow more values.


* ROW PACKET *

+-----------------------------------------------+
| Header        | Data Length   | Column Data   | ....for each column
|               | 1-9 Bytes     | n Bytes       |
+-----------------------------------------------+

 * Data Length: (packed with net_store_length() in sql/net_pkg.cc)
                
		If 'Data Length' == 0, this is an 'ERROR PACKET'.
		
 * Column Data: String representation of data. MySQL always sends result set
                data as strings.

* LAST DATA PACKET *

Packet length is < 9 bytes, and first byte is 0xFE

+--------+
| 0xFE   |
| 1 Byte |
+--------+

Examples:

***********
*
* INITDB Command
*
***********

A client issuing an 'INITDB' (select the database to use) command,
followed by an 'OK' packet with no rows and no affected rows from
the server:

* INITDB (select database to use) 'COMMAND' Packet *

    +--------------------- Packet Length (5 bytes)
    |
    |     +--------------- Packet Sequence #
    |     |
    |     |  +------------ Command # (INITDB = 0x02)
          |  |
+---+---+ |  | +---------- Beginning of query data
|       | |  | |
05 00 00 00 02 74 65 73     . . . . . t e s 
74                          t 

* 'OK' Packet with no rows, and no rows affected *

    +--------------------- Packet Length (3 bytes)
    |
    |     +--------------- Packet Sequence #
    |     | 
+---+---+ |
|       | |
03 00 00 01 00 00 00        . . . . . . .


***********
*
* SELECT query example
*
***********

Client issuing a 'SELECT *' query on the following table:

    CREATE TABLE number_test (minBigInt bigint, 
                              maxBigInt bigint, 
                              testBigInt bigint)

* 'COMMAND' Packet with QUERY (select ...) *

    +--------------------- Packet Length (26)
    |
    |     +--------------- Packet Sequence #
    |     |
    |     |  +------------ Command # (QUERY = 0x03)
          |  |
+---+---+ |  | +---------- Beginning of query data
|       | |  | |
1a 00 00 00 03 53 45 4c     . . . . . S E L 
45 43 54 20 2a 20 66 72     E C T . * . f r 
6f 6d 20 6e 75 6d 62 65     o m . n u m b e 
72 5f 74 65 73 74           r _ t e s t 


and receiving an 'OK' packet with a 'FIELD COUNT' of 3


* 'OK' Packet with 3 fields *

    +--------------------- Packet Length (3 bytes)
    |
    |     +--------------- Packet Sequence #
    |     | 
+---+---+ |
|       | |
01 00 00 01 03              . . . . . 

Followed immediately by 3 'FIELD' Packets. Note, the individual packets 
are delimitted by =======, so that all fields can be annotated in the first
'FIELD' packet example:

=============================================================

    +--------------------- Packet Length (0x1f = 31 bytes)
    |
    |     +--------------- Packet Sequence #
    |     | 
    |     |  +------------ Block Length (0x0b = 11 bytes)
    |     |  |   
+---+---+ |  |  +--------- Table Name (11 bytes long)
|       | |  |  |
1f 00 00 02 0b 6e 75 6d     . . . . . n u m  
62 65 72 5f 74 65 73 74     b e r _ t e s t 

 +------------------------ Block Length (9 bytes)
 |
 |  +--------------------- Column Name (9 bytes long)
 |  |
09 6d 69 6e 42 69 67 49     . m i n B i g I     
6e 74 03 14 00 00 01 08     n t . . . . . .
       | |       | |  |
       | +---+---+ |  +--- Field Type (0x08 = FIELD_TYPE_LONGLONG)
       |     |     |
       |     |     +------ Block Length (1)
       |     |
       |     +--------------- Display Length (0x14 = 20 chars)
       |
       +------------------ Block Length (3)

 +------------------------ Block Length (2)
 |
 |   +-------------------- Field Flags (0 - no flags set)
 |   | 
 | +---+  +--------------- Decimal Places (0)
 | |   |  |
02 00 00 00                 . . . .                                  

=============================================================

'FIELD' packet for the 'number_Test.maxBigInt' column

1f 00 00 03 0b 6e 75 6d     . . . . . n u m
62 65 72 5f 74 65 73 74     b e r _ t e s t
09 6d 61 78 42 69 67 49     . m a x B i g I
6e 74 03 14 00 00 01 08     n t . . . . . .
02 00 00 00                 . . . .
        
=============================================================                    

'FIELD' packet for the 'number_test.testBigInt' column

20 00 00 04 0b 6e 75 6d     . . . . . n u m
62 65 72 5f 74 65 73 74     b e r _ t e s t 
0a 74 65 73 74 42 69 67     . t e st B i g
49 6e 74 03 14 00 00 01     I n t . . . . .
08 02 00 00 00              . . . . .
============================================================= 

Followed immediately by one 'LAST DATA' packet:

fe 00                       . .

Followed immediately by 'n' row packets (in this case, only
one packet is sent from the server, for simplicity's sake):


    +--------------------- Packet Length (0x52 = 82 bytes)
    |
    |     +--------------- Packet Sequence #
    |     | 
    |     |  +------------ Data Length (0x14 = 20 bytes)
    |     |  |   
+---+---+ |  |  +--------- String Data '-9223372036854775808'
|       | |  |  |          (repeat Data Length/Data sequence)

52 00 00 06 14 2d 39 32     . . . . . - 9 2
32 33 33 37 32 30 33 36     2 3 3 7 2 0 3 6
38 35 34 37 37 35 38 30     8 5 4 7 7 5 8 0
38 13 39 32 32 33 33 37     8 . 9 2 2 3 3 7
32 30 33 36 38 35 34 37     2 0 3 6 8 5 4 7
37 35 38 30 37 0a 36 31     7 5 8 0 7 . 6 1
34 37 34 38 33 36 34 37     4 7 4 8 3 6 4 7

Followed immediately by one 'LAST DATA' packet:

fe 00                       . .
1654
@end example
1655 1656


1657 1658 1659 1660 1661 1662
@c The Index was empty, and ugly, so I removed it. (jcole, Sep 7, 2000)

@c @node Index
@c @unnumbered Index

@c @printindex fn
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1663

1664 1665
@c @node 4.1 protocol,,,
@c @chapter MySQL 4.1 protocol
1666

1667
@node 4.1 protocol changes, 4.1 field packet, protocol version 2
1668 1669
@section Changes to 4.0 protocol in 4.1

1670
All basic packet handling is identical to 4.0. When communication
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
with an old 4.0 or 3.x client we will use the old protocol.

The new things that we support with 4.1 are:

@itemize @bullet
@item
Warnings
@item
Prepared statements
@item
1681
Binary protocol (will be faster than the current protocol that
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
converts everything to strings)
@end itemize


What has changed in 4.1 are:

@itemize @bullet
@item
A lot of new field information (database, real table name etc)
@item
The 'ok' packet has more status fields
@item
The 'end' packet (send last for each result set) now contains some
extra information
@item
New protocol for prepared statements.  In this case all parameters and
results will sent as binary (low-byte-first).
@end itemize


1702
@node 4.1 field packet, 4.1 field desc, 4.1 protocol changes
1703
@section 4.1 field description packet
1704

1705 1706 1707
The field description packet is sent as a response to a query that
contains a result set.  It can be distinguished from a ok packet by
the fact that the first byte can't be 0 for a field packet.
1708
@xref{4.1 ok packet}.
1709

1710
The header packet has the following structure:
1711 1712 1713 1714 1715 1716 1717 1718

@multitable @columnfractions .10 .90
@item Size @tab Comment
@item 1-9  @tab Number of columns in result set (never 0)
@item 1-9  @tab Extra information sent be some command (SHOW COLUMNS
uses this to send the number of rows in the table)
@end multitable

1719
This packet is always followed by a field description set.
1720 1721
@xref{4.1 field desc}.

1722
@node 4.1 field desc, 4.1 ok packet, 4.1 field packet
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
@section 4.1 field description result set

The field description result set contains the meta info for a result set.

@multitable @columnfractions .20 .80
@item Type   @tab Comment
@item string @tab Database name
@item string @tab Table name alias (or table name if no alias)
@item string @tab Real table name
@item string @tab Alias for column name (or column name if not used)
@item 3 byte int @tab Length of column definition
@item 1 byte int @tab Enum value for field type
@item 3 byte int @tab 2 byte column flags (NOT_NULL_FLAG etc..) + 1 byte number of decimals.
@item string int @tab Default value, only set when using mysql_list_fields().
@end multitable


1740
@node 4.1 ok packet, 4.1 end packet, 4.1 field desc
1741
@section 4.1 ok packet
1742

1743
The ok packet is the first that is sent as an response for a query
1744 1745
that didn't return a result set.

1746
The ok packet has the following structure:
1747 1748 1749

@multitable @columnfractions .10 .90
@item Size @tab Comment
1750
@item 1	  @tab  0 ; Marker for ok packet
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
@item 1-9 @tab	Affected rows
@item 1-9 @tab  Last insert id (0 if one wasn't used)
@item 2   @tab  Server status; Can be used by client to check if we are inside an transaction
@item 2	  @tab  Warning count
@item 1-9 @tab  Message length (optional)
@item xxx @tab  Message (optional)
@end multitable

Size 1-9 means that the parameter is packed in to 1-9 bytes depending on
the value.  (See function sql/net_pkg.cc::net_store_length).

The message is optional.  For example for multi line INSERT it
contains a string for how many rows was inserted / deleted.


1766
@node 4.1 end packet, 4.1 error packet, 4.1 ok packet
1767
@section 4.1 end packet
1768

1769
The end packet is sent as the last packet for
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779

@itemize @bullet
@item
End of field information
@item
End of parameter type information
@item
End of result set
@end itemize

1780
The end packet has the following structure:
1781 1782 1783

@multitable @columnfractions .10 .90
@item Size @tab Comment
1784
@item 1	   @tab 254  ; Marker for EOF packet
1785 1786 1787 1788
@item 2	   @tab Warning count
@item 2	   @tab Status flags (For flags like SERVER_STATUS_MORE_RESULTS)
@end multitable

1789
Note that a normal packet may start with byte 254, which means
1790 1791 1792 1793 1794
'length stored in 9 bytes'.  One can different between these cases
by checking the packet length < 9 bytes (in which case it's and end
packet).


1795
@node 4.1 error packet, 4.1 prep init, 4.1 end packet
1796
@section 4.1 error packet.
1797

1798 1799
The error packet is sent when something goes wrong.
The error packet has the following structure:
1800 1801 1802

@multitable @columnfractions .10 .90
@item Size  @tab Comment
1803 1804
@item 1	    @tab 255  Error packet marker
@item 2	    @tab Error code
1805 1806 1807
@item 1-255 @tab Null terminated error message
@end multitable

1808 1809
The client/server protocol is designed in such a way that a packet
can only start with 255 if it's an error packet.
1810 1811


1812
@node 4.1 prep init, 4.1 long data, 4.1 error packet
1813
@section 4.1 prepared statement init packet
1814

1815
This is the return packet when one sends a query with the COM_PREPARE
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
command.

@multitable @columnfractions .10 .90
@item Size @tab Comment
@item 4	   @tab Statement handler id
@item 2	   @tab Number of columns in result set
@item 2	   @tab Number of parameters in query
@end multitable

After this, there is a packet that contains the following for each
parameter in the query:

@multitable @columnfractions .10 .90
@item Size @tab Comment
@item 2	@tab Enum value for field type. (MYSQL_TYPE_UNKNOWN if not known)
@item 2 @tab 2 byte column flags (NOT_NULL_FLAG etc)
@item 1 @tab Number of decimals
@item 4 @tab Max column length.
1834
@end multitable
1835 1836 1837 1838 1839 1840

Note that the above is not yet in 4.1 but will be added this month.

As MySQL can have a parameter 'anywhere' it will in many cases not be
able to provide the optimal information for all parameters.

1841 1842
If number of columns, in the header packet, is not 0 then the
prepared statement will contain a result set. In this case the packet
1843
is followed by a field description result set. @xref{4.1 field desc}.
1844 1845


1846
@node 4.1 long data, 4.1 execute, 4.1 prep init
1847 1848 1849 1850 1851 1852 1853
@section 4.1 long data handling

This is used by mysql_send_long_data() to set any parameter to a string
value.  One can call mysql_send_long_data() multiple times for the
same parameter; The server will concatenate the results to a one big
string.

1854
The server will not require an end packet for the string.
1855 1856 1857 1858
mysql_send_long_data() is responsible updating a flag that all data
has been sent. (Ie;  That the last call to mysql_send_long_data() has
the 'last_data' flag set).

1859
This packet is sent from client -> server:
1860 1861 1862 1863 1864 1865

@multitable @columnfractions .10 .90
@item Size @tab Comment
@item 4	@tab Statement handler
@item 2 @tab Parameter number
@item 2 @tab Type of parameter  (not used at this point)
1866
@item # @tab data (Rest of packet)
1867
@end multitable
1868

1869
The server will NOT send an @code{ok} or @code{error} packet in
1870 1871 1872
responce for this.  If there is any errors (like to big string), one
will get the error when calling execute.

1873
@node 4.1 execute, 4.1 binary result, 4.1 long data
1874 1875 1876
@section 4.1 execute

On execute we send all parameters to the server in a COM_EXECUTE
1877
packet.
1878

1879
The packet contains the following information:
1880 1881 1882

@multitable @columnfractions .30 .70
@item Size @tab Comment
1883
@item (param_count+9)/8 @tab Null bit map (2 bits reserved for protocol)
1884 1885 1886 1887 1888
@item 1	   @tab new_parameter_bound flag.  Is set to 1 for first
execute or if one has rebound the parameters.
@item 2*param_count     @tab Type of parameters (only given if new_parameter_bound flag is 1)
@item #    @tab Parameter data, repeated for each parameter that are
NOT NULL and not used with mysql_send_long_data().
1889
@end multitable
1890 1891 1892 1893 1894 1895 1896 1897 1898

The null-bit-map is for all parameters (including parameters sent with
'mysql_send_long_data). If parameter 0 is NULL, then bit 0 in the
null-bit-map should be 1 (ie:  first byte should be 1)

The parameters are stored the following ways:

@multitable @columnfractions .20 .10 .70
@item Type    @tab Size @tab Comment
1899
@item tinyint @tab 1	@tab One byte integer
1900 1901 1902 1903 1904 1905 1906 1907
@item short   @tab 2	@tab
@item int     @tab 4	@tab
@item longlong @tab 8	@tab
@item float   @tab 4	@tab
@item double  @tab 8	@tab
@item string  @tab 1-9 + # @tab Packed string length + string
@end multitable

1908
The result for this will be either an ok packet or a binary result
1909 1910
set.

1911
@node 4.1 binary result, , 4.1 execute
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
@section 4.1 binary result set

A binary result are sent the following way.

For each result row:

@itemize
@item
null bit map with first two bits set to 01 (bit 0,1 value 1)
@item
1922
parameter data, repeated for each not null result column.
1923 1924 1925
@end itemize

The idea with the reserving two bits in the null map is that we can
1926
use standard error (first byte 255) and ok packets (first byte 0)
1927 1928 1929 1930 1931 1932 1933 1934
to end a result sets.

Except that the null-bit-map is shifted two steps, the server is
sending the data to the client the same way that the server is sending
bound parameters to the client.  The server is always sending the data
as type given for 'column type' for respective column.  It's up to the
client to convert the parameter to the requested type.

1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
DATETIME, DATE and TIME are sent to the server in a binary format as follows:

@multitable @columnfractions .20 .10 .70
@item Type    @tab Size @tab Comment
@item date    @tab 1 + 0-11 @tab Length + 2 byte year, 1 byte MMDDHHMMSS, 4 byte billionth of a second
@item datetime    @tab 1 + 0-11 @tab Length + 2 byte year, 1 byte MMDDHHMMSS, 4 byte billionth of a second
@item time    @tab 1 + 0-14 @tab Length + sign (0 = pos, 1= neg), 4 byte days, 1 byte HHMMDD, 4 byte billionth of a second
@end multitable

The first byte is a length byte and then comes all parameters that are
not 0. (Always counted from the beginning).

1947
@node Fulltext Search, MyISAM Record Structure, protocol, Top
1948 1949 1950 1951 1952 1953 1954
@chapter Fulltext Search in MySQL

Hopefully, sometime there will be complete description of
fulltext search algorithms.
Now it's just unsorted notes.

@menu
1955
* Weighting in boolean mode::   
1956 1957
@end menu

1958
@node Weighting in boolean mode,  , Fulltext Search, Fulltext Search
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
@section Weighting in boolean mode

The basic idea is as follows: in expression
@code{A or B or (C and D and E)}, either @code{A} or @code{B} alone
is enough to match the whole expression. While @code{C},
@code{D}, and @code{E} should @strong{all} match. So it's
reasonable to assign weight 1 to @code{A}, @code{B}, and
@code{(C and D and E)}. And @code{C}, @code{D}, and @code{E}
should get a weight of 1/3.

Things become more complicated when considering boolean
operators, as used in MySQL FTB. Obvioulsy, @code{+A +B}
should be treated as @code{A and B}, and @code{A B} -
as @code{A or B}. The problem is, that @code{+A B} can @strong{not}
be rewritten in and/or terms (that's the reason why this - extended -
set of operators was chosen). Still, aproximations can be used.
@code{+A B C} can be approximated as @code{A or (A and (B or C))}
or as @code{A or (A and B) or (A and C) or (A and B and C)}.
Applying the above logic (and omitting mathematical
transformations and normalization) one gets that for
@code{+A_1 +A_2 ... +A_N B_1 B_2 ... B_M} the weights
should be: @code{A_i = 1/N}, @code{B_j=1} if @code{N==0}, and,
otherwise, in the first rewritting approach @code{B_j = 1/3},
and in the second one - @code{B_j = (1+(M-1)*2^M)/(M*(2^(M+1)-1))}.

The second expression gives somewhat steeper increase in total
weight as number of matched B's increases, because it assigns
higher weights to individual B's. Also the first expression in
much simplier. So it is the first one, that is implemented in MySQL.

1989

1990
@node MyISAM Record Structure, InnoDB Record Structure, Fulltext Search, Top
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
@chapter MyISAM Record Structure

@section Introduction

When you say:
@*

@strong{CREATE TABLE Table1 ...}
@*

MySQL creates files named Table1.MYD ("MySQL Data"), Table1.MYI
2002
("MySQL Index"), and Table1.frm ("Format"). These files will be in the
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
directory: @*
/<datadir>/<database>/
@*

For example, if you use Linux, you might find the files here (assume
your database name is "test"): @*
/usr/local/var/test
@*

And if you use Windows, you might find the files in this directory: @*
\mysql\data\test\
@*@*

Let's look at the .MYD Data file (MyISAM SQL Data file) more closely.

@table @strong
@item Page Size
Unlike most DBMSs, MySQL doesn't store on disk using pages. Therefore
you will not see filler space between rows. (Reminder: This does not
refer to BDB and INNODB tables, which do use pages).
@*

@item Record Header
The minimal record header is a set of flags:
@itemize @bullet
@item
"X bit"  =  0 if row is deleted, = 1 if row is not deleted
@item
"Null Bits"  =  0 if column is not NULL, = 1 if column is NULL
@item
"Filler Bits"  = 1
@end itemize
@end table
@*

2038 2039 2040 2041 2042 2043
The length of the record header is thus:@*
(1 + number of NULL columns + 7) / 8 bytes@*
After the header, all columns are stored in 
the order that they were created, which is the 
same order that you would get from SHOW COLUMNS.

2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
Here's an example. Suppose you say:
@*

@strong{CREATE TABLE Table1 (column1 CHAR(1), column2 CHAR(1), column3 CHAR(1))}
@*

@strong{INSERT INTO Table1 VALUES ('a', 'b', 'c')}
@*

@strong{INSERT INTO Table1 VALUES ('d', NULL, 'e')}
@*

A CHAR(1) column takes precisely one byte (plus one bit of overhead
that is assigned to every column -- I'll describe the details of
column storage later). So the file Table1.MYD looks like this:
@*

@strong{Hexadecimal Display of Table1.MYD file}@*
@code{
F1 61 62 63 00 F5 64 00 66 00              ... .abc..d e.
}
@*

Here's how to read this hexadecimal-dump display:@*
@itemize @bullet
@item
The hexadecimal numbers @code{F1 61 62 63 00 F5 64 20 66 00} are byte
values and the column on the right is an attempt to show the
same bytes in ASCII.
@item
The @code{F1} byte means that there are no null fields in the first row.
@item
The @code{F5} byte means that the second column of the second row is NULL.
@end itemize

(It's probably easier to understand the flag setting if you restate
@code{F5} as @code{11110101 binary}, and (a) notice that the third flag bit from the
right is @code{on}, and (b) remember that the first flag bit is the X bit.)
@*

There are complications -- the record header is more complex if there
are variable-length fields -- but the simple display shown in the
2086 2087
example is exactly what you'd see if you looked at the MySQL Data file 
with a debugger or a hexadecimal file dumper.
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
@*

@section Physical Attributes of Columns

Next I'll describe the physical attributes of each column in a row.
The format depends entirely on the data type and the size of the
column, so, for every data type, I'll give a description and an example.
@*

@table @strong
@item The character data types

@strong{CHAR}
@itemize @bullet
@item
Storage: fixed-length string with space padding on the right.
@item
Example: a CHAR(5) column containing the value 'A' looks like:@*
@code{hexadecimal 41 20 20 20 20} --  (length = 5, value = @code{'A    '})
@end itemize

@strong{VARCHAR}
@itemize @bullet
@item
Storage: variable-length string with a preceding length.
@item
Example: a VARCHAR(7) column containing 'A' looks like:@*
@code{hexadecimal 01 41}  --  (length = 1, value = @code{'A'})
@end itemize

@item The numeric data types

2120 2121
Important: MySQL almost always stores multi-byte binary numbers with 
the low byte first. This is called "little-endian" numeric storage;
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
it's normal on Intel x86 machines; MySQL uses it even for non-Intel
machines so that databases will be portable.
@*

@strong{TINYINT}
@itemize @bullet
@item
Storage: fixed-length binary, always one byte.
@item
Example: a TINYINT column containing 65 looks like:@*
@code{hexadecimal 41}  --  (length = 1, value = 65)
@end itemize

@strong{SMALLINT}
@itemize @bullet
@item
Storage: fixed-length binary, always two bytes.
@item
Example: a SMALLINT column containing 65 looks like:@*
@code{hexadecimal 41 00}  --  (length = 2, value = 65)
@end itemize

@strong{MEDIUMINT}
@itemize @bullet
@item
Storage: fixed-length binary, always three bytes.
@item
Example: a MEDIUMINT column containing 65 looks like:@*
@code{hexadecimal 41 00 00}  --  (length = 3, value = 65)
@end itemize

@strong{INT}
@itemize @bullet
@item
Storage: fixed-length binary, always four bytes.
@item
Example: an INT column containing 65 looks like:@*
@code{hexadecimal 41 00 00 00}  --  (length = 4, value = 65)
@end itemize

@strong{BIGINT}
@itemize @bullet
@item
Storage: fixed-length binary, always eight bytes.
@item
Example: a BIGINT column containing 65 looks like:@*
@code{hexadecimal 41 00 00 00 00 00 00 00}  --  (length = 8, value = 65)
@end itemize

@strong{FLOAT}
@itemize @bullet
@item
Storage: fixed-length binary, always four bytes.
@item
Example: a FLOAT column containing approximately 65 looks like:@*
@code{hexadecimal 00 00 82 42}  --  (length = 4, value = 65)
@end itemize

@strong{DOUBLE PRECISION}
@itemize @bullet
@item
Storage: fixed-length binary, always eight bytes.
@item
Example: a DOUBLE PRECISION column containing approximately 65 looks like:@*
@code{hexadecimal 00 00 00 00 00 40 50 40}  --  (length = 8, value = 65)
@end itemize

@strong{REAL}
@itemize @bullet
@item
Storage: same as FLOAT, or same as DOUBLE PRECISION, depending on setting of the --ansi switch.
@end itemize

@strong{DECIMAL}
@itemize @bullet
@item
Storage: fixed-length string, with a leading byte for the sign, if any.
@item
Example: a DECIMAL(2) column containing 65 looks like:@*
@code{hexadecimal 20 36 35}  --  (length = 3, value = @code{' 65'})
@item
Example: a DECIMAL(2) UNSIGNED column containing 65 looks like:@*
@code{hexadecimal 36 35}  --  (length = 2, value = @code{'65'})
@item
Example: a DECIMAL(4,2) UNSIGNED column containing 65 looks like:@*
@code{hexadecimal 36 35 2E 30 30}  --  (length = 5, value = @code{'65.00'})
@end itemize

@strong{NUMERIC}
@itemize @bullet
@item
Storage: same as DECIMAL.
@end itemize

@strong{BOOL}
@itemize @bullet
@item
Storage: same as TINYINT.
@end itemize

@item The temporal data types

@strong{DATE}
@itemize @bullet
@item
2227 2228
Storage: 3 byte integer, low byte first.
Packed as: 'day + month*32 + year*16*32'
2229
@item
2230 2231
Example: a DATE column containing '1962-01-02' looks like:@*
@code{hexadecimal 22 54 0F}
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
@end itemize

@strong{DATETIME}
@itemize @bullet
@item
Storage: eight bytes.
@item
Part 1 is a 32-bit integer containing year*10000 + month*100 + day.
@item
Part 2 is a 32-bit integer containing hour*10000 + minute*100 + second.
@item
Example: a DATETIME column for '0001-01-01 01:01:01' looks like:@*
@code{hexadecimal B5 2E 11 5A 02 00 00 00}
@end itemize

@strong{TIME}
@itemize @bullet
@item
2250 2251
Storage: 3 bytes, low byte first.
This is stored as seconds:  days*24*3600+hours*3600+minutes*60+seconds
2252
@item
2253 2254
Example: a TIME column containing '1 02:03:04' (1 day 2 hour 3 minutes and 4 seconds) looks like:@*
@code{hexadecimal 58 6E 01}
2255 2256 2257 2258 2259
@end itemize

@strong{TIMESTAMP}
@itemize @bullet
@item
2260 2261 2262
Storage: 4 bytes, low byte first.
Stored as unix @code{time()}, which is seconds since the Epoch
(00:00:00 UTC, January 1, 1970).
2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
@item
Example: a TIMESTAMP column containing '2003-01-01 01:01:01' looks like:@*
@code{hexadecimal 4D AE 12 23}
@end itemize

@strong{YEAR}
@itemize @bullet
@item
Storage: same as unsigned TINYINT with a base value of 0 = 1901.
@end itemize

@item Others

@strong{SET}
@itemize @bullet
@item
Storage: one byte for each eight members in the set.
@item
Maximum length: eight bytes (for maximum 64 members).
@item
This is a bit list. The least significant bit corresponds to the
first listed member of the set.
@item
Example: a SET('A','B','C') column containing 'A' looks like:@*
@code{01} --  (length = 1, value = 'A')
@end itemize

@strong{ENUM}
@itemize @bullet
@item
Storage: one byte if less than 256 alternatives, else two bytes.
@item
This is an index. The value 1 corresponds to the first listed
2296
alternative. (Note: ENUM always reserves 0 for an erroneous value. This
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
explains why 'A' is 1 instead of 0.)
@item
Example: an ENUM('A','B','C') column containing 'A' looks like:@*
@code{01}  --  (length = 1, value = 'A')
@end itemize

@item The Large-Object data types

Warning: Because TINYBLOB's preceding length is one byte long (the
size of a TINYINT) and MEDIUMBLOB's preceding length is three bytes
long (the size of a MEDIUMINT), it's easy to think there's some sort
of correspondence between the BLOB and the INT types. There isn't -- a
BLOB's preceding length is not four bytes long (the size of an INT).
@*

(NOTE TO SELF: BLOB storage has not been fully addressed here.)
@*

@strong{TINYBLOB}
@itemize @bullet
@item
Storage: variable-length string with a preceding one-byte length.
@item
Example: a TINYBLOB column containing 'A' looks like:@*
@code{hexadecimal 01 41}  --  (length = 2, value = 'A')
@end itemize

@strong{TINYTEXT}
@itemize @bullet
@item
Storage: same as TINYBLOB.
@end itemize

@strong{BLOB}
@itemize @bullet
@item
Storage: variable-length string with a preceding two-byte length.
@item
Example: a BLOB column containing 'A' looks like:@*
@code{hexadecimal 01 00 41}  --  (length = 2, value = 'A')
@end itemize

@strong{TEXT}
@itemize @bullet
@item
Storage: same as BLOB.
@end itemize

@strong{MEDIUMBLOB}
@itemize @bullet
@item
Storage: variable-length string with a preceding length.
@item
Example: a MEDIUMBLOB column containing 'A' looks like:@*
@code{hexadecimal 01 00 00 41}  --  (length = 4, value = 'A')
@end itemize

@strong{MEDIUMTEXT}
@itemize @bullet
@item
Storage: same as MEDIUMBLOB.
@end itemize

@strong{LONGBLOB}
@itemize @bullet
@item
Storage: variable-length string with a preceding four-byte length.
@item
Example: a LONGBLOB column containing 'A' looks like:@*
@code{hexadecimal 01 00 00 00 41}  --  (length = 5, value = 'A')
@end itemize

@strong{LONGTEXT}
@itemize @bullet
@item
Storage: same as LONGBLOB.
@end itemize

@end table

@section Where to Look For More Information

@strong{References:} @*
Most of the formatting work for MyISAM columns is visible
2381 2382 2383 2384
in the program /sql/field.cc in the source code directory. 
And in the MyISAM directory, the files that do formatting 
work for different record formats are: /myisam/mi_statrec.c, 
/myisam/mi_dynrec.c, and /myisam/mi_packrec.c.
2385 2386
@*

2387
@node InnoDB Record Structure,InnoDB Page Structure,MyISAM Record Structure,Top
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
@chapter InnoDB Record Structure

This page contains:
@itemize @bullet
@item
A high-altitude "summary" picture of the parts of a MySQL/InnoDB
record structure.
@item
A description of each part.
@item
An example.
@end itemize

After reading this page, you will know how MySQL/InnoDB stores a
physical record.
@*

@section High-Altitude Picture

The chart below shows the three parts of a physical record.

@multitable @columnfractions .10 .35

@item @strong{Name} @tab @strong{Size}
@item Field Start Offsets
@tab (F*1) or (F*2) bytes
@item Extra Bytes
@tab 6 bytes
@item Field Contents
@tab depends on content

@end multitable

Legend: The letter 'F' stands for 'Number Of Fields'.

The meaning of the parts is as follows:
@itemize @bullet
@item
The FIELD START OFFSETS is a list of numbers containing the
information "where a field starts".
@item
The EXTRA BYTES is a fixed-size header.
@item
The FIELD CONTENTS contains the actual data.
@end itemize

@strong{An Important Note About The Word "Origin"}@*
The "Origin" or "Zero Point" of a record is the first byte of the
Field Contents -- not the first byte of the Field Start Offsets. If
there is a pointer to a record, that pointer is pointing to the
Origin. Therefore the first two parts of the record are addressed by
subtracting from the pointer, and only the third part is addressed by
adding to the pointer.

@subsection FIELD START OFFSETS

The Field Start Offsets is a list in which each entry is the
position, relative to the Origin, of the start of the next field. The
entries are in reverse order, that is, the first field's offset is at
the end of the list.
@*

An example: suppose there are three columns. The first column's length
is 1, the second column's length is 2, and the third column's length is 4.
In this case, the offset values are, respectively, 1, 3 (1+2), and 7 (1+2+4).
Because values are reversed, a core dump of the Field Start Offsets
would look like this: @code{07,03,01}.
@*

There are two complications for special cases:
@itemize @bullet
@item
Complication #1: The size of each offset can be either one byte or
two bytes. One-byte offsets are only usable if the total record size
is less than 127. There is a flag in the "Extra Bytes" part which will
tell you whether the size is one byte or two bytes.
@item
Complication #2: The most significant bits of an offset may contain
flag values. The next two paragraphs explain what the contents are.
@end itemize

@strong{When The Size Of Each Offset Is One Byte}
@itemize @bullet
@item
1 bit  = 0 if field is non-NULL, = 1 if field is NULL
@item
7 bits  = the actual offset, a number between 0 and 127
@end itemize

@strong{When The Size Of Each Offset Is Two Bytes}
@itemize @bullet
@item
1 bit  = 0 if field is non-NULL, = 1 if field is NULL
@item
1 bit  = 0 if field is on same page as offset, = 1 if field and offset are on different pages
@item
14 bits  = the actual offset, a number between 0 and 16383
@end itemize

It is unlikely that the "field and offset are on different pages"
unless the record contains a large BLOB.

@subsection EXTRA BYTES

The Extra Bytes are a fixed six-byte header.

@multitable @columnfractions .10 .25 .35

@item @strong{Name} @tab @strong{Size} @tab @strong{Description}
@item @strong{info_bits:}
@item ()
@tab 1 bit
@tab unused or unknown
@item ()
@tab 1 bit
@tab unused or unknown
@item deleted_flag
@tab 1 bit
@tab 1 if record is deleted
@item min_rec_flag
@tab 1 bit
@tab 1 if record is predefined minimum record
@item n_owned
@tab 4 bits
@tab number of records owned by this record
@item heap_no
@tab 13 bits
@tab record's order number in heap of index page
@item n_fields
@tab 10 bits
@tab number of fields in this record, 1 to 1023
@item 1byte_offs_flag
@tab 1 bit
@tab 1 if each Field Start Offsets is 1 byte long (this item is also called the "short" flag)
@item @strong{next 16 bits}
@tab 16 bits
@tab pointer to next record in page
@item @strong{TOTAL}
@tab 48 bits

@end multitable

Total size is 48 bits, which is six bytes.
@*

If you're just trying to read the record, the key bit in the Extra
Bytes is 1byte_offs_flag -- you need to know if 1byte_offs_flag is 1
(i.e.: "short 1-byteoffsets") or 0 (i.e.: "2-byte offsets").
@*

Given a pointer to the Origin, InnoDB finds the start of the record as follows:
2539
@itemize @bullet
2540 2541 2542 2543 2544 2545 2546 2547 2548 2549
@item
Let X = n_fields (the number of fields is by definition equal to the
number of entries in the Field Start Offsets Table).
@item
If 1byte_offs_flag equals 0, then let X = X * 2 because there are
two bytes for each entry instead of just one.
@item
Let X = X + 6, because the fixed size of Extra Bytes is 6.
@item
The start of the record is at (pointer value minus X).
2550
@end itemize
2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562

@subsection FIELD CONTENTS

The Field Contents part of the record has all the data. Fields are
stored in the order they were defined in.
@*

There are no markers between fields, and there is no marker or filler
at the end of a record.
@*

Here's an example.
2563
@itemize @bullet
2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
@item
I made a table with this definition:
@*@*

@strong{CREATE TABLE T
    (FIELD1 VARCHAR(3), FIELD2 VARCHAR(3), FIELD3 VARCHAR(3))
    Type=InnoDB;}
@*@*

To understand what follows, you must know that table T has six columns
-- not three -- because InnoDB automatically added three "system
columns" at the start for its own housekeeping. It happens that these
system columns are the row ID, the transaction ID, and the rollback
pointer, but their values don't matter now. Regard them as three black
boxes.
@*@*

@item
I put some rows in the table. My last three INSERTs were:
@*@*

@strong{INSERT INTO T VALUES ('PP', 'PP', 'PP')}
@*@*

@strong{INSERT INTO T VALUES ('Q', 'Q', 'Q')}
@*@*

@strong{INSERT INTO T VALUES ('R', NULL, NULL)}
@*@*

@item
I ran Borland's TDUMP to get a hexadecimal dump of
the contents of \mysql\data\ibdata1, which (in my case) is the
MySQL/InnoDB data file (on Windows).
2598
@end itemize
2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692

Here is an extract of the dump:

@multitable @columnfractions .05 .95

@item @strong{Address Values In Hexadecimal} @tab @strong{Values In ASCII}
@item @code{0D4280: 00 00 2D 00 84 4F 4F 4F 4F 4F 4F 4F 4F 4F 19 17}
@tab @code{..-..OOOOOOOOO..}
@item @code{0D4290: 15 13 0C 06 00 00 78 0D 02 BF 00 00 00 00 04 21}
@tab @code{......x........!}
@item @code{0D42A0: 00 00 00 00 09 2A 80 00 00 00 2D 00 84 50 50 50}
@tab @code{.....*....-..PPP}
@item @code{0D42B0: 50 50 50 16 15 14 13 0C 06 00 00 80 0D 02 E1 00}
@tab @code{PPP.............}
@item @code{0D42C0: 00 00 00 04 22 00 00 00 00 09 2B 80 00 00 00 2D}
@tab @code{....".....+....-}
@item @code{0D42D0: 00 84 51 51 51 94 94 14 13 0C 06 00 00 88 0D 00}
@tab @code{..QQQ...........}
@item @code{0D42E0: 74 00 00 00 00 04 23 00 00 00 00 09 2C 80 00 00}
@tab @code{t.....#.....,...}
@item @code{0D42F0: 00 2D 00 84 52 00 00 00 00 00 00 00 00 00 00 00}
@tab @code{.-..R...........}

@end multitable

A reformatted version of the dump, showing only the relevant bytes,
looks like this (I've put a line break after each field and added labels):

@strong{Reformatted Hexadecimal Dump}@*
@code{
  19 17 15 13 0C 06 Field Start Offsets /* First Row */@*
  00 00 78 0D 02 BF Extra Bytes@*
  00 00 00 00 04 21 System Column #1@*
  00 00 00 00 09 2A System Column #2@*
  80 00 00 00 2D 00 84 System Column #3@*
  50 50 Field1 'PP'@*
  50 50 Field2 'PP'@*
  50 50 Field3 'PP'}@*

@code{
  16 15 14 13 0C 06 Field Start Offsets /* Second Row */@*
  00 00 80 0D 02 E1 Extra Bytes@*
  00 00 00 00 04 22 System Column #1@*
  00 00 00 00 09 2B 80 System Column #2@*
  00 00 00 2D 00 84 System Column #3@*
  51 Field1 'Q'@*
  51 Field2 'Q'@*
  51 Field3 'Q'}@*

@code{
  94 94 14 13 0C 06 Field Start Offsets /* Third Row */@*
  00 00 88 0D 00 74 Extra Bytes@*
  00 00 00 00 04 23 System Column #1@*
  00 00 00 00 09 2C System Column #2@*
  80 00 00 00 2D 00 84 System Column #3@*
  52 Field1 'R'}@*
@*

You won't need explanation if you followed everything I've said, but
I'll add helpful notes for the three trickiest details.
@itemize @bullet
@item
Helpful Notes About "Field Start Offsets": @*
Notice that the sizes of the record's fields, in forward order, are:
6, 6, 7, 2, 2, 2. Since each offset is for the start of the "next"
field, the hexadecimal offsets are 06, 0c (6+6), 13 (6+6+7), 15
(6+6+7+2), 17 (6+6+7+2+2), 19 (6+6+7+2+2+2). Reversing the order, the
Field Start Offsets of the first record are: @code{19,17,15,13,0c,06}.
@item
Helpful Notes About "Extra Bytes": @*
Look at the Extra Bytes of the first record: @code{00 00 78 0D 02 BF}. The
fourth byte is @code{0D hexadecimal}, which is @code{1101 binary} ... the 110 is the
last bits of n_fields (@code{110 binary} is 6 which is indeed the number of
fields in the record) and the final 1 bit is 1byte_offs_flag. The
fifth and sixth bytes, which contain @code{02 BF}, constitute the "next"
field. Looking at the original hexadecimal dump, at address
@code{0D42BF} (which is position @code{02BF} within the page), you'll see the beginning bytes of
System Column #1 of the second row. In other words, the "next" field
points to the "Origin" of the following row.
@item
Helpful Notes About NULLs:@*
For the third row, I inserted NULLs in FIELD2 and FIELD3. Therefore in
the Field Start Offsets the top bit is @code{on} for these fields (the
values are @code{94 hexadecimal}, @code{94 hexadecimal}, instead of 
@code{14 hexadecimal}, @code{14 hexadecimal}). And the row is
shorter because the NULLs take no space.
@end itemize

@section Where to Look For More Information

@strong{References:} @*
The most relevant InnoDB source-code files are rem0rec.c, rem0rec.ic,
and rem0rec.h in the rem ("Record Manager") directory.

2693
@node InnoDB Page Structure,Files in MySQL Sources,InnoDB Record Structure,Top
2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
@chapter InnoDB Page Structure

InnoDB stores all records inside a fixed-size unit which is commonly called a
"page" (though InnoDB sometimes calls it a "block" instead).
Currently all pages are the same size, 16KB.
@*

A page contains records, but it also contains headers and trailers.
I'll start this description with a high-altitude view of a page's parts,
then I'll describe each part of a page. Finally, I'll show an example. This 
discussion deals only with the most common format, for the leaf page of a data file.
@*

@section High-Altitude View

An InnoDB page has seven parts:
@itemize @bullet
@item
Fil Header
@item
Page Header
@item
Infimum + Supremum Records
@item
User Records
@item
Free Space
@item
Page Directory
@item
Fil Trailer
@end itemize

As you can see, a page has two header/trailer pairs. The inner pair, "Page Header" and
"Page Directory", are mostly the concern of the \page program group,
while the outer pair, "Fil Header" and "Fil Trailer", are mostly the
concern of the \fil program group. The "Fil" header also goes goes by
the name of "File Page Header".
@*

Sandwiched between the headers and trailers, are the records and
the free (unused) space. A page always begins with two unchanging
records called the Infimum and the Supremum. Then come the user
records. Between the user records (which grow downwards) and the page 
directory (which grows upwards) there is space for new records.
@*

@subsection Fil Header

The Fil Header has eight parts, as follows:

@multitable @columnfractions .10 .30 .35

@item @strong{Name} @tab @strong{Size} @tab @strong{Remarks}
@item FIL_PAGE_SPACE
@tab 4
@tab 4  ID of the space the page is in
@item FIL_PAGE_OFFSET
@tab 4
@tab ordinal page number from start of space
@item FIL_PAGE_PREV
@tab 4
@tab offset of previous page in key order
@item FIL_PAGE_NEXT
@tab 4
@tab offset of next page in key order
@item FIL_PAGE_LSN
@tab 8
@tab log serial number of page's latest log record
@item FIL_PAGE_TYPE
@tab 2
@tab current defined types are: FIL_PAGE_INDEX, FIL_PAGE_UNDO_LOG, FIL_PAGE_INODE, FIL_PAGE_IBUF_FREE_LIST
@item FIL_PAGE_FILE_FLUSH_LSN
@tab 8
@tab "the file has been flushed to disk at least up to this lsn" (log serial number), 
     valid only on the first page of the file
@item FIL_PAGE_ARCH_LOG_NO
@tab 4
@tab the latest archived log file number at the time that FIL_PAGE_FILE_FLUSH_LSN was written (in the log)
@end multitable

2775
@itemize
2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820
@item
FIL_PAGE_SPACE is a necessary identifier because different pages might belong to
different (table) spaces within the same file. The word
"space" is generic jargon for either "log" or "tablespace".
@*@*

@item
FIL_PAGE_PREV and FIL_PAGE_NEXT are the page's "backward" and
"forward" pointers. To show what they're about, I'll draw a two-level
B-tree.
@*@*

@example
  --------
  - root -
  --------
       |
  ----------------------
  |                    |
  |                    |
  --------          --------
  - leaf -  <-->    - leaf -
  --------          --------
@end example
@*

Everyone has seen a B-tree and knows that the entries in the root page
point to the leaf pages. (I indicate those pointers with vertical '|'
bars in the drawing.) But sometimes people miss the detail that leaf
pages can also point to each other (I indicate those pointers with a horizontal
two-way pointer '<-->' in the drawing). This feature allows InnoDB to navigate from
leaf to leaf without having to back up to the root level. This is a
sophistication which you won't find in the classic B-tree, which is
why InnoDB should perhaps be called a B+-tree instead.
@*@*

@item
The fields FIL_PAGE_FILE_FLUSH_LSN, FIL_PAGE_PREV, and FIL_PAGE_NEXT
all have to do with logs, so I'll refer you to my article "How Logs
Work With MySQL And InnoDB" on devarticles.com.
@*@*

@item
FIL_PAGE_FILE_FLUSH_LSN and FIL_PAGE_ARCH_LOG_NO are only valid for
the first page of a data file.
2821
@end itemize
2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123

@subsection Page Header

The Page Header has 14 parts, as follows:
@*@*

@multitable @columnfractions .10 .20 .30

@item @strong{Name} @tab @strong{Size} @tab @strong{Remarks}
@item PAGE_N_DIR_SLOTS
@tab 2
@tab number of directory slots in the Page Directory part; initial value = 2
@item PAGE_HEAP_TOP
@tab 2
@tab record pointer to first record in heap
@item PAGE_N_HEAP
@tab 2
@tab number of heap records; initial value = 2
@item PAGE_FREE
@tab 2
@tab record pointer to first free record
@item PAGE_GARBAGE
@tab 2
@tab "number of bytes in deleted records"
@item PAGE_LAST_INSERT
@tab 2
@tab record pointer to the last inserted record
@item PAGE_DIRECTION
@tab 2
@tab either PAGE_LEFT, PAGE_RIGHT, or PAGE_NO_DIRECTION
@item PAGE_N_DIRECTION
@tab 2
@tab number of consecutive inserts in the same direction, e.g. "last 5 were all to the left"
@item PAGE_N_RECS
@tab 2
@tab number of user records
@item PAGE_MAX_TRX_ID
@tab 8
@tab the highest ID of a transaction which might have changed a record on the page (only set for secondary indexes)
@item PAGE_LEVEL
@tab 2
@tab level within the index (0 for a leaf page)
@item PAGE_INDEX_ID
@tab 8
@tab identifier of the index the page belongs to
@item PAGE_BTR_SEG_LEAF
@tab 10
@tab "file segment header for the leaf pages in a B-tree" (this is irrelevant here)
@item PAGE_BTR_SEG_TOP
@tab 10
@tab "file segment header for the non-leaf pages in a B-tree" (this is irrelevant here)

@end multitable
@*

(Note: I'll clarify what a "heap" is when I discuss the User Records part of the page.)
@*@*

Some of the Page Header parts require further explanation:
@itemize @bullet
@item
PAGE_FREE: @*
Records which have been freed (due to deletion or migration) are in a
one-way linked list. The PAGE_FREE pointer in the page header points
to the first record in the list. The "next" pointer in the record
header (specifically, in the record's Extra Bytes) points to the next
record in the list.
@item
PAGE_DIRECTION and PAGE_N_DIRECTION: @*
It's useful to know whether inserts are coming in a constantly
ascending sequence. That can affect InnoDB's efficiency.
@item
PAGE_HEAP_TOP and PAGE_FREE and PAGE_LAST_INSERT: @*
Warning: Like all record pointers, these point not to the beginning of the
record but to its Origin (see the earlier discussion of Record
Structure).
@item
PAGE_BTR_SEG_LEAF and PAGE_BTR_SEG_TOP: @*
These variables contain information (space ID, page number, and byte offset) about
index node file segments. InnoDB uses the information for allocating new pages. 
There are two different variables because InnoDB allocates separately for leaf 
pages and upper-level pages.
@end itemize

@subsection The Infimum And Supremum Records

"Infimum" and "supremum" are real English words but they are found
only in arcane mathematical treatises, and in InnoDB comments. To
InnoDB, an infimum is lower than the the lowest possible real value
(negative infinity) and a supremum is greater than the greatest
possible real value (positive infinity). InnoDB sets up an infimum
record and a supremum record automatically at page-create time, and
never deletes them. They make a useful barrier to navigation so that
"get-prev" won't pass the beginning and "get-next" won't pass the end.
Also, the infimum record can be a dummy target for temporary record
locks.
@*@*

The InnoDB code comments distinguish between "the infimum and supremum
records" and the "user records" (all other kinds).
@*@*

It's sometimes unclear whether InnoDB considers the infimum and
supremum to be part of the header or not. Their size is fixed and
their position is fixed, so I guess so.

@subsection User Records

In the User Records part of a page, you'll find all the records that the user
inserted.
@*@*

There are two ways to navigate through the user records, depending
whether you want to think of their organization as an unordered or an
ordered list.
@*@*

An unordered list is often called a "heap". If you make a pile of
stones by saying "whichever one I happen to pick up next will go on
top" -- rather than organizing them according to size and colour --
then you end up with a heap. Similarly, InnoDB does not want to insert
new rows according to the B-tree's key order (that would involve
expensive shifting of large amounts of data), so it inserts new rows
right after the end of the existing rows (at the
top of the Free Space part) or wherever there's space left by a
deleted row.
@*@*

But by definition the records of a B-tree must be accessible in order
by key value, so there is a record pointer in each record (the "next"
field in the Extra Bytes) which points to the next record in key
order. In other words, the records are a one-way linked list. So
InnoDB can access rows in key order when searching.

@subsection Free Space

I think it's clear what the Free Space part of a page is, from the discussion of
other parts.

@subsection Page Directory

The Page Directory part of a page has a variable number of record pointers.
Sometimes the record pointers are called "slots" or "directory slots".
Unlike other DBMSs, InnoDB does not have a slot for every record in
the page. Instead it keeps a sparse directory. In a fullish page, 
there will be one slot for every six records.
@*@*

The slots track the records' logical order (the order by key rather
than the order by placement on the heap). Therefore, if the records
are @code{'A' 'B' 'F' 'D'} the slots will be @code{(pointer to 'A') (pointer to
'B') (pointer to 'D') (pointer to 'F')}. Because the slots are in key
order, and each slot has a fixed size, it's easy to do a binary
search of the records on the page via the slots.
@*@*

(Since the Page Directory does not have a slot for every record,
binary search can only give a rough position and then InnoDB must
follow the "next" record pointers. InnoDB's "sparse slots" policy also
accounts for the n_owned field in the Extra Bytes part of a record:
n_owned indicates how many more records must be gone through because
they don't have their own slots.)

@subsection Fil Trailer

The Fil Trailer has one part, as follows:
@*@*

@multitable @columnfractions .10 .35 .40

@item @strong{Name} @tab @strong{Size} @tab @strong{Remarks}
@item FIL_PAGE_END_LSN
@tab 8
@tab low 4 bytes = checksum of page, last 4 bytes = same as FIL_PAGE_LSN
@end multitable
@*

The final part of a page, the fil trailer (or File Page Trailer),
exists because InnoDB's architect worried about integrity. It's
impossible for a page to be only half-written, or corrupted by
crashes, because the log-recovery mechanism restores to a consistent
state. But if something goes really wrong, then it's nice to have a
checksum, and to have a value at the very end of the page which must
be the same as a value at the very beginning of the page.

@section Example

For this example, I used Borland's TDUMP again, as I did for the earlier chapter on
Record Format. This is what a page looked like:
@*@*

@multitable @columnfractions .05 .95

@item @strong{Address Values In Hexadecimal} @tab @strong{Values In ASCII}
@item @code{0D4000: 00 00 00 00 00 00 00 35 FF FF FF FF FF FF FF FF}
@tab @code{.......5........}
@item @code{0D4010: 00 00 00 00 00 00 E2 64 45 BF 00 00 00 00 00 00}
@tab @code{.......dE.......}
@item @code{0D4020: 00 00 00 00 00 00 00 05 02 F5 00 12 00 00 00 00}
@tab @code{................}
@item @code{0D4030: 02 E1 00 02 00 0F 00 10 00 00 00 00 00 00 00 00}
@tab @code{................}
@item @code{0D4040: 00 00 00 00 00 00 00 00 00 14 00 00 00 00 00 00}
@tab @code{................}
@item @code{0D4050: 00 02 16 B2 00 00 00 00 00 00 00 02 15 F2 08 01}
@tab @code{................}
@item @code{0D4060: 00 00 03 00 89 69 6E 66 69 6D 75 6D 00 09 05 00}
@tab @code{.....infimum....}
@item @code{0D4070: 08 03 00 00 73 75 70 72 65 6D 75 6D 00 22 1D 18}
@tab @code{....supremum."..}
@item @code{0D4080: 13 0C 06 00 00 10 0D 00 B7 00 00 00 00 04 14 00}
@tab @code{................}
@item @code{0D4090: 00 00 00 09 1D 80 00 00 00 2D 00 84 41 41 41 41}
@tab @code{.........-..AAAA}
@item @code{0D40A0: 41 41 41 41 41 41 41 41 41 41 41 1F 1B 17 13 0C}
@tab @code{AAAAAAAAAAA.....}
@item @code{ ... }
@item @code{ ... }
@item @code{0D7FE0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 74}
@tab @code{...............t}
@item @code{0D7FF0: 02 47 01 AA 01 0A 00 65 3A E0 AA 71 00 00 E2 64}
@tab @code{.G.....e:..q...d}
@end multitable
@*@*

Let's skip past the first 38 bytes, which are Fil Header. The bytes
of the Page Header start at location @code{0d4026 hexadecimal}:
@*@*

@multitable @columnfractions .10 .45 .60

@item @strong{Location} @tab @strong{Name} @tab @strong{Description}
@item @code{00 05}
@tab PAGE_N_DIR_SLOTS
@tab There are 5 directory slots.
@item @code{02 F5}
@tab PAGE_HEAP_TOP
@tab At location @code{0402F5}, not shown, is the beginning of free space.
Maybe a better name would have been PAGE_HEAP_END
@item @code{00 12}
@tab PAGE_N_HEAP
@tab There are 18 (hexadecimal 12) records in the page.
@item @code{00 00}
@tab PAGE_FREE
@tab There are zero free (deleted) records.
@item @code{00 00}
@tab PAGE_GARBAGE
@tab There are zero bytes in deleted records.
@item @code{02 E1}
@tab PAGE_LAST_INSERT
@tab The last record was inserted at location @code{02E1}, not shown, within the page.
@item @code{00 02}
@tab PAGE_DIRECTION
@tab A glance at page0page.h will tell you that 2 is the #defined value for PAGE_RIGHT.
@item @code{00 0F}
@tab PAGE_N_DIRECTION
@tab The last 15 (hexadecimal 0F) inserts were all done "to the right"
because I was inserting in ascending order.
@item @code{00 10}
@tab PAGE_N_RECS
@tab There are 16 (hexadecimal 10) user records. Notice that PAGE_N_RECS is
smaller than the earlier field, PAGE_N_HEAP.
@item @code{00 00 00 00 00 00 00}
@tab PAGE_MAX_TRX_ID
@item @code{00 00}
@tab PAGE_LEVEL
@tab Zero because this is a leaf page.
@item @code{00 00 00 00 00 00 00 14}
@tab PAGE_INDEX_ID
@tab This is index number 20.
@item @code{00 00 00 00 00 00 00 02 16 B2}
@tab PAGE_BTR_SEG_LEAF
@item @code{00 00 00 00 00 00 00 02 15 F2}
@tab PAGE_BTR_SEG_TOP
@end multitable
@*

Immediately after the page header are the infimum and supremum
records. Looking at the "Values In ASCII" column in the hexadecimal
dump, you will see that the contents are in fact the words "infimum"
and "supremum" respectively.
@*@*

Skipping past the User Records and the Free Space, many bytes later,
is the end of the 16KB page. The values shown there are the two trailers.
@itemize @bullet
@item
The first trailer (@code{00 74, 02 47, 01 AA, 01 0A, 00 65}) is the page
directory. It has 5 entries, because the header field PAGE_N_DIR_SLOTS
says there are 5.
@item
The next trailer (@code{3A E0 AA 71, 00 00 E2 64}) is the fil trailer. Notice
that the last four bytes, @code{00 00 E2 64}, appeared before in the fil
header.
@end itemize

@section Where to Look For More Information

@strong{References:} @*
The most relevant InnoDB source-code files are page0page.c,
page0page.ic, and page0page.h in \page directory.

3124
@node Files in MySQL Sources,Files in InnoDB Sources,InnoDB Page Structure,Top
3125 3126 3127 3128
@chapter Annotated List Of Files in the MySQL Source Code Distribution

This is a description of the files that you get when you download the
source code of MySQL. This description begins with a list
3129
of the main directories and a short comment about each one. Then, for
3130 3131 3132 3133 3134 3135 3136 3137 3138
each directory, in alphabetical order, a longer description is
supplied. When a directory contains significant program files, a list of each C
program is given along with an explanation of its intended function.

@section Directory Listing

@strong{Directory  --  Short Comment}
@itemize @bullet
@item
3139
bdb  --  The Berkeley Database table handler
3140
@item
3141
BitKeeper  --  BitKeeper administration (not part of the source distribution)
3142
@item
3143
BUILD  --  Frequently used build scripts
3144
@item
3145
Build-tools  --  Build tools (not part of the source distribution)
3146
@item
3147
client  --  Client library
3148
@item
3149
cmd-line-utils  --  Command-line utilities (libedit and readline)
3150
@item
3151
dbug  --  Fred Fish's dbug library
3152
@item
3153
Docs  --  Preliminary documents about internals and new modules; will eventually be moved to the mysqldoc repository
3154
@item
3155
extra  --  Some minor standalone utility programs
3156
@item
3157
heap  --  The HEAP table handler
3158
@item
3159
include  --  Header (*.h) files for most libraries; includes all header files distributed with the MySQL binary distribution
3160
@item
3161
innobase  --  The Innobase (InnoDB) table handler
3162
@item
3163
libmysql  --  For producing MySQL as a library (e.g. a Windows .DLL)
3164
@item
3165
libmysql_r  --  For building a thread-safe libmysql library
3166
@item
3167
libmysqld  --  The MySQL Server as an embeddable library
3168
@item
3169
man  --  Some user-contributed manual pages
3170
@item
3171
myisam  --  The MyISAM table handler 
3172 3173 3174 3175 3176
@item
myisammrg  --  The MyISAM Merge table handler 
@item
mysql-test  --  A test suite for mysqld 
@item
3177
mysys  --  MySQL system library (Low level routines for file access etc.)
3178 3179 3180
@item
netware  --  Files related to the Novell NetWare version of MySQL 
@item
3181
NEW-RPMS  --  Directory to place RPMs while making a distribution
3182
@item
3183
os2  --  Routines for working with the OS/2 operating system
3184
@item
3185
pstack  --  Process stack display (not currently used)
3186
@item
3187
regex  --  Henry Spencer's Regular Expression library for support of REGEXP function
3188
@item
3189
SCCS  --  Source Code Control System (not part of source distribution)
3190
@item
3191
scripts  --  SQL batches, e.g. mysqlbug and mysql_install_db
3192
@item
3193
sql  --  Programs for handling SQL commands; the "core" of MySQL 
3194 3195 3196
@item
sql-bench  --  The MySQL benchmarks 
@item
3197
SSL  --  Secure Sockets Layer; includes an example certification one can use to test an SSL (secure) database connection
3198 3199 3200
@item
strings  --  Library for C string routines, e.g. atof, strchr 
@item
3201
support-files  --  Files used to build MySQL on different systems
3202
@item
3203
tests  --  Tests in Perl and in C
3204
@item
3205
tools  --  mysqlmanager.c (tool under development, not yet useful)
3206
@item
3207
VC++Files  --  Includes this entire directory, repeated for VC++ (Windows) use
3208 3209 3210
@item
vio  --  Virtual I/O Library 
@item
3211
zlib  --  Data compression library, used on Windows
3212 3213 3214 3215 3216 3217 3218
@end itemize

@subsection bdb

The Berkeley Database table handler.
@*@*

3219
The Berkeley Database (BDB) is maintained by Sleepycat Software.
3220 3221
MySQL AB maintains only a few small patches to make BDB work
better with MySQL.
3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234
@*@*

The documentation for BDB is available at
http://www.sleepycat.com/docs/. Since it's reasonably thorough
documentation, a description of the BDB program files is not included
in this document.
@*@*

@subsection BitKeeper

BitKeeper administration.
@*@*

3235 3236
Bitkeeper administration is not part of the source distribution. This 
directory may be present if you downloaded the MySQL source using
3237 3238 3239 3240 3241
BitKeeper rather than via the mysql.com site. The files in the
BitKeeper directory are for maintenance purposes only -- they are not
part of the MySQL package.
@*@*

3242 3243 3244
The MySQL Reference Manual explains how to use Bitkeeper to get the
MySQL source. Please see @url{http://www.mysql.com/doc/en/Installing_source_tree.html}
for more information.
3245 3246
@*@*

3247 3248
@subsection BUILD

3249
Frequently used build scripts.
3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271
@*@*

This directory contains the build switches for compilation on various
platforms. There is a subdirectory for each set of options. The main
ones are:
@itemize @bullet
@item
alpha
@item
ia64
@item
pentium (with and without debug or bdb, etc.)
@item
solaris
@end itemize
@*@*

@subsection Build-tools

Build tools.
@*@*

3272 3273 3274 3275 3276
Build-tools is not part of the source distribution. This directory
contains batch files for extracting, making directories, and making
programs from source files. There are several subdirectories with
different scripts -- for building Linux executables, for compiling,
for performing all build steps, and so on.
3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291
@*@*

@subsection client

Client library.
@*@*

The client library includes mysql.cc (the source of the 'mysql'
executable) and other utilities. Most of the utilities are mentioned
in the MySQL Reference Manual. Generally these are standalone C
programs which one runs in "client mode", that is, they call the
server.
@*@*

The C program files in the directory are:
3292
@itemize @bullet
3293
@item
3294
get_password.c  --  ask for a password from the console
3295
@item
3296
mysql.cc  --  "The MySQL command tool"
3297
@item
3298
mysqladmin.c  --  maintenance of MySQL databases
3299
@item
3300
mysqlcheck.c  --  check all databases, check connect, etc.
3301
@item
3302
mysqldump.c  --  dump table's contents as SQL statements, suitable to backup a MySQL database
3303
@item
3304
mysqlimport.c  --  import text files in different formats into tables
3305
@item
3306
mysqlmanager-pwgen.c  --  pwgen stands for "password generation" (not currently maintained)
3307
@item
3308
mysqlmanagerc.c  --  entry point for mysql manager (not currently maintained)
3309 3310 3311
@item
mysqlshow.c  --  show databases, tables or columns 
@item
3312
mysqltest.c  --  test program used by the mysql-test suite, mysql-test-run
3313
@item
3314
password.c  --  password checking routines (version 4.1 and up)
3315
@end itemize
3316 3317 3318 3319
@*@*

@subsection cmd-line-utils

3320
Command-line utilities (libedit and readline).
3321 3322 3323
@*@*

There are two subdirectories: \readline and \libedit. All the files
3324
here are "non-MySQL" files, in the sense that MySQL AB didn't produce
3325
them, it just uses them. It should be unnecessary to study the
3326 3327
programs in these files unless you are writing or debugging a tty-like
client for MySQL, such as mysql.exe.
3328 3329 3330 3331 3332 3333 3334 3335 3336
@*@*

The \readline subdirectory contains the files of the GNU Readline
Library, "a library for reading lines of text with interactive input
and history editing". The programs are copyrighted by the Free
Software Foundation.
@*@*

The \libedit (library of edit functions) subdirectory has files
3337
written by Christos Zoulas. They are distributed and modifed under
3338 3339 3340
the BSD License. These files are for editing the line contents.
@*@*

3341
These are the program files in the \libedit subdirectory:
3342
@itemize @bullet
3343
@item
3344
chared.c  --  character editor
3345
@item
3346
common.c  --  common editor functions
3347
@item
3348
el.c  --  editline interface functions
3349
@item
3350
emacs.c  --  emacs functions
3351
@item
3352
fgetln.c  --  get line
3353
@item
3354
hist.c  --  history access functions
3355
@item
3356
history.c  --  more history access functions
3357
@item
3358
key.c  --  procedures for maintaining the extended-key map
3359
@item
3360
map.c  --  editor function definitions
3361
@item
3362
parse.c  --  parse an editline extended command
3363
@item
3364
prompt.c  --  prompt printing functions
3365
@item
3366
read.c  --  terminal read functions
3367
@item
3368
readline.c  --  read line
3369
@item
3370
refresh.c  --  "lower level screen refreshing functions"
3371
@item
3372
search.c  --  "history and character search functions"
3373
@item
3374
sig.c  --  for signal handling
3375
@item
3376
strlcpy.c  --  string copy
3377
@item
3378
term.c  --  "editor/termcap-curses interface"
3379
@item
3380
tokenizer.c  --  Bourne shell line tokenizer
3381
@item
3382
tty.c  --  for a tty interface
3383
@item
3384
vi.c  --  commands used when in the vi (editor) mode
3385
@end itemize
3386 3387 3388 3389 3390 3391 3392 3393
@*@*

@subsection dbug

Fred Fish's dbug library.
@*@*

This is not really part of the MySQL package. Rather, it's a set of
3394 3395
public-domain routines which are useful for debugging MySQL programs.
The MySQL Server and all .c and .cc programs support the use of this
3396
package.
3397 3398 3399 3400 3401 3402 3403 3404 3405
@*@*

How it works: One inserts a function call that begins with DBUG_* in
one of the regular MYSQL programs. For example, in get_password.c, you
will find this line: @*
DBUG_ENTER("get_tty_password"); @*
at the start of a routine, and this line: @*
DBUG_RETURN(my_strdup(to,MYF(MY_FAE))); @*
at the end of the routine. These lines don't affect production code.
3406
Features of the dbug library include extensive reporting and profiling
3407
(the latter has not been used by the MySQL team).
3408 3409 3410
@*@*

The C programs in this directory are:
3411
@itemize @bullet
3412
@item
3413
dbug.c  --  The main module
3414
@item
3415
dbug_analyze.c  --  Reads a file produced by trace functions
3416
@item
3417
example1.c  --  A tiny example
3418
@item
3419
example2.c  --  A tiny example
3420
@item
3421
example3.c  --  A tiny example
3422
@item
3423
factorial.c  --  A tiny example
3424
@item
3425
main.c  --  A tiny example
3426
@item
3427
sanity.c  --   Declaration of a variable
3428
@end itemize
3429 3430 3431 3432
@*@*

@subsection Docs

3433 3434
Preliminary documents about internals and new modules, which will eventually
be moved to the mysqldoc repository.
3435 3436 3437 3438 3439
@*@*

This directory doesn't have much at present that's very useful to the
student, but the plan is that some documentation related to the source
files and the internal workings of MySQL, including perhaps some
3440 3441
documentation from developers themselves, will be placed here. Files in
this directory will eventually be moved to the MySQL documentation repository.
3442 3443 3444
@*@*

These sub-directories are part of this directory:
3445
@itemize @bullet
3446
@item
3447
books  --  .gif images and empty .txt files; no real information
3448
@item
3449
flags  --  images of flags of countries
3450
@item
3451
images  --  flag backgrounds and the MySQL dolphin logo
3452
@item
3453
mysql-logos  --  more MySQL-related logos, some of them moving
3454
@item
3455
raw-flags  --   more country flags, all .gif files
3456
@item
3457
support  --  various files for generating texinfo/docbook documentation
3458
@item
3459
to-be-included...  --  an empty subdirectory
3460
@item
3461
translations  --  some Portuguese myodbc documentation
3462
@end itemize
3463 3464 3465 3466 3467 3468 3469 3470 3471
@*@*

In the main directory, you'll find some .txt files related to the
methods that MySQL uses to produce its printed and html documents, odd
bits in various languages, and the single file in the directory which
has any importance -- internals.texi -- The "MySQL Internals"
document.
@*@*

3472 3473 3474 3475 3476
Despite the name, internals.texi is not yet much of a description of MySQL
internals although work is in progress to make it so. However, there is 
some useful description of the functions in the mysys directory (see below), 
and of the structure of client/server messages (doubtless very useful for 
eople who want to make their own JDBC drivers, or just sniff).
3477 3478 3479 3480
@*@*

@subsection extra

3481
Some minor standalone utility programs.
3482 3483
@*@*

3484
These programs are all standalone utilities, that is, they have
3485 3486 3487
a main() function and their main role is to show information that the
MySQL server needs or produces. Most are unimportant. They are as
follows:
3488
@itemize @bullet
3489
@item
3490
my_print_defaults.c  --  print parameters from my.ini files. Can also be used in scripts to enable processing of my.ini files.
3491
@item
3492
mysql_waitpid.c  --  wait for a program to terminate. Useful for shell scripts when one needs to wait until a process terminates.
3493
@item
3494
perror.c  --  "print error" -- given error number, display message
3495
@item
3496
replace.c  --  replace strings in text files or pipe
3497
@item
3498
resolve_stack_dump.c  --  show symbolic information from a MySQL stack dump, normally found in the mysql.err file
3499
@item
3500
resolveip.c  --  convert an IP address to a hostname, or vice versa
3501
@end itemize
3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517
@*@*

@subsection heap

The HEAP table handler.
@*@*

All the MySQL table handlers (i.e. the handlers that MySQL itself
produces) have files with similar names and functions. Thus, this
(heap) directory contains a lot of duplication of the myisam directory
(for the MyISAM table handler). Such duplicates have been marked with
an "*" in the following list. For example, you will find that
\heap\hp_extra.c has a close equivalent in the myisam directory
(\myisam\mi_extra.c) with the same descriptive comment.
@*@*

3518
@itemize
3519 3520 3521
@item
hp_block.c  --  Read/write a block (i.e. a page)
@item
3522
hp_clear.c  --  Remove all records in the table
3523
@item
3524
hp_close.c  --  * close database
3525
@item
3526
hp_create.c  --  * create a table
3527
@item
3528
hp_delete.c  --  * delete a row
3529 3530 3531
@item
hp_extra.c  --  * for setting options and buffer sizes when optimizing
@item
3532
hp_hash.c  --  Hash functions used for saving keys
3533
@item
3534
hp_info.c  --  * Information about database status
3535
@item
3536
hp_open.c  --  * open database
3537
@item
3538
hp_panic.c  --  * the hp_panic routine, for shutdowns and flushes
3539
@item
3540
hp_rename.c  --  * rename a table
3541 3542 3543
@item
hp_rfirst.c  --  * read first row through a specific key (very short)
@item
3544
hp_rkey.c  --  * read record using a key
3545 3546 3547 3548 3549
@item
hp_rlast.c  --  * read last row with same key as previously-read row
@item
hp_rnext.c  --  * read next row with same key as previously-read row
@item
3550
hp_rprev.c  --  * read previous row with same key as previously-read row
3551
@item
3552
hp_rrnd.c  --  * read a row based on position
3553 3554
@item
hp_rsame.c  --  * find current row using positional read or key-based
3555
read
3556
@item
3557
hp_scan.c  --  * read all rows sequentially
3558 3559 3560
@item
hp_static.c  --  * static variables (very short)
@item
3561
hp_test1.c  --  * testing basic functions
3562
@item
3563
hp_test2.c  --  * testing database and storing results
3564
@item
3565
hp_update.c  --  * update an existing row
3566
@item
3567
hp_write.c  --  * insert a new row
3568
@end itemize
3569 3570 3571 3572 3573 3574 3575 3576 3577 3578
@*@*

There are fewer files in the heap directory than in the myisam
directory, because fewer are necessary. For example, there is no need
for a \myisam\mi_cache.c equivalent (to cache reads) or a
\myisam\log.c equivalent (to log statements).
@*@*

@subsection include

3579 3580
Header (*.h) files for most libraries; includes all header files distributed
with the MySQL binary distribution.
3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594
@*@*

These files may be included in C program files. Note that each
individual directory will also have its own *.h files, for including
in its own *.c programs. The *.h files in the include directory are
ones that might be included from more than one place.
@*@*

For example, the mysys directory contains a C file named rijndael.c,
but does not include rijndael.h. The include directory contains
rijndael.h. Looking further, you'll find that rijndael.h is also
included in other places: by my_aes.c and my_aes.h.
@*@*

3595
The include directory contains 51 *.h (header) files.
3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625
@*@*

@subsection innobase

The Innobase (InnoDB) table handler.
@*@*

A full description of these files can be found elsewhere in this
document.
@*@*

@subsection libmysql

The MySQL Library, Part 1.
@*@*

The files here are for producing MySQL as a library (e.g. a Windows
DLL). The idea is that, instead of producing separate mysql (client)
and mysqld (server) programs, one produces a library. Instead of
sending messages, the client part merely calls the server part.
@*@*

The libmysql files are split into three directories: libmysql (this
one), libmysql_r (the next one), and libmysqld (the next one after
that). It may be that the original intention was that the libmysql
directory would hold the "client part" files, and the libmysqld
directory would hold the "server part" files.
@*@*

The program files on this directory are:
3626
@itemize @bullet
3627 3628 3629 3630 3631 3632 3633 3634 3635
@item
conf_to_src.c  --  has to do with charsets 
@item
dll.c  --  initialization of the dll library 
@item
errmsg.c  --  English error messages, compare \mysys\errors.c 
@item
get_password.c  --  get password 
@item
3636
libmysql.c  --  the code that implements the MySQL API, i.e. the functions a client that wants to connect to MySQL will call
3637 3638
@item
manager.c  --  initialize/connect/fetch with MySQL manager 
3639
@end itemize
3640 3641 3642 3643 3644 3645 3646 3647
@*@*

@subsection libmysql_r

The MySQL Library, Part 2.
@*@*

This is a continuation of the libmysql directory. There is only one
3648
file here, used to build a thread-safe libmysql library:
3649
@itemize @bullet
3650 3651
@item
makefile.am
3652
@end itemize
3653 3654 3655 3656 3657 3658 3659
@*@*

@subsection libmysqld

The MySQL library, Part 3.
@*@*

3660 3661 3662
This is a continuation of the libmysql directory and contains the MySQL
Server as an embeddable library. The program files on this directory
are:
3663
@itemize @bullet
3664
@item
3665
libmysqld.c  --  The called side, compare the mysqld.exe source
3666
@item
3667
lib_vio.c --  Emulate the vio directory's communication buffer
3668
@end itemize
3669 3670 3671 3672
@*@*

@subsection man

3673
Some user-contributed manual pages
3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685
@*@*

These are not the actual "man" (manual) pages, they are switches for
the production.
@*@*

@subsection myisam

The MyISAM table handler.
@*@*

The C files in this subdirectory come in six main groups:
3686
@itemize @bullet
3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704
@item
ft*.c files  --  ft stands for "Full Text", code contributed by Sergei
Golubchik 
@item
mi*.c files  --  mi stands for "My Isam", these are the main programs
for Myisam 
@item
myisam*.c files  --  for example, "myisamchk" utility routine
functions source 
@item
rt*.c files  --  rt stands for "rtree", some code was written by
Alexander Barkov 
@item
sp*.c files  --  sp stands for "spatial", some code was written by
Ramil Kalimullin 
@item
sort.c  --  this is a single file that sorts keys for index-create
purposes 
3705
@end itemize
3706 3707 3708 3709 3710
@*@*

The "full text" and "rtree" and "spatial" program sets are for special
purposes, so this document focuses only on the mi*.c "myisam" C
programs. They are:
3711
@itemize @bullet
3712 3713 3714
@item
mi_cache.c  --  for reading records from a cache 
@item
3715
mi_changed.c  --  a single routine for setting a "changed" flag (very short)
3716
@item
3717
mi_check.c  --  for checking and repairing tables. Used by the myisamchk program and by the MySQL server.
3718 3719 3720 3721 3722 3723 3724
@item
mi_checksum.c  --  calculates a checksum for a row 
@item
mi_close.c  --  close database 
@item
mi_create.c  --  create a table 
@item
3725
mi_dbug.c  -- support routines for use with "dbug" (see \dbug description)
3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736
@item
mi_delete.c  --  delete a row 
@item
mi_delete_all.c  --  delete all rows 
@item
mi_delete_table.c  --  delete a table (very short)
@item
mi_dynrec.c  --  functions to handle space-packed records and blobs 
@item
mi_extra.c  --  setting options and buffer sizes when optimizing 
@item
3737
mi_info.c  --  return useful base information for an open table
3738
@item
3739
mi_key.c  --  for handling keys
3740 3741 3742
@item
mi_locking.c  --  lock database 
@item
3743
mi_log.c  --  save commands in a log file which myisamlog program can read. Can be used to exactly replay a set of changes to a table.
3744 3745 3746
@item
mi_open.c  --  open database 
@item
3747
mi_packrec.c  --  read from a data file compresed with myisampack
3748
@item
3749
mi_page.c  --  read and write pages containing keys
3750
@item
3751
mi_panic.c  --  the mi_panic routine, probably for sudden shutdowns
3752
@item
3753
mi_range.c  --  approximate count of how many records lie between two keys
3754
@item
3755
mi_rename.c  --  rename a table
3756 3757 3758
@item
mi_rfirst.c  --  read first row through a specific key (very short)
@item
3759
mi_rkey.c  --  read a record using a key
3760
@item
3761
mi_rlast.c  --  read last row with same key as previously-read row
3762
@item
3763
mi_rnext.c  --  read next row with same key as previously-read row
3764
@item
3765
mi_rnext_same.c  --  same as mi_rnext.c, but abort if the key changes
3766 3767 3768
@item
mi_rprev.c  --  read previous row with same key as previously-read row
@item
3769
mi_rrnd.c  --  read a row based on position
3770
@item
3771
mi_rsame.c  --  find current row using positional read or key-based read
3772
@item
3773
mi_rsamepos.c  --  positional read
3774
@item
3775
mi_scan.c  --  read all rows sequentially
3776
@item
3777
mi_search.c  --  key-handling functions
3778 3779 3780
@item
mi_static.c  --  static variables (very short)
@item
3781
mi_statrec.c  --  functions to handle fixed-length records
3782
@item
3783
mi_test1.c  --  testing basic functions
3784
@item
3785
mi_test2.c  --  testing database and storing results
3786
@item
3787
mi_test3.c  --  testing locking
3788
@item
3789
mi_unique.c  --  functions to check if a row is unique
3790
@item
3791
mi_update.c  --  update an existing row
3792
@item
3793
mi_write.c  --  insert a new row
3794
@end itemize
3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812
@*@*

@subsection myisammrg

MyISAM Merge table handler.
@*@*

As with other table handlers, you'll find that the *.c files in the
myissammrg directory have counterparts in the myisam directory. In
fact, this general description of a myisammrg program is almost always
true: The myisammrg
function checks an argument, the myisammrg function formulates an
expression for passing to a myisam function, the myisammrg calls a
myisam function, the myisammrg function returns.
@*@*

These are the 21 files in the myisammrg directory, with notes about
the myisam functions or programs they're connected with:
3813
@itemize @bullet
3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861
@item
myrg_close.c  --  mi_close.c 
@item
myrg_create.c  --  mi_create.c 
@item
myrg_delete.c  --  mi_delete.c / delete last-read record 
@item
myrg_extra.c  --  mi_extra.c / "extra functions we want to do ..." 
@item
myrg_info.c  --  mi_info.c / display information about a mymerge file 
@item
myrg_locking.c  --  mi_locking.c / lock databases 
@item
myrg_open.c  --  mi_open.c / open a MyISAM MERGE table 
@item
myrg_panic.c  --  mi_panic.c / close in a hurry 
@item
myrg_queue.c  --  read record based on a key 
@item
myrg_range.c  --  mi_range.c / find records in a range 
@item
myrg_rfirst.c  --  mi_rfirst.c / read first record according to
specific key 
@item
myrg_rkey.c  --  mi_rkey.c / read record based on a key 
@item
myrg_rlast.c  --  mi_rlast.c / read last row with same key as previous
read 
@item
myrg_rnext.c  --  mi_rnext.c / read next row with same key as previous
read 
@item
myrg_rnext_same.c  --  mi_rnext_same.c / read next row with same key
@item
myrg_rprev.c  --  mi_rprev.c / read previous row with same key 
@item
myrg_rrnd.c  --  mi_rrnd.c / read record with random access 
@item
myrg_rsame.c  --  mi_rsame.c / call mi_rsame function, see
\myisam\mi_rsame.c 
@item
myrg_static.c  --  mi_static.c / static variable declaration 
@item
myrg_update.c  --  mi_update.c / call mi_update function, see
\myisam\mi_update.c 
@item
myrg_write.c  --  mi_write.c / call mi_write function, see
\myisam\mi_write.c 
3862
@end itemize
3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875
@*@*

@subsection mysql-test

A test suite for mysqld.
@*@*

The directory has a README file which explains how to run the tests,
how to make new tests (in files with the filename extension "*.test"),
and how to report errors.
@*@*

There are four subdirectories:
3876
@itemize @bullet
3877 3878 3879 3880 3881 3882 3883 3884 3885
@item
\misc  --  contains one minor Perl program
@item
\r  --  contains *.result, i.e. "what happened" files and
*.required, i.e. "what should happen" file
@item
\std_data  --  contains standard data for input to tests
@item
\t  --  contains tests
3886
@end itemize
3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905
@*@*

There are 186 *.test files in the \t subdirectory. Primarily these are
SQL scripts which try out a feature, output a result, and compare the
result with what's required. Some samples of what the test files check
are: latin1_de comparisons, date additions, the HAVING clause, outer
joins, openSSL, load data, logging, truncate, and UNION.
@*@*

There are other tests in these directories:
@itemize @bullet
@item
sql-bench
@item
tests
@end itemize

@subsection mysys

3906
MySQL system library. Low level routines for file access and so on.
3907 3908 3909
@*@*

There are 115 *.c programs in this directory:
3910
@itemize @bullet
3911 3912 3913
@item
array.c  --  Dynamic array handling 
@item
3914
charset.c  --  Using dynamic character sets, set default character set, ...
3915
@item
3916
charset2html.c  --  Check what character set a browser is using
3917
@item
3918
checksum.c  --  Calculate checksum for a memory block, used for pack_isam
3919 3920 3921 3922 3923 3924 3925 3926 3927
@item
default.c  --  Find defaults from *.cnf or *.ini files 
@item
errors.c  --  English text of global errors 
@item
hash.c  --  Hash search/compare/free functions "for saving keys" 
@item
list.c  --  Double-linked lists 
@item
3928
make-conf.c  --  "Make a charset .conf file out of a ctype-charset.c file"
3929 3930 3931
@item
md5.c  --  MD5 ("Message Digest 5") algorithm from RSA Data Security
@item
3932
mf_brkhant.c  --  Prevent user from doing a Break during critical execution (not used in MySQL; can be used by standalone MyISAM applications)
3933
@item
3934
mf_cache.c  --  "Open a temporary file and cache it with io_cache"
3935
@item
3936
mf_dirname.c  --  Parse/convert directory names
3937
@item
3938
mf_fn_ext.c  --  Get filename extension
3939
@item
3940
mf_format.c  --  Format a filename
3941
@item
3942
mf_getdate.c  --  Get date, return in yyyy-mm-dd hh:mm:ss format
3943
@item
3944
mf_iocache.c  --  Cached read/write of files in fixed-size units
3945
@item
3946
mf_iocache2.c  --  Continuation of mf_iocache.c
3947
@item
3948
mf_keycache.c  --  Key block caching for certain file types
3949 3950 3951 3952 3953
@item
mf_loadpath.c  --  Return full path name (no ..\ stuff)
@item
mf_pack.c  --  Packing/unpacking directory names for create purposes
@item
3954
mf_path.c  --  Determine where a program can find its files
3955
@item
3956
mf_qsort.c  --  Quicksort
3957
@item
3958
mf_qsort2.c  --  Quicksort, part 2 (allows the passing of an extra argument to the sort-compare routine)
3959
@item
3960
mf_radix.c  --  Radix sort
3961
@item
3962
mf_same.c  --  Determine whether filenames are the same
3963
@item
3964
mf_sort.c  --  Sort with choice of Quicksort or Radix sort
3965
@item
3966
mf_soundex.c  --  Soundex algorithm derived from EDN Nov. 14, 1985 (pg. 36)
3967
@item
3968
mf_strip.c  --  Strip trail spaces from a string
3969
@item
3970
mf_tempdir.c  --  Initialize/find/free temporary directory
3971
@item
3972
mf_tempfile.c  --  Create a temporary file
3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061
@item
mf_unixpath.c  --  Convert filename to UNIX-style filename 
@item
mf_util.c  --  Routines, #ifdef'd, which may be missing on some
machines 
@item
mf_wcomp.c  --  Comparisons with wildcards 
@item
mf_wfile.c  --  Finding files with wildcards 
@item
mulalloc.c  --  Malloc many pointers at the same time 
@item
my_aes.c  --  AES encryption 
@item
my_alarm.c  --  Set a variable value when an alarm is received 
@item
my_alloc.c  --  malloc of results which will be freed simultaneously
@item
my_append.c  --  one file to another 
@item
my_bit.c  --  smallest X where 2^X >= value, maybe useful for
divisions 
@item
my_bitmap.c  --  Handle uchar arrays as large bitmaps 
@item
my_chsize.c  --  Truncate file if shorter, else fill with a filler
character 
@item
my_clock.c  --  Time-of-day ("clock()") function, with OS-dependent
#ifdef's  
@item
my_compress.c  --  Compress packet (see also description of \zlib
directory)
@item
my_copy.c  --  Copy files 
@item
my_create.c  --  Create file 
@item
my_delete.c  --  Delete file 
@item
my_div.c  --  Get file's name 
@item
my_dup.c  --  Open a duplicated file 
@item
my_error.c  --  Return formatted error to user 
@item
my_fopen.c  --  File open 
@item
my_fstream.c  --  Streaming file read/write 
@item
my_getwd.c  --  Get working directory 
@item
my_gethostbyname.c  --  Thread-safe version of standard net
gethostbyname() func 
@item
my_getopt.c  --  Find out what options are in effect 
@item
my_handler.c  --  Compare two keys in various possible formats 
@item
my_init.c  --  Initialize variables and functions in the mysys library
@item
my_lib.c  --  Compare/convert directory names and file names 
@item
my_lock.c  --  Lock part of a file 
@item
my_lockmem.c  --  "Allocate a block of locked memory" 
@item
my_lread.c  --  Read a specified number of bytes from a file into
memory 
@item
my_lwrite.c  --  Write a specified number of bytes from memory into a
file 
@item
my_malloc.c  --  Malloc (memory allocate) and dup functions 
@item
my_messnc.c  --  Put out a message on stderr with "no curses" 
@item
my_mkdir.c  --  Make directory 
@item
my_net.c  --  Thread-safe version of net inet_ntoa function 
@item
my_netware.c  --  Functions used only with the Novell Netware version
of MySQL 
@item
my_once.c  --  Allocation / duplication for "things we don't need to
free" 
@item
my_open.c  --  Open a file 
@item
4062
my_os2cond.c  --  OS2-specific: "A simple implementation of posix conditions"
4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075
@item
my_os2dirsrch.c  --  OS2-specific: Emulate a Win32 directory search 
@item
my_os2dlfcn.c  --  OS2-specific: Emulate UNIX dynamic loading 
@item
my_os2file64.c  --  OS2-specific: For File64bit setting 
@item
my_os2mutex.c  --  OS2-specific: For mutex handling 
@item
my_os2thread.c  --  OS2-specific: For thread handling 
@item
my_os2tls.c  --  OS2-specific: For thread-local storage 
@item
4076
my_port.c  --  OS/machine-dependent porting functions, e.g. AIX-specific my_ulonglong2double()
4077 4078 4079
@item
my_pread.c  --  Read a specified number of bytes from a file 
@item
4080
my_pthread.c  --  A wrapper for thread-handling functions in different OSs
4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096
@item
my_quick.c  --  Read/write (labelled a "quicker" interface, perhaps
obsolete)
@item
my_read.c  --  Read a specified number of bytes from a file, possibly
retry 
@item
my_realloc.c  --  Reallocate memory allocated with my_alloc.c
(probably)
@item
my_redel.c  --  Rename and delete file 
@item
my_rename.c  --  Rename without delete 
@item
my_seek.c  --  Seek, i.e. point to a spot within a file 
@item
4097
my_semaphore.c  --  Semaphore routines, for use on OS that doesn't support them
4098 4099 4100
@item
my_sleep.c  --  Wait n microseconds 
@item
4101
my_static.c  --  Static variables used by the mysys library
4102
@item
4103
my_symlink.c  --  Read a symbolic link (symlinks are a UNIX thing, I guess)
4104
@item
4105
my_symlink2.c  --  Part 2 of my_symlink.c
4106
@item
4107
my_tempnam.c  --  Obsolete temporary-filename routine used by ISAM table handler
4108
@item
4109
my_thr_init.c  --  initialize/allocate "all mysys & debug thread variables"
4110
@item
4111
my_wincond.c  --  Windows-specific: emulate Posix conditions
4112
@item
4113
my_winsem.c  --  Windows-specific: emulate Posix threads
4114
@item
4115
my_winthread.c  --  Windows-specific: emulate Posix threads
4116
@item
4117
my_write.c  --  Write a specified number of bytes to a file
4118
@item
4119
ptr_cmp.c  --  Point to an optimal byte-comparison function
4120
@item
4121
queues.c  --  Handle priority queues as in Robert Sedgewick's book
4122 4123 4124
@item
raid2.c  --  RAID support (the true implementation is in raid.cc)
@item
4125
rijndael.c  --  "Optimised ANSI C code for the Rijndael cipher (now AES")
4126
@item
4127
safemalloc.c  --  A version of the standard malloc() with safety checking
4128
@item
4129
sha1.c  --  Implementation of Secure Hashing Algorithm 1
4130
@item
4131
string.c  --  Initialize/append/free dynamically-sized strings; see also sql_string.cc in the /sql directory
4132
@item
4133
testhash.c  --  Standalone program: test the hash library routines
4134
@item
4135
test_charset.c  --  Standalone program: display character set information
4136
@item
4137
test_dir.c  --  Standalone program: placeholder for "test all functions" idea
4138
@item
4139
test_fn.c  --  Standalone program: apparently tests a function
4140
@item
4141
test_xml.c  --  Standalone program: test XML routines
4142
@item
4143
thr_alarm.c  --  Thread alarms and signal handling
4144
@item
4145
thr_lock.c  --  "Read and write locks for Posix threads"
4146
@item
4147
thr_mutex.c  --  A wrapper for mutex functions
4148
@item
4149
thr_rwlock.c  --  Synchronizes the readers' thread locks with the writer's lock
4150
@item
4151
tree.c  --  Initialize/search/free binary trees
4152
@item
4153
typelib.c  --  Find a string in a set of strings; returns the offset to the string found
4154
@end itemize
4155 4156 4157
@*@*

You can find documentation for the main functions in these files
4158 4159
elsewhere in this document. For example, the main functions in my_getwd.c 
are described thus:
4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188
@*@*

@example
"int my_getwd _A((string buf, uint size, myf MyFlags)); @*
     int my_setwd _A((const char *dir, myf MyFlags)); @*
     Get and set working directory." @*
@end example

@subsection netware

Files related to the Novell NetWare version of MySQL.
@*@*

There are 39 files on this directory. Most have filename extensions of
*.def, *.sql, or *.c.
@*@*

The twenty-five *.def files are all from Novell Inc. They contain import or
export symbols. (".def" is a common filename extension for
"definition".)
@*@*

The two *.sql files are short scripts of SQL statements used in
testing.
@*@*

These are the five *.c files, all from Novell Inc.:
@itemize @bullet
@item
4189
libmysqlmain.c  --  Only one function: init_available_charsets()
4190
@item
4191
my_manage.c  --  Standalone management utility
4192
@item
4193
mysql_install_db.c  --  Compare \scripts\mysql_install_db.sh
4194
@item
4195
mysql_test_run.c  --  Short test program
4196
@item
4197
mysqld_safe.c  --  Compare \scripts\mysqld_safe.sh
4198 4199 4200
@end itemize

Perhaps the most important file is:
4201
@itemize @bullet
4202 4203 4204
@item
netware.patch  --  NetWare-specific build instructions and switches
(compare \mysql-4.1\ltmain.sh)
4205
@end itemize
4206 4207 4208
@*@*

For instructions about basic installation, see "Deployment Guide For
4209
NetWare AMP" at:
4210 4211 4212 4213 4214
@url{http://developer.novell.com/ndk/whitepapers/namp.htm}
@*

@subsection NEW-RPMS

4215
Directory to place RPMs while making a distribution.
4216 4217
@*@*

4218
This directory is not part of the Windows distribution. It is
4219
a temporary directory used during RPM builds with Linux distributions.
4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231
@*@*

@subsection os2

Routines for working with the OS2 operating system.
@*@*

The files in this directory are the product of the efforts of three
people from outside MySQL: Yuri Dario, Timo Maier, and John M
Alfredsson. There are no .C program files in this directory.
@*@*

4232
The contents of \os2 are:
4233
@itemize @bullet
4234
@item
4235
A Readme.Txt file
4236 4237 4238 4239 4240
@item
An \include subdirectory containing .h files which are for OS/2 only
@item
Files used in the build process (configuration, switches, and one
.obj)
4241
@end itemize
4242 4243 4244 4245 4246 4247 4248 4249
@*@*

The README file refers to MySQL version 3.23, which suggests that
there have been no updates for MySQL 4.0 for this section.
@*@*

@subsection pstack

4250
Process stack display (not currently used).
4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267
@*@*

This is a set of publicly-available debugging aids which all do pretty
well the same thing: display the contents of the stack, along with
symbolic information, for a running process. There are versions for
various object file formats (such as ELF and IEEE-695). Most of the
programs are copyrighted by the Free Software Foundation and are
marked as "part of GNU Binutils".
@*@*

In other words, the pstack files are not really part of the MySQL
library. They are merely useful when you re-program some MYSQL code
and it crashes.
@*@*

@subsection regex

4268
Henry Spencer's Regular Expression library for support of REGEXP function.
4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293
@*@*

This is the copyrighted product of Henry Spencer from the University
of Toronto. It's a fairly-well-known implementation of the
requirements of POSIX 1003.2 Section 2.8. The library is bundled with
Apache and is the default implementation for regular-expression
handling in BSD Unix. MySQL's Monty Widenius has made minor changes in
three programs (debug.c, engine.c, regexec.c) but this is not a MySQL
package. MySQL calls it only in order to support two MySQL functions:
REGEXP and RLIKE.
@*@*

Some of Mr Spencer's documentation for the regex library can be found
in the README and WHATSNEW files.
@*@*

One MySQL program which uses regex is \cmd-line-utils\libedit\search.c
@*@*

This program calls the 'regcomp' function, which is the entry point in
\regex\regexp.c.
@*@*

@subsection SCCS

4294
Source Code Control System (not part of source distribution).
4295 4296 4297 4298 4299 4300 4301 4302 4303
@*@*

You will see this directory if and only if you used BitKeeper for
downloading the source. The files here are for BitKeeper
administration and are not of interest to application programmers.
@*@*

@subsection scripts

4304
SQL batches, e.g. mysqlbug and mysql_install_db.
4305 4306
@*@*

4307
The *.sh filename extension stands for "shell script". Linux
4308
programmers use it where Windows programmers would use a *.bat
4309 4310 4311 4312
(batch filename extension).
@*@*

The *.sh files on this directory are:
4313
@itemize @bullet
4314
@item
4315
fill_help_tables.sh  --  Create help-information tables and insert
4316
@item
4317
make_binary_distribution.sh  --  Get configure information, make, produce tar
4318
@item
4319
msql2mysql.sh  --  Convert (partly) mSQL programs and scripts to MySQL
4320
@item
4321
mysqlbug.sh  --  Create a bug report and mail it
4322
@item
4323
mysqld_multi.sh  --  Start/stop any number of mysqld instances
4324
@item
4325
mysqld_safe-watch.sh  --  Start/restart in safe mode
4326
@item
4327
mysqld_safe.sh  --  Start/restart in safe mode
4328
@item
4329
mysqldumpslow.sh  --  Parse and summarize the slow query log
4330
@item
4331
mysqlhotcopy.sh  --  Hot backup
4332
@item
4333
mysql_config.sh  --  Get configuration information that might be needed to compile a client
4334
@item
4335
mysql_convert_table_format.sh  --  Conversion, e.g. from ISAM to MyISAM
4336
@item
4337
mysql_explain_log.sh  --  Put a log (made with --log) into a MySQL table
4338
@item
4339
mysql_find_rows.sh  --  Search for queries containing <regexp>
4340
@item
4341
mysql_fix_extensions.sh  --  Renames some file extensions, not recommended
4342
@item
4343 4344
mysql_fix_privilege_tables.sh  --  Fix mysql.user etc. when upgrading. Can be safely run during any upgrade to get the newest 
MySQL privilege tables
4345
@item
4346
mysql_install_db.sh  --  Create privilege tables and func table
4347
@item
4348
mysql_secure_installation.sh  --  Disallow remote root login, eliminate test, etc.
4349
@item
4350
mysql_setpermission.sh  --  Aid to add users or databases, sets privileges
4351 4352 4353
@item
mysql_tableinfo.sh  --  Puts info re MySQL tables into a MySQL table
@item
4354
mysql_zap.sh  --  Kill processes which match pattern
4355
@end itemize
4356 4357 4358 4359 4360 4361 4362 4363
@*@*

@subsection sql

Programs for handling SQL commands. The "core" of MySQL.
@*@*

These are the .c and .cc files in the sql directory:
4364
@itemize @bullet
4365
@item
4366
convert.cc  --  convert tables between different character sets
4367
@item
4368
derror.cc  --  read language-dependent message file
4369
@item
4370
des_key_file.cc  --  load DES keys from plaintext file
4371
@item
4372 4373
field.cc  --  "implement classes defined in field.h" (long); defines all storage methods MySQL uses to store field information 
into records that are then passed to handlers
4374
@item
4375
field_conv.cc  --  functions to copy data between fields
4376
@item
4377
filesort.cc  --  sort a result set, using memory or temporary files
4378
@item
4379
frm_crypt.cc  --  contains only one short function: get_crypt_for_frm
4380
@item
4381
gen_lex_hash.cc  --  Knuth's algorithm from Vol 3 Sorting and Searching, Chapter 6.3; used to search for SQL keywords in a query
4382
@item
4383
gstream.cc  --  GTextReadStream, used to read GIS objects
4384
@item
4385
handler.cc  --  handler-calling functions
4386
@item
4387
hash_filo.cc  --  static-sized hash tables, used to store info like hostname -> ip tables in a FIFO manner
4388
@item
4389
ha_berkeley.cc  --  Handler: BDB
4390
@item
4391
ha_heap.cc  --  Handler: Heap
4392
@item
4393
ha_innodb.cc  --  Handler: InnoDB
4394
@item
4395
ha_isam.cc  --  Handler: ISAM
4396 4397 4398
@item
ha_isammrg.cc  --  Handler: (ISAM MERGE)
@item
4399
ha_myisam.cc  --  Handler: MyISAM
4400 4401 4402
@item
ha_myisammrg.cc  --  Handler: (MyISAM MERGE)
@item
4403
hostname.cc  --  Given IP, return hostname
4404
@item
4405
init.cc  --  Init and dummy functions for interface with unireg
4406
@item
4407
item.cc  --  Item functions
4408
@item
4409
item_buff.cc  --  Buffers to save and compare item values
4410
@item
4411
item_cmpfunc.cc  --  Definition of all compare functions
4412
@item
4413
item_create.cc  --  Create an item. Used by lex.h.
4414
@item
4415
item_func.cc  --  Numerical functions
4416
@item
4417
item_row.cc  --  Row items for comparing rows and for IN on rows
4418
@item
4419
item_sum.cc  --  Set functions (SUM, AVG, etc.)
4420
@item
4421
item_strfunc.cc  --  String functions
4422
@item
4423
item_subselect.cc  --  Item subselect
4424
@item
4425
item_timefunc.cc  --  Date/time functions, e.g. week of year
4426
@item
4427
item_uniq.cc  --  Empty file, here for compatibility reasons
4428
@item
4429
key.cc  --  Functions to create keys from records and compare a key to a key in a record
4430
@item
4431
lock.cc  --  Locks
4432
@item
4433
log.cc  --  Logs
4434
@item
4435
log_event.cc  --  Log event (a binary log consists of a stream of log events)
4436
@item
4437
matherr.c  --  Handling overflow, underflow, etc.
4438
@item
4439
mf_iocache.cc  --  Caching of (sequential) reads and writes
4440
@item
4441
mini_client.cc  --  Client included in server for server-server messaging; used by the replication code
4442
@item
4443
mysqld.cc  --  Source of mysqld.exe; includes the main() program that starts mysqld, handling of signals and connections
4444
@item
4445
my_lock.c  --  Lock part of a file (like /mysys/my_lock.c, but with timeout handling for threads)
4446
@item
4447
net_serv.cc  --  Read/write of packets on a network socket
4448
@item
4449
nt_servc.cc  --  Initialize/register/remove an NT service
4450 4451
@item
opt_ft.cc  --  Create a FT or QUICK RANGE based on a key (very short)
4452 4453
@item
opt_range.cc  --  Range of keys
4454 4455 4456
@item
opt_sum.cc  --  Optimize functions in presence of (implied) GROUP BY
@item
4457
password.c  --  Password checking
4458
@item
4459
procedure.cc  --  Procedure interface, as used in SELECT * FROM Table_name PROCEDURE ANALYSE
4460
@item
4461
protocol.cc  --  Low level functions for PACKING data that is sent to client; actual sending done with net_serv.cc
4462
@item
4463
records.cc  --  Functions for easy reading of records, possible through a cache
4464
@item
4465
repl_failsafe.cc  --  Replication fail-save (not yet implemented)
4466
@item
4467
set_var.cc  --  Set and retrieve MySQL user variables
4468
@item
4469
slave.cc  --  Procedures for a slave in a master/slave (replication) relation
4470 4471 4472
@item
spatial.cc  --  Geometry stuff (lines, points, etc.)
@item
4473
sql_acl.cc  --  Functions related to ACL security; checks, stores, retrieves, and deletes MySQL user level privileges
4474
@item
4475
sql_analyse.cc  --  Implements the PROCEDURE analyse, which analyses a query result and returns the 'optimal' data type for each result column
4476
@item
4477
sql_base.cc  --  Basic functions needed by many modules, like opening and closing tables with table cache management
4478
@item
4479
sql_cache.cc  --  SQL query cache, with long comments about how caching works
4480
@item
4481
sql_class.cc  --  SQL class; implements the SQL base classes, of which THD (THREAD object) is the most important
4482
@item
4483
sql_crypt.cc  --  Encode / decode, very short
4484
@item
4485
sql_db.cc  --  Create / drop database
4486
@item
4487
sql_delete.cc  --  The DELETE statement
4488
@item
4489
sql_derived.cc  --  Derived tables, with long comments
4490
@item
4491
sql_do.cc  --  The DO statement
4492
@item
4493
sql_error.cc  --  Errors and warnings
4494
@item
4495
sql_handler.cc  --  Implements the HANDLER interface, which gives direct access to rows in MyISAM and InnoDB
4496
@item
4497
sql_help.cc  --  The HELP statement
4498
@item
4499
sql_insert.cc  --  The INSERT statement
4500
@item
4501 4502
sql_lex.cc  --  Does lexical analysis of a query; i.e. breaks a query string into pieces and determines the basic type (number,
string, keyword, etc.) of each piece
4503
@item
4504
sql_list.cc  --  Only list_node_end_of_list, short (the rest of the list class is implemented in sql_list.h)
4505
@item
4506
sql_load.cc  --  The LOAD DATA statement
4507
@item
4508
sql_map.cc  --  Memory-mapped files (not yet in use)
4509
@item
4510
sql_manager.cc  --  Maintenance tasks, e.g. flushing the buffers periodically; used with BDB table logs
4511
@item
4512
sql_olap.cc  --  ROLLUP
4513
@item
4514
sql_parse.cc  --  Parse an SQL statement; do initial checks and then jump to the function that should execute the statement
4515
@item
4516
sql_prepare.cc  --  Prepare an SQL statement
4517
@item
4518
sql_repl.cc  --  Replication
4519
@item
4520
sql_rename.cc  --  Rename table
4521
@item
4522
sql_select.cc  --  Select and join optimisation
4523
@item
4524
sql_show.cc  --  The SHOW statement
4525
@item
4526
sql_string.cc  --  String functions: alloc, realloc, copy, convert, etc.
4527
@item
4528
sql_table.cc  --  The DROP TABLE and ALTER TABLE statements
4529
@item
4530
sql_test.cc  --  Some debugging information
4531
@item
4532
sql_udf.cc  --  User-defined functions
4533
@item
4534
sql_union.cc  --  The UNION operator
4535
@item
4536
sql_update.cc  --  The UPDATE statement
4537
@item
4538
stacktrace.c  --  Display stack trace (Linux/Intel only)
4539
@item
4540
table.cc  --  Table metadata retrieval; read the table definition from a .frm file and store it in a TABLE object
4541
@item
4542
thr_malloc.cc  --  Thread-safe interface to /mysys/my_alloc.c
4543
@item
4544
time.cc  --  Date and time functions
4545
@item
4546
udf_example.cc  --  Example file of user-defined functions
4547
@item
4548
uniques.cc  --  Function to handle quick removal of duplicates
4549
@item
4550
unireg.cc  --  Create a unireg form file (.frm) from a FIELD and field-info struct
4551
@end itemize
4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565
@*@*

@subsection sql-bench

The MySQL Benchmarks.
@*@*

This directory has the programs and input files which MySQL uses for
its comparisons of MySQL, PostgreSQL, mSQL, Solid, etc. Since MySQL
publishes the comparative results, it's only right that it should make
available all the material necessary to reproduce all the tests.
@*@*

There are five subdirectories and sub-subdirectories:
4566
@itemize @bullet
4567
@item
4568
\Comments  --  Comments about results from tests of Access, Adabas, etc.
4569
@item
4570
\Data\ATIS  --  .txt files containing input data for the "ATIS" tests
4571
@item
4572
\Data\Wisconsin  --  .txt files containing input data for the "Wisconsin" tests
4573
@item
4574
\Results  --  old test results
4575
@item
4576
\Results-win32  --  old test results from Windows 32-bit tests
4577
@end itemize
4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591
@*@*

There are twenty-four *.sh (shell script) files, which involve Perl
programs.
@*@*

There are three *.bat (batch) files.
@*@*

There is one README file and one TODO file.
@*@*

@subsection SSL

4592 4593
Secure Sockets Layer; includes an example certification one can use
test an SSL (secure) database connection.
4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619
@*@*

This isn't a code directory. It contains a short note from Tonu Samuel
(the NOTES file) and seven *.pem files. PEM stands for "Privacy
Enhanced Mail" and is an Internet standard for adding security to
electronic mail. Finally, there are two short scripts for running
clients and servers over SSL connections.
@*@*

@subsection strings

The string library.
@*@*

Many of the files in this subdirectory are equivalent to well-known
functions that appear in most C string libraries. For those, there is
documentation available in most compiler handbooks.
@*@*

On the other hand, some of the files are MySQL additions or
improvements. Often the MySQL changes are attempts to optimize the
standard libraries. It doesn't seem that anyone tried to optimize for
recent Pentium class processors, though.
@*@*

The .C files are:
4620
@itemize @bullet
4621
@item
4622
atof.c  --  ascii-to-float, MySQL version
4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670
@item
bchange.c  --  short replacement routine written by Monty Widenius in
1987 
@item
bcmp.c  --  binary compare, rarely used 
@item
bcopy-duff.c  --  block copy: attempt to copy memory blocks faster
than cmemcpy 
@item
bfill.c  --  byte fill, to fill a buffer with (length) copies of a
byte 
@item
bmove.c  --  block move 
@item
bmove512.c  --  "should be the fastest way to move a multiple of 512
bytes" 
@item
bmove_upp.c  --  bmove.c variant, starting with last byte 
@item
bzero.c  --  something like bfill with an argument of 0 
@item
conf_to_src.c  --  reading a configuration file (NOTE TO SELF ? what's
this doing here?)
@item
ctype*.c  --  string handling programs for each char type MySQL
handles 
@item
do_ctype.c  --  display case-conversion and sort-conversion tables 
@item
int2str.c  --  integer-to-string 
@item
is_prefix.c  --  checks whether string1 starts with string2 
@item
llstr.c  --  convert long long to temporary-buffer string, return
pointer 
@item
longlong2str.c  --  ditto, but to argument-buffer 
@item
memcmp.c  --  memory compare 
@item
memset.c  --  memory set 
@item
my_vsnprintf.c  --  variant of printf 
@item
r_strinstr.c  --  see if one string is within another 
@item
str2int.c  --  convert string to integer 
@item
4671
strappend.c  --  fill up a string to n characters
4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690
@item
strcat.c  --  concatenate strings 
@item
strcend.c  --  point to where a character C occurs within str, or NULL
@item
strchr.c  --  point to first place in string where character occurs 
@item
strcmp.c  --  compare two strings 
@item
strcont.c  --  point to where any one of a set of characters appears
@item
strend.c  --  point to the '\0' byte which terminates str 
@item
strfill.c  --  fill a string with n copies of a byte 
@item
strinstr.c  --  find string within string 
@item
strlen.c  --  return length of string in bytes 
@item
4691
strmake.c  --  create new string from old string with fixed length, append end \0 if needed
4692
@item
4693
strmov.c  --  move source to dest and return pointer to end
4694
@item
4695
strnlen.c  --  return min(length of string, n)
4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718
@item
strnmov.c  --  move source to dest for source size, or for n bytes 
@item
strrchr.c  --  find a character within string, searching from end 
@item
strstr.c  --  find an instance of pattern within source 
@item
strto.c  --  string to long, to long long, to unsigned long, etc. 
@item
strtol.c  --  string to long 
@item
strtoll.c  --  string to long long 
@item
strtoul.c  --  string to unsigned long 
@item
strtoull.c  --  string to unsigned long long 
@item
strxmov.c  --  move a series of concatenated source strings to dest 
@item
strxnmov.c  --  like strxmov.c but with a maximum length n 
@item
str_test.c  --  test of all the string functions encoded in assembler 
@item
4719
udiv.c  --  unsigned long divide, for operating systems that don't support these
4720
@item
4721
xml.c  --  read and parse XML strings; used to read character definition information stored in /sql/share/charsets
4722
@end itemize
4723 4724 4725 4726 4727 4728 4729 4730 4731 4732
@*@*

There are also four .ASM files -- macros.asm, ptr_cmp.asm,
strings.asm, and strxmov.asm -- which can replace some of the
C-program functions. But again, they look like optimizations for old
members of the Intel processor family.
@*@*

@subsection support-files

4733
Files used to build MySQL on different systems.
4734 4735 4736 4737
@*@*

The files here are for building ("making") MySQL given a package
manager, compiler, linker, and other build tools. The support files
4738 4739 4740
provide instructions and switches for the build processes. They 
include example my.cnf files one can use as a default setup for
MySQL.
4741 4742 4743 4744
@*@*

@subsection tests

4745
Tests in Perl and in C.
4746 4747
@*@*

4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767
The files in this directory are test programs that can be used 
as a base to write a program to simulate problems in MySQL in various
scenarios: forks, locks, big records, exporting, truncating, and so on. 
Some examples are:
@itemize @bullet
@item
connect_test.c  --  test that a connect is possible
@item
insert_test.c  --  test that an insert is possible
@item
list_test.c  --  test that a select is possible
@item
select_test.c  --  test that a select is possible
@item
showdb_test.c  --  test that a show-databases is possible
@item
ssl_test.c  --  test that SSL is possible
@item
thread_test.c  --  test that threading is possible
@end itemize
4768 4769 4770 4771 4772 4773 4774 4775
@*@*

@subsection tools

Tools -- well, actually, one tool.
@*@*

The only file is:
4776
@itemize @bullet
4777
@item
4778 4779 4780
mysqlmanager.c  --  A "server management daemon" by Sasha Pachev. This
is a tool under development and is not yet useful. Related to fail-safe 
replication.
4781
@end itemize
4782 4783 4784 4785 4786 4787 4788 4789 4790 4791
@*@*

@subsection VC++Files

Visual C++ Files.
@*@*

Includes this entire directory, repeated for VC++ (Windows) use.
@*@*

4792 4793 4794 4795 4796 4797
VC++Files includes a complete environment to compile MySQL with the VC++
compiler. To use it, just copy the files on this directory; the make_win_src_distribution.sh
script uses these files to create a Windows source installation.
@*@*

This directory has subdirectories which are copies of the main directories.
4798 4799 4800 4801
For example, there is a subdirectory \VC++Files\heap, which has the Microsoft
developer studio project file to compile \heap with VC++. So for a description 
of the files in \VC++Files\heap, see the description of the files in \heap. The 
same applies for almost all of VC++Files's subdirectories (bdb, client,
4802 4803 4804 4805 4806 4807 4808 4809
isam, libmysql, etc.). The difference is that the \VC++Files variants
are specifically for compilation with Microsoft Visual C++ in 32-bit
Windows environments.
@*@*

In addition to the "subdirectories which are duplicates of
directories", VC++Files contains these subdirectories, which are not
duplicates:
4810
@itemize @bullet
4811
@item
4812
comp_err  --  (nearly empty)
4813
@item
4814
contrib  --  (nearly empty)
4815
@item
4816
InstallShield  --  script files
4817
@item
4818
isamchk  --  (nearly empty)
4819
@item
4820
libmysqltest  --  one small non-MySQL test program: mytest.c
4821
@item
4822
myisamchk  --  (nearly empty)
4823
@item
4824
myisamlog  --  (nearly empty)
4825
@item
4826
myisammrg  --  (nearly empty)
4827
@item
4828
mysqlbinlog  --  (nearly empty)
4829
@item
4830
mysqlmanager  --  MFC foundation class files created by AppWizard
4831
@item
4832
mysqlserver  --  (nearly empty)
4833
@item
4834
mysqlshutdown  --  one short program, mysqlshutdown.c
4835
@item
4836
mysqlwatch.c  --  Windows service initialization and monitoring
4837
@item
4838
my_print_defaults  --  (nearly empty)
4839
@item
4840
pack_isam  --  (nearly empty)
4841
@item
4842
perror  --  (nearly empty)
4843
@item
4844
prepare  --  (nearly empty)
4845
@item
4846
replace  --  (nearly empty)
4847
@item
4848
SCCS  --  source code control system
4849
@item
4850
test1  --  tests connecting via X threads
4851
@item
4852
thr_insert_test  --  (nearly empty)
4853 4854 4855
@item
thr_test  --  one short program used to test for memory-allocation bug
@item
4856
winmysqladmin  --  the winmysqladmin.exe source
4857
@end itemize
4858 4859
@*@*

4860 4861 4862 4863 4864 4865
The "nearly empty" subdirectories noted above (e.g. comp_err and isamchk) 
are needed because VC++ requires one directory per project (i.e. executable). 
We are trying to keep to the MySQL standard source layout and compile only 
to different directories.
@*@*

4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882
@subsection vio

Virtual I/O Library.
@*@*

The VIO routines are wrappers for the various network I/O calls that
happen with different protocols. The idea is that in the main modules
one won't have to write separate bits of code for each protocol. Thus
vio's purpose is somewhat like the purpose of Microsoft's winsock
library.
@*@*

The underlying protocols at this moment are: TCP/IP, Named Pipes (for
WindowsNT), Shared Memory, and Secure Sockets (SSL).
@*@*

The C programs are:
4883
@itemize @bullet
4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903
@item
test-ssl.c  --  Short standalone test program: SSL 
@item
test-sslclient.c  --  Short standalone test program: clients 
@item
test-sslserver.c  --  Short standalone test program: server 
@item
vio.c  --  Declarations + open/close functions 
@item
viosocket.c  --  Send/retrieve functions 
@item
viossl.c  --  SSL variations for the above 
@item
viosslfactories.c  --  Certification / Verification 
@item
viotest.cc  --  Short standalone test program: general 
@item
viotest-ssl.c  --  Short standalone test program: SSL 
@item
viotest-sslconnect.cc  --  Short standalone test program: SSL connect 
4904
@end itemize
4905 4906 4907 4908 4909 4910 4911 4912
@*@*

The older functions -- raw_net_read, raw_net_write -- are now
obsolete.
@*@*

@subsection zlib

4913 4914 4915 4916 4917 4918
Data compression library, used on Windows.
@*@*

zlib is a data compression library used to support the compressed
protocol and the COMPRESS/UNCOMPRESS functions under Windows.
On Unix, MySQL uses the system libgz.a library for this purpose.
4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944
@*@*

Zlib -- which presumably stands for "Zip Library" -- is not a MySQL
package. It was produced by the GNU Zip (gzip.org) people. Zlib is a
variation of the famous "Lempel-Ziv" method, which is also used by
"Zip". The method for reducing the size of any arbitrary string of
bytes is as follows:
@itemize @bullet
@item
Find a substring which occurs twice in the string. 
@item
Replace the second occurrence of the substring with (a) a pointer to
the first occurrence, plus (b) an indication of the length of the
first occurrence. 
@end itemize

There is a full description of the library's functions in the gzip
manual at: @*
@url{http://www.gzip.org/zlib/manual.html} @*
There is therefore no need to list the modules in this document.
@*@*

The MySQL program that uses zlib is \mysys\my_compress.c. The use is
for packet compression. The client sends messages to the server which
are compressed by zlib. See also: \sql\net_serv.cc.

4945
@node Files in InnoDB Sources,,Files in MySQL Sources,Top
4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049
@chapter Annotated List Of Files in the InnoDB Source Code Distribution

ERRATUM BY HEIKKI TUURI (START)
@*@*

Errata about InnoDB row locks:@*@*

@example
  #define LOCK_S  4 /* shared */
  #define LOCK_X  5 /* exclusive */
...
@strong{/* Waiting lock flag */}
  #define LOCK_WAIT 256
/* this wait bit should be so high that it can be ORed to the lock
mode and type; when this bit is set, it means that the lock has not
yet been granted, it is just waiting for its turn in the wait queue */
...
@strong{/* Precise modes */}
  #define LOCK_ORDINARY 0
/* this flag denotes an ordinary next-key lock in contrast to LOCK_GAP
or LOCK_REC_NOT_GAP */
  #define LOCK_GAP 512
/* this gap bit should be so high that it can be ORed to the other
flags; when this bit is set, it means that the lock holds only on the
gap before the record; for instance, an x-lock on the gap does not
give permission to modify the record on which the bit is set; locks of
this type are created when records are removed from the index chain of
records */
  #define LOCK_REC_NOT_GAP 1024
/* this bit means that the lock is only on the index record and does
NOT block inserts to the gap before the index record; this is used in
the case when we retrieve a record with a unique key, and is also used
in locking plain SELECTs (not part of UPDATE or DELETE) when the user
has set the READ COMMITTED isolation level */
  #define LOCK_INSERT_INTENTION 2048
/* this bit is set when we place a waiting gap type record lock
request in order to let an insert of an index record to wait until
there are no conflicting locks by other transactions on the gap; note
that this flag remains set when the waiting lock is granted, or if the
lock is inherited to a neighboring record */
@end example
@*

ERRATUM BY HEIKKI TUURI (END)
@*@*

The InnoDB source files are the best place to look for information
about internals of the file structure that MySQLites can optionally
use for transaction support. But when you first look at all the
subdirectories and file names you'll wonder: Where Do I Start? It can
be daunting.
@*@*

Well, I've been through that phase, so I'll pass on what I had to
learn on the first day that I looked at InnoDB source files. I am very
sure that this will help you grasp, in overview, the organization of
InnoDB modules. I'm also going to add comments about what is going on
-- which you should mistrust! These comments are reasonable working
hypotheses; nevertheless, they have not been subjected to expert peer
review.
@*@*

Here's how I'm going to organize the discussion. I'll take each of the
32 InnoDB subdirectories that come with the MySQL 4.0 source code in
\mysql\innobase (on my Windows directory). The format of each section
will be like this every time:
@*@*

@strong{\subdirectory-name (LONGER EXPLANATORY NAME)}@*
@multitable @columnfractions .10 .20 .40 .50
@item @strong{File Name} @tab @strong{What Name Stands For} @tab @strong{Size} @tab @strong{Comment Inside File}
@item file-name
@tab my-own-guess
@tab in-bytes
@tab from-the-file-itself
@end multitable
...@*
My-Comments@*
@*

For example: @*
@example
"
@strong{\ha (HASHING)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  ha0ha.c     Hashing/Hashing        7,452   Hash table with external chains

  Comments about hashing will be here.
"
@end example
@*

The "Comment Inside File" column is a direct copy from the first /*
comment */ line inside the file. All other comments are mine. After
I've discussed each directory, I'll finish with some notes about
naming conventions and a short list of URLs that you can use for
further reference.
@*@*

Now let's begin.
@*@*

@example
5050

5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372
@strong{\ha (HASHING)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  ha0ha.c     Hashing / Hashing      7,452   Hash table with external chains

I'll hold my comments until the next section, \hash (HASHING).

@strong{\hash (HASHING)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  hash0hash.c Hashing / Hashing      3,257   Simple hash table utility

The two C programs in the \ha and \hashing directories -- ha0ha.c and
hash0hash.c -- both refer to a "hash table" but hash0hash.c is
specialized, it is mostly about accessing points in the table under
mutex control.

When a "database" is so small that InnoDB can load it all into memory
at once, it's more efficient to access it via a hash table. After all,
no disk i/o can be saved by using an index lookup, if there's no disk.

@strong{\os (OPERATING SYSTEM)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  os0shm.c    OS / Shared Memory     3,150   To shared memory primitives
  os0file.c   OS / File             64,412   To i/o primitives
  os0thread.c OS / Thread            6,827   To thread control primitives
  os0proc.c   OS / Process           3,700   To process control primitives
  os0sync.c   OS / Synchronization  10,208   To synchronization primitives

This is a group of utilities that other modules may call whenever they
want to use an operating-system resource. For example, in os0file.c
there is a public InnoDB function named os_file_create_simple(), which
simply calls the Windows-API function CreateFile. Naturally the
contents of this group are somewhat different for other operating systems.

The "Shared Memory" functions in os0shm.c are only called from the
communications program com0shm.c (see \com COMMUNICATIONS). The i/o
and thread-control primitives are called extensively. The word
"synchronization" in this context refers to the mutex-create and
mutex-wait functionality.

@strong{\ut (UTILITIES)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  ut0ut.c     Utilities / Utilities  7,041   Various utilities
  ut0byte.c   Utilities / Debug      1,856   Byte utilities
  ut0rnd.c    Utilities / Random     1,475   Random numbers and hashing
  ut0mem.c    Utilities / Memory     5,530   Memory primitives
  ut0dbg.c    Utilities / Debug        642   Debug utilities

The two functions in ut0byte.c are just for lower/upper case
conversion and comparison. The single function in ut0rnd.c is for
finding a prime slightly greater than the given argument, which is
useful for hash functions, but unrelated to randomness. The functions
in ut0mem.c are wrappers for "malloc" and "free" calls -- for the
real "memory" module see section \mem (MEMORY). Finally, the
functions in ut0ut.c are a miscellany that didn't fit better elsewhere:
get_high_bytes, clock, time, difftime, get_year_month_day, and "sprintf"
for various diagnostic purposes.

In short: the \ut group is trivial.

@strong{\buf (BUFFERING)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  buf0buf.c   Buffering / Buffering 53,246   The database buffer buf_pool
  buf0flu.c   Buffering / Flush     23,711   ... flush algorithm
  buf0lru.c   / least-recently-used 20,245   ... replacement algorithm
  buf0rea.c   Buffering / read      17,399   ... read

There is a separate file group (\mem MEMORY) which handles memory
requests in general.A "buffer" usually has a more specific
definition, as a memory area which contains copies of pages that
ordinarily are in the main data file. The "buffer pool" is the set
of all buffers (there are lots of them because InnoDB doesn't
depend on the OS's caching to make things faster).

The pool size is fixed (at the time of this writing) but the rest of
the buffering architecture is sophisticated, involving a host of
control structures. In general: when InnoDB needs to access a new page
it looks first in the buffer pool; InnoDB reads from disk to a new
buffer when the page isn't there; InnoDB chucks old buffers (basing
its decision on a conventional Least-Recently-Used algorithm) when it
has to make space for a new buffer.

There are routines for checking a page's validity, and for read-ahead.
An example of "read-ahead" use: if a sequential scan is going on, then
a DBMS can read more than one page at a time, which is efficient
because reading 32,768 bytes (two pages) takes less than twice as long
as reading 16,384 bytes (one page).

@strong{\btr (B-TREE)}
  File Name   What Name Stands For         Size     Comment Inside File
  ---------   --------------------         ------   -------------------
  btr0btr.c   B-tree / B-tree              74,255   B-tree
  btr0cur.c   B-tree / Cursor              94,950   index tree cursor
  btr0sea.c   B-tree / Search              36,580   index tree adaptive search
  btr0pcur.c  B-tree / persistent cursor   14,548   index tree persistent cursor

If you total up the sizes of the C files, you'll see that \btr is the
second-largest file group in InnoDB. This is understandable because
maintaining a B-tree is a relatively complex task. Luckily, there has
been a lot of work done to describe efficient management of B-tree and
B+-tree structures, much of it open-source or public-domain, since
their original invention over thirty years ago.

InnoDB likes to put everything in B-trees. This is what I'd call a
"distinguishing characteristic" because in all the major DBMSs (like
IBM DB2, Microsoft SQL Server, and Oracle), the main or default or
classic structure is the heap-and-index. In InnoDB the main structure
is just the index. To put it another way: InnoDB keeps the rows in the
leaf node of the index, rather than in a separate file. Compare
Oracle's Index Organized Tables, and Microsoft SQL Server's Clustered
Indexes.

This, by the way, has some consequences. For example, you may as well
have a primary key since otherwise InnoDB will make one anyway. And
that primary key should be the shortest of the candidate keys, since
InnoDB
will use it as a pointer if there are secondary indexes.

Most importantly, it means that rows have no fixed address. Therefore
the routines for managing file pages should be good. We'll see about
that when we look at the \row (ROW) program group later.

@strong{\com (COMMUNCATION)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  com0com.c   Communication          6,913   Communication primitives
  com0shm.c   Communication /       24,633   ... through shared memory
              Shared Memory

The communication primitives in com0com.c are said to be modelled
after the ones in Microsoft's winsock library (the Windows Sockets
interface). The communication primitives in com0shm.c are at a
slightly lower level, and are called from the routines in com0com.c.

I was interested in seeing how InnoDB would handle inter-process
communication, since there are many options -- named pipes, TCP/IP,
Windows messaging, and Shared Memory being the main ones that come to
mind. It appears that InnoDB prefers Shared Memory. The main idea is:
there is an area of memory which two different processes (or threads,
of course) can both access. To communicate, a thread gets an
appropriate mutex, puts in a request, and waits for a response. Thread 
interaction is also a subject for the os0thread.c program in another 
program group, \os (OPERATING SYSTEM).

@strong{\dyn (DYNAMICALLY ALLOCATED ARRAY)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  dyn0dyn.c   Dynamic / Dynamic        994   dynamically allocated array

There is a single function in the dyn0dyn.c program, for adding a
block to the dynamically allocated array. InnoDB might use the array
for managing concurrency between threads.

At the moment, the \dyn program group is trivial.

@strong{\fil (FILE)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  fil0fil.c   File / File           39,725   The low-level file system

The reads and writes to the database files happen here, in
co-ordination with the low-level file i/o routines (see os0file.h in
the \os program group).

Briefly: a table's contents are in pages, which are in files, which
are in tablespaces. Files do not grow; instead one can add new files
to the tablespace. As we saw earlier (discussing the \btr program group)
the pages are nodes of B-trees. Since that's the case, new additions can
happen at various places in the logical file structure, not
necessarily at the end. Reads and writes are asynchronous, and go into
buffers, which are set up by routines in the \buf program group.

@strong{\fsp (FILE SPACE)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  fsp0fsp.c   File Space Management 100,271  File space management

I would have thought that the \fil (FILE) and \fsp (FILE SPACE)
MANAGEMENT programs would fit together in the same program group;
however, I guess the InnoDB folk are splitters rather than lumpers.

It's in fsp0fsp.c that one finds some of the descriptions and comments
of extents, segments, and headers. For example, the "descriptor bitmap
of the pages in the extent" is in here, and you can find as well how
the free-page list is maintained, what's in the bitmaps, and what
various header fields' contents are.

@strong{\fut (FILE UTILITY)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  fut0fut.c   File Utility / Utility   293   File-based utilities
  fut0lst.c   File Utility / List   14,129   File-based list utilities

Mainly these small programs affect only file-based lists, so maybe
saying "File Utility" is too generic. The real work with data files 
goes on in the \fsp program group.

@strong{\log (LOGGING)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  log0log.c   Logging / Logging     77,834   Database log
  log0recv.c  Logging / Recovery    80,701   Recovery

I've already written about the \log program group, so here's a link to
my previous article: "How Logs work with MySQL and InnoDB":
@url{http://www.devarticles.com/art/1/181/2}

@strong{\mem (MEMORY)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  mem0mem.c   Memory / Memory        9,971   The memory management
  mem0dbg.c   Memory / Debug        21,297   ... the debug code
  mem0pool.c  Memory / Pool         16,293   ... the lowest level

There is a long comment at the start of the mem0pool.c program, which
explains what the memory-consumers are, and how InnoDB tries to
satisfy them. The main thing to know is that there are really three
pools: the buffer pool (see the \buf program group), the log pool (see the \log
program group), and the common pool, which is where everything that's
not in the buffer or log pools goes (for example the parsed SQL
statements and the data dictionary cache).

@strong{\mtr (MINI-TRANSACTION)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  mtr0mtr.c   Mini-transaction /    12,433   Mini-transaction buffer
  mtr0log.c   Mini-transaction / Log 8,180   ... log routines

The mini-transaction routines are called from most of the other
program groups. I'd describe this as a low-level utility set.

@strong{\que (QUERY GRAPH)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  que0que.c   Query Graph / Query   35,964   Query graph

The program que0que.c ostensibly is about the execution of stored
procedures which contain commit/rollback statements. I took it that
this has little importance for the average MySQL user.

@strong{\rem (RECORD MANAGER)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  rem0rec.c   Record Manager        14,961   Record Manager
  rem0cmp.c   Record Manager /      25,263   Comparison services for records
              Comparison

There's an extensive comment near the start of rem0rec.c title
"Physical Record" and it's recommended reading. At some point you'll
ask what are all those bits that surround the data in the rows on a page, 
and this is where you'll find the answer.

@strong{\row (ROW)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  row0row.c   Row / Row             16,764   General row routines
  row0uins.c  Row / Undo Insert      7,199   Fresh insert undo
  row0umod.c  Row / Undo Modify     17,147   Undo modify of a row
  row0undo.c  Row / Undo            10,254   Row undo
  row0vers.c  Row / Version         12,288   Row versions
  row0mysql.c Row / MySQL           63,556   Interface [to MySQL]
  row0ins.c   Row / Insert          42,829   Insert into a table
  row0sel.c   Row / Select          85,923   Select
  row0upd.c   Row / Update          44,456   Update of a row
  row0purge.c Row / Purge           14,961   Purge obsolete records

Rows can be selected, inserted, updated/deleted, or purged (a
maintenance activity). These actions have ancillary actions, for
example after insert there can be an index-update test, but it seems 
to me that sometimes the ancillary action has no MySQL equivalent (yet) 
and so is inoperative.

Speaking of MySQL, notice that one of the larger programs in the \row
program group is the "interface between Innobase row operations and
MySQL" (row0mysql.c) -- information interchange happens at this level
because rows in InnoDB and in MySQL are analogous, something which
can't be said for pages and other levels.

@strong{\srv (Server)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  srv0srv.c   Server / Server       79,058   Server main program
  srv0que.c   Server / Query         2,361   Server query execution
  srv0start.c Server / Start        34,586   Starts the server

This is where the server reads the initial configuration files, splits
up the threads, and gets going. There is a long comment deep in the
program (you might miss it at first glance) titled "IMPLEMENTATION OF
THE SERVER MAIN PROGRAM" in which you'll find explanations about
thread priority, and about what the responsibiities are for various 
thread types.

InnoDB has many threads, for example "user threads" (which wait for
client requests and reply to them), "parallel communication threads"
(which take part of a user thread's job if a query process can be
split), "utility threads" (background priority), and a "master thread"
(high priority, usually asleep).

@strong{\thr (Thread Local Storage)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  thr0loc.c   Thread / Local         5,261   The thread local storage

InnoDB doesn't use the Windows-API thread-local-storage functions,
perhaps because they're not portable enough.

@strong{\trx (Transaction)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  trx0trx.c   Transaction /         37,447   The transaction
  trx0purge.c Transaction / Purge   26,782   ... Purge old versions
  trx0rec.c   Transaction / Record  36,525   ... Undo log record
  trx0sys.c   Transaction / System  20,671   ... System
  trx0rseg.c  / Rollback segment     6,214   ... Rollback segment
  trx0undo.c  Transaction / Undo    46,595   ... Undo log

InnoDB's transaction management is supposedly "in the style of Oracle"
and that's close to true but can mislead you. 
5373
@itemize
5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390
@item
First: InnoDB uses rollback segments like Oracle8i does -- but
Oracle9i uses a different name 
@item
Second: InnoDB uses multi-versioning like Oracle does -- but I see
nothing that looks like an Oracle ITL being stored in the InnoDB data
pages. 
@item
Third: InnoDB and Oracle both have short (back-to-statement-start)
versioning for the READ COMMITTED isolation level and long
(back-to-transaction-start) versioning for higher levels -- but InnoDB
and Oracle have different "default" isolation levels. 
@item
Finally: InnoDB's documentation says it has to lock "the gaps before
index keys" to prevent phantoms -- but any Oracle user will tell you that
phantoms are impossible anyway at the SERIALIZABLE isolation level, so 
key-locks are unnecessary.
5391
@end itemize
5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582

The main idea, though, is that InnoDB has multi-versioning. So does
Oracle. This is very different from the way that DB2 and SQL Server do
things.

@strong{\usr (USER)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  usr0sess.c  User / Session        27,415   Sessions

One user can have multiple sessions (the session being all the things
that happen betweeen a connect and disconnect). This is where InnoDB
tracks session IDs, and server/client messaging. It's another of those
items which is usually MySQL's job, though.

@strong{\data (DATA)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  data0data.c Data / Data           26,002   SQL data field and tuple
  data0type.c Data / Type            2,122   Data types

This is a collection of minor utility routines affecting rows.

@strong{\dict (DICTIONARY)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  dict0dict.c Dictionary / Dictionary 84,667 Data dictionary system
  dict0boot.c Dictionary / boot     12,134   ... creation and booting
  dict0load.c Dictionary / load     26,546   ... load to memory cache
  dict0mem.c  Dictionary / memory    8,221   ... memory object creation

The data dictionary (known in some circles as the catalog) has the
metadata information about objects in the database -- column sizes,
table names, and the like.

@strong{\eval (EVALUATING)}
  File Name   What Name Stands For  Size    Comment Inside File
  ---------   --------------------  ------  -------------------
  eval0eval.c Evaluating/Evaluating 15,682  SQL evaluator
  eval0proc.c Evaluating/Procedures  5,000  Executes SQL procedures

The evaluating step is a late part of the process of interpreting an
SQL statement -- parsing has already occurred during \pars (PARSING).

The ability to execute SQL stored procedures is an InnoDB feature, but
not a MySQL feature, so the eval0proc.c program is unimportant.

@strong{\ibuf (INSERT BUFFER)}
  File Name   What Name Stands For  Size     Comment Inside File
  ---------   --------------------  ------   -------------------
  ibuf0ibuf.c Insert Buffer /       69,884   Insert buffer

The words "Insert Buffer" mean not "buffer used for INSERT" but
"insertion of a buffer into the buffer pool" (see the \buf BUFFER
program group description). The matter is complex due to possibilities
for deadlocks, a problem to which the comments in the ibuf0ibuf.c 
program devote considerable attention.

@strong{\mach (MACHINE FORMAT)}
  File Name   What Name Stands For  Size    Comment Inside File
  ---------   --------------------  ------  -------------------
  mach0data.c Machine/Data           2,319  Utilities for converting

The mach0data.c program has two small routines for reading compressed
ulints (unsigned long integers).

@strong{\lock (LOCKING)}
  File Name   What Name Stands For  Size    Comment Inside File
  ---------   --------------------  ------  -------------------
  lock0lock.c Lock / Lock           127,646 The transaction lock system

If you've used DB2 or SQL Server, you might think that locks have their
own in-memory table, that row locks might need occasional escalation to 
table locks, and that there are three lock types: Shared, Update, Exclusive. 

All those things are untrue with InnoDB! Locks are kept in the database 
pages. A bunch of row locks can't be rolled together into a single table 
lock. And most importantly there's only one lock type. I call this type 
"Update" because it has the characteristics of DB2 / SQL Server Update 
locks, that is, it blocks other updates but doesn't block reads. 
Unfortunately, InnoDB comments refer to them as "x-locks" etc.

To sum it up: if your background is Oracle you won't find too much
surprising, but if your background is DB2 or SQL Server the locking
concepts and terminology will probably confuse you at first.

You can find an online article about the differences between
Oracle-style and DB2/SQL-Server-style locks at:
@url{http://dbazine.com/gulutzan6.html}

@strong{\odbc (ODBC)}
  File Name   What Name Stands For Size    Comment Inside File
  ---------   --------------------  ------  -------------------
  odbc0odbc.c ODBC / ODBC           16,865  ODBC client library

The odbc0odbc.c program has a small selection of old ODBC-API
functions: SQLAllocEnv, SQLAllocConnect, SQLAllocStmt, SQLConnect, 
SQLError, SQLPrepare, SQLBindParameter, SQLExecute.

@strong{\page (PAGE)}
  File Name   What Name Stands For  Size    Comment Inside File
  ---------   --------------------  ------  -------------------
  page0page.c Page / Page           44,309  Index page routines
  page0cur.c  Page / Cursor         30,305  The page cursor

It's in the page0page.c program that you'll learn as follows: index
pages start with a header, entries in the page are in order, at the
end of the page is a sparse "page directory" (what I would have called
a slot table) which makes binary searches easier.

Incidentally, the program comments refer to "a page size of 8 kB"
which seems obsolete. In univ.i (a file containing universal
constants) the page size is now #defined as 16KB.

@strong{\pars (PARSING)}
  File Name   What Name Stands For Size    Comment Inside File
  ---------   -------------------- ------  -------------------
  pars0pars.c Parsing/Parsing      49,947  SQL parser
  pars0grm.c  Parsing/Grammar      62,685  A Bison parser
  pars0opt.c  Parsing/Optimizer    30,809  Simple SQL Optimizer
  pars0sym.c  Parsing/Symbol Table  5,541  SQL parser symbol table
  lexyy.c     ?/Lexer              59,948  Lexical scanner

The job is to input a string containing an SQL statement and output an
in-memory parse tree. The EVALUATING (subdirectory \eval) programs
will use the tree.

As is common practice, the Bison and Flex tools were used -- pars0grm.c 
is what the Bison parser produced from an original file named pars0grm.y 
(not supplied), and lexyy.c is what Flex produced.

Since InnoDB is a DBMS by itself, it's natural to find SQL parsing in
it. But in the MySQL/InnoDB combination, MySQL handles most of the
parsing. These files are unimportant.

@strong{\read (READ)}
  File Name   What Name Stands For Size    Comment Inside File
  ---------   -------------------- ------  -------------------
  read0read.c Read / Read           6,244  Cursor read

The read0read.c program opens a "read view" of a query result, using
some functions in the \trx program group.

@strong{\sync (SYNCHRONIZATION)}
  File Name   What Name Stands For Size    Comment Inside File
  ---------   -------------------- ------  -------------------
  sync0sync.c Synchronization /    35,918  Mutex, the basic sync primitive
  sync0arr.c  ... / array          26,461  Wait array used in primitives
  sync0ipm.c  ... / interprocess    4,027  for interprocess sync
  sync0rw.c   ... / read-write     22,220  read-write lock for thread sync

A mutex (Mutual Exclusion) is an object which only one thread/process
can hold at a time. Any modern operating system API has some functions
for mutexes; however, as the comments in the sync0sync.c code indicate, it
can be faster to write one's own low-level mechanism. In fact the old
assembly-language XCHG trick is in here -- this is the only program
that contains any assembly code.
@end example
@*
@*

This is the end of the section-by-section account of InnoDB
subdirectories.
@*@*

@strong{A Note About File Naming} @*@*

There appears to be a naming convention. The first letters of the file
name are the same as the subdirectory name, then there is a '0'
separator, then there is an individual name. For the main program in a
subdirectory, the individual name may be a repeat of the subdirectory
name. For example, there is a file named ha0ha.c (the first two
letters ha mean "it's in in subdirectory ..\ha", the next letter 0
means "0 separator", the next two letters mean "this is the main ha
program"). This naming convention is not strict, though: for example
the file lexyy.c is in the \pars subdirectory.
@*@*

@strong{A Note About Copyrights} @*@*

Most of the files begin with a copyright notice or a creation date,
for example "Created 10/25/1995 Heikki Tuuri". I don't know a great
deal about the history of InnoDB, but found it interesting that most
creation dates were between 1994 and 1998.
@*@*

@strong{References} @*@*

Ryan Bannon, Alvin Chin, Faryaaz Kassam and Andrew Roszko @*
"InnoDB Concrete Architecture" @*
@url{http://www.swen.uwaterloo.ca/~mrbannon/cs798/assignment_02/innodb.pdf}
5583

5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597
A student paper. It's an interesting attempt to figure out InnoDB's
architecture using tools, but I didn't end up using it for the specific 
purposes of this article.
@*@*

Peter Gulutzan @*
"How Logs Work With MySQL And InnoDB" @*
@url{http://www.devarticles.com/art/1/181/2}
@*@*

Heikki Tuuri @*
"InnoDB Engine in MySQL-Max-3.23.54 / MySQL-4.0.9: The Up-to-Date
Reference Manual of InnoDB" @*
@url{http://www.innodb.com/ibman.html}
5598

5599 5600 5601 5602
This is the natural starting point for all InnoDB information. Mr
Tuuri also appears frequently on MySQL forums.
@*@*

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5603 5604 5605 5606
@summarycontents
@contents

@bye