File Coverage

blib/lib/DBIx/Admin/CreateTable.pm
Criterion Covered Total %
statement 9 95 9.4
branch 0 74 0.0
condition 0 8 0.0
subroutine 3 11 27.2
pod 4 8 50.0
total 16 196 8.1


line stmt bran cond sub pod time code
1             package DBIx::Admin::CreateTable;
2              
3 2     2   61645 use strict;
  2         5  
  2         85  
4 2     2   12 use warnings;
  2         5  
  2         62  
5              
6 2     2   6094 use Moo;
  2         63385  
  2         12  
7              
8             has db_vendor =>
9             (
10             is => 'rw',
11             default => sub{return ''},
12             required => 0,
13             );
14              
15             has dbh =>
16             (
17             is => 'rw',
18             isa => sub{die "The 'dbh' parameter to new() is mandatory\n" if (! $_[0])},
19             default => sub{return ''},
20             required => 0,
21             );
22              
23             has primary_index_name =>
24             (
25             is => 'rw',
26             default => sub{return {} },
27             required => 0,
28             );
29              
30             has sequence_name =>
31             (
32             is => 'rw',
33             default => sub{return {} },
34             required => 0,
35             );
36              
37             has verbose =>
38             (
39             is => 'rw',
40             default => sub{return 0},
41             required => 0,
42             );
43              
44             our $VERSION = '2.10';
45              
46             # -----------------------------------------------
47              
48             sub BUILD
49             {
50 0     0 0   my($self) = @_;
51              
52 0           $self -> db_vendor(uc $self -> dbh -> get_info(17) ); # SQL_DBMS_NAME.
53              
54 0 0         print STDERR __PACKAGE__, '. Db vendor ' . $self -> db_vendor . ". \n" if ($self -> verbose);
55              
56             } # End of BUILD.
57              
58             # --------------------------------------------------
59              
60             sub create_table
61             {
62 0     0 1   my($self, $sql, $arg) = @_;
63 0           my($table_name) = $sql;
64 0           $table_name =~ s/^\s*create\s+table\s+([a-z_0-9]+).+$/$1/is;
65              
66 0 0         $arg = {} if (! defined $arg);
67 0 0         $$arg{$table_name} = {} if (! defined $$arg{$table_name});
68 0 0         $$arg{$table_name}{no_sequence} = 0 if (! defined $$arg{$table_name}{no_sequence});
69              
70 0 0         if (! $$arg{$table_name}{no_sequence})
71             {
72 0           my($sequence_name) = $self -> generate_primary_sequence_name($table_name);
73              
74 0 0         if ($sequence_name)
75             {
76 0           my($sql) = "create sequence $sequence_name";
77              
78 0           $self -> dbh -> do($sql);
79              
80 0 0         print STDERR __PACKAGE__, ". SQL: $sql. \n" if ($self -> verbose);
81              
82 0 0         if ($self -> dbh -> errstr() )
83             {
84 0           return $self -> dbh -> errstr(); # Failure.
85             }
86              
87 0 0         print STDERR __PACKAGE__, ". Created sequence '$sequence_name'. \n" if ($self -> verbose);
88             }
89             }
90              
91 0           $self -> dbh -> do($sql);
92              
93 0 0         print STDERR __PACKAGE__, ". SQL: $sql. \n" if ($self -> verbose);
94              
95 0 0         if ($self -> dbh -> errstr() )
96             {
97 0           return $self -> dbh -> errstr(); # Failure.
98             }
99              
100 0 0         print STDERR __PACKAGE__, ". Created table '$table_name'. \n" if ($self -> verbose);
101              
102 0           return ''; # Success.
103              
104             } # End of create_table.
105              
106             # --------------------------------------------------
107              
108             sub drop_table
109             {
110 0     0 1   my($self, $table_name, $arg) = @_;
111 0           my($sequence_name) = $self -> generate_primary_sequence_name($table_name);
112              
113             # Turn off RaiseError so we don't error if the sequence and table being deleted do not exist.
114             # We do this by emulating local $$dbh{RaiseError}.
115              
116 0           my($dbh) = $self -> dbh;
117 0           my($raise_error) = $$dbh{RaiseError};
118 0           $$dbh{RaiseError} = 0;
119              
120 0           $self -> dbh($dbh);
121              
122 0 0         $arg = {} if (! defined $arg);
123 0 0         $$arg{$table_name} = {} if (! defined $$arg{$table_name});
124 0 0         $$arg{$table_name}{no_sequence} = 0 if (! defined $$arg{$table_name}{no_sequence});
125              
126 0           my($sql);
127              
128             # For Oracle, drop the sequence before dropping the table.
129              
130 0 0 0       if ( ($self -> db_vendor eq 'ORACLE') && ! $$arg{$table_name}{no_sequence})
131             {
132 0           $sql = "drop sequence $sequence_name";
133              
134 0           $self -> dbh -> do($sql);
135              
136 0 0         print STDERR __PACKAGE__, ". SQL: $sql. \n" if ($self -> verbose);
137 0 0         print STDERR __PACKAGE__, ". Dropped sequence '$sequence_name'. \n" if ($self -> verbose);
138             }
139              
140 0           $sql = "drop table $table_name";
141              
142 0           $self -> dbh -> do($sql);
143              
144 0 0         print STDERR __PACKAGE__, ". SQL: $sql. \n" if ($self -> verbose);
145 0 0         print STDERR __PACKAGE__, ". Dropped table '$table_name'. \n" if ($self -> verbose);
146              
147             # For Postgres, drop the sequence after dropping the table.
148              
149 0 0 0       if ( ($self -> db_vendor eq 'POSTGRESQL') && ! $$arg{$table_name}{no_sequence})
150             {
151 0           $sql = "drop sequence $sequence_name";
152              
153 0           $self -> dbh -> do($sql);
154              
155 0 0         print STDERR __PACKAGE__, ". SQL: $sql. \n" if ($self -> verbose);
156 0 0         print STDERR __PACKAGE__, ". Dropped sequence '$sequence_name'. \n" if ($self -> verbose);
157             }
158              
159             # Undo local $$dbh{RaiseError}.
160              
161 0           $$dbh{RaiseError} = $raise_error;
162              
163 0           $self -> dbh($dbh);
164              
165 0           return '';
166              
167             } # End of drop_table.
168              
169             # --------------------------------------------------
170              
171             sub generate_primary_index_name
172             {
173 0     0 0   my($self, $table_name) = @_;
174 0           my($hashref) = $self -> primary_index_name;
175              
176 0 0         if (! $$hashref{$table_name})
177             {
178 0 0         $$hashref{$table_name} = $self -> db_vendor eq 'POSTGRESQL'
179             ? "${table_name}_pkey"
180             : ''; # MySQL, Oracle, SQLite.
181              
182 0           $self -> primary_index_name($hashref);
183             }
184              
185 0           return $$hashref{$table_name};
186              
187             } # End of generate_primary_index_name.
188              
189             # --------------------------------------------------
190              
191             sub generate_primary_key_sql
192             {
193 0     0 1   my($self, $table_name) = @_;
194 0           my($sequence_name) = $self -> generate_primary_sequence_name($table_name);
195 0 0         my($primary_key) =
    0          
    0          
196             ($self -> db_vendor eq 'MYSQL')
197             ? 'integer primary key auto_increment'
198             : ($self -> db_vendor eq 'SQLITE')
199             ? 'integer primary key autoincrement'
200             : $self -> db_vendor eq 'ORACLE'
201             ? 'integer primary key'
202             : "integer primary key default nextval('$sequence_name')"; # Postgres.
203              
204 0           return $primary_key;
205              
206             } # End of generate_primary_key_sql.
207              
208             # --------------------------------------------------
209              
210             sub generate_primary_sequence_name
211             {
212 0     0 1   my($self, $table_name) = @_;
213 0           my($hashref) = $self -> sequence_name;
214              
215 0 0         if (! $$hashref{$table_name})
216             {
217 0 0         $$hashref{$table_name} = $self -> db_vendor =~ /(?:MYSQL|SQLITE)/
218             ? ''
219             : "${table_name}_id_seq"; # Oracle, Postgres.
220              
221 0           $self -> sequence_name($hashref);
222             }
223              
224 0           return $$hashref{$table_name};
225              
226             } # End of generate_primary_sequence_name.
227              
228             # -----------------------------------------------
229             # Assumption: This code is only called in the case
230             # of Oracle and Postgres, and after importing data
231             # for all tables from a XML file (say).
232             # The mechanism used to import from XML does not
233             # activate the sequences because the primary keys
234             # are included in the data being imported.
235             # So, we have to reset the current values of the
236             # sequences up from their default values of 1 to
237             # the number of records in the corresponding table.
238             # If not, then the next call to nextval() would
239             # return a value of 2, which is already in use.
240              
241             sub reset_all_sequences
242             {
243 0     0 0   my($self, $arg) = @_;
244              
245 0 0         if ($self -> db_vendor ne 'MYSQL')
246             {
247 0           $self -> reset_sequence($_, $arg) for keys %{$self -> sequence_name};
  0            
248             }
249              
250             } # End of reset_all_sequences.
251              
252             # -----------------------------------------------
253              
254             sub reset_sequence
255             {
256 0     0 0   my($self, $table_name, $arg) = @_;
257              
258 0 0         $arg = {} if (! defined $arg);
259 0 0         $$arg{$table_name} = {} if (! defined $$arg{$table_name});
260 0 0         $$arg{$table_name}{no_sequence} = 0 if (! defined $$arg{$table_name}{no_sequence});
261              
262 0 0         if (! $$arg{$table_name}{no_sequence})
263             {
264 0           my($sequence_name) = $self -> generate_primary_sequence_name($table_name);
265 0           my($sth) = $self -> dbh -> prepare("select count(*) from $table_name");
266              
267 0           $sth -> execute();
268              
269 0           my($max) = $sth -> fetch();
270 0   0       $max = $$max[0] || 0;
271 0           my($sql) = "select setval('$sequence_name', $max)";
272              
273 0           $sth -> finish();
274 0           $self -> dbh -> do($sql);
275              
276 0 0         print STDERR __PACKAGE__, ". SQL: $sql. \n" if ($self -> verbose);
277 0 0         print STDERR __PACKAGE__, ". Reset table '$table_name', sequence '$sequence_name' to $max. \n" if ($self -> verbose);
278             }
279              
280             } # End of reset_sequence.
281              
282             # --------------------------------------------------
283              
284             1;
285              
286             =head1 NAME
287              
288             DBIx::Admin::CreateTable - Create and drop tables, primary indexes, and sequences
289              
290             =head1 Synopsis
291              
292             #!/usr/bin/env perl
293              
294             use strict;
295             use warnings;
296              
297             use DBI;
298             use DBIx::Admin::CreateTable;
299              
300             # ----------------
301              
302             my($dbh) = DBI -> connect(...);
303             my($creator) = DBIx::Admin::CreateTable -> new(dbh => $dbh, verbose => 1);
304             my($table_name) = 'test';
305              
306             $creator -> drop_table($table_name);
307              
308             my($primary_key) = $creator -> generate_primary_key_sql($table_name);
309              
310             $creator -> create_table(<
311             create table $table_name
312             (
313             id $primary_key,
314             data varchar(255)
315             )
316             SQL
317              
318             See also xt/author/fk.t in L.
319              
320             =head1 Description
321              
322             C is a pure Perl module.
323              
324             Database vendors supported: MySQL, Oracle, Postgres, SQLite.
325              
326             Assumptions:
327              
328             =over 4
329              
330             =item Every table has a primary key
331              
332             =item The primary key is a unique, non-null, integer
333              
334             =item The primary key is a single column
335              
336             =item The primary key column is called 'id'
337              
338             =item If a primary key has a corresponding auto-created index, the index is called 't_pkey'
339              
340             This is true for Postgres, where declaring a column as a primary key automatically results in the creation
341             of an associated index for that column. The index is named after the table, not after the column.
342              
343             =item If a table 't' (with primary key 'id') has an associated sequence, the sequence is called 't_id_seq'
344              
345             This is true for both Oracle and Postgres, which use sequences to populate primary key columns. The sequences
346             are named after both the table and the column.
347              
348             =back
349              
350             =head1 Constructor and initialization
351              
352             new(...) returns an object of type C.
353              
354             This is the class contructor.
355              
356             Usage: DBIx::Admin::CreateTable -> new().
357              
358             This method takes a set of parameters. Only the dbh parameter is mandatory.
359              
360             For each parameter you wish to use, call new as new(param_1 => value_1, ...).
361              
362             =over 4
363              
364             =item dbh
365              
366             This is a database handle, returned from the DBI connect() call.
367              
368             This parameter is mandatory.
369              
370             There is no default.
371              
372             =item verbose
373              
374             This is 0 or 1, to turn off or on printing of progress statements to STDERR.
375              
376             This parameter is optional.
377              
378             The default is 0.
379              
380             =back
381              
382             =head1 Method: create_table($sql, $arg)
383              
384             Returns '' (empty string) if successful and DBI errstr() if there is an error.
385              
386             $sql is the SQL to create the table.
387              
388             $arg is an optional hash ref of options per table.
389              
390             The keys are table names. The only sub-key at the moment is...
391              
392             =over 4
393              
394             =item no_sequence
395              
396             $arg = {$table_name_1 => {no_sequence => 1}, $table_name_2 => {no_sequence => 1} };
397              
398             can be used to tell create_table not to create a sequence for the given table.
399              
400             You would use this on a CGI::Session-type table called 'sessions', for example,
401             when using Oracle or Postgres. With MySQL there would be no sequence anyway.
402              
403             You would also normally use this on a table called 'log'.
404              
405             The reason for this syntax is so you can use the same hash ref in a call to reset_all_sequences.
406              
407             =back
408              
409             Usage with CGI::Session:
410              
411             my($creator) = DBIx::Admin::CreateTable -> new(dbh => $dbh, verbose => 1);
412             my($table_name) = 'sessions';
413             my($type) = $creator -> db_vendor() eq 'ORACLE' ? 'long' : 'text';
414              
415             $creator -> drop_table($table_name);
416             $creator -> create_table(< {no_sequence => 1} });
417             create table $table_name
418             (
419             id char(32) primary key,
420             a_session $type not null
421             )
422             SQL
423              
424             Typical usage:
425              
426             my($creator) = DBIx::Admin::CreateTable -> new(dbh => $dbh, verbose => 1);
427             my($table_name) = 'test';
428             my($primary_key) = $creator -> generate_primary_key_sql($table_name);
429              
430             $creator -> drop_table($table_name);
431             $creator -> create_table(<
432             create table $table_name
433             (
434             id $primary_key,
435             data varchar(255)
436             )
437             SQL
438              
439             The SQL generated by this call to create_table() is spelled-out in the (SQL) table below.
440              
441             Action:
442              
443             Method: create_table($table_name, $arg).
444             Comment: Creation of tables and sequences.
445             Sequence: See generate_primary_sequence_name($table_name).
446             +----------|---------------------------------------------------+
447             | | Action for $$arg{$table_name} |
448             | Vendor | {no_sequence => 0} | {no_sequence => 1} |
449             +----------|------------------------------|--------------------+
450             | MySQL | Create table | Create table |
451             +----------|------------------------------|--------------------+
452             | Oracle | Create sequence before table | Create table |
453             +----------|------------------------------|--------------------+
454             | Postgres | Create sequence before table | Create table |
455             +----------|------------------------------|--------------------+
456             | SQLite | Create table | Create table |
457             +----------|------------------------------|--------------------+
458              
459             SQL:
460              
461             Method: create_table($table_name, $arg).
462             Comment: SQL generated.
463             Sequence: See generate_primary_sequence_name($table_name).
464             +----------|-------------------------------------------------------------------------------------+
465             | | SQL for $$arg{$table_name} |
466             | Vendor | {no_sequence => 0} | {no_sequence => 1} |
467             +----------|------------------------------------------|------------------------------------------+
468             | MySQL | create table $table_name | create table $table_name |
469             | | (id integer primary key | (id integer auto_increment |
470             | | auto_increment, | primary key, |
471             | | data varchar(255) ) | data varchar(255) ) |
472             +----------|------------------------------------------|------------------------------------------+
473             | Oracle | create sequence ${table_name}_id_seq & | |
474             | | create table $table_name | create table $table_name |
475             | | (id integer primary key, | (id integer primary key, |
476             | | data varchar(255) ) | data varchar(255) ) |
477             +----------|------------------------------------------|------------------------------------------+
478             | Postgres | create sequence ${table_name}_id_seq & | |
479             | | create table $table_name | create table $table_name |
480             | | (id integer primary key | (id integer primary key |
481             | | default nextval("${table_name}_id_seq"), | default nextval("${table_name}_id_seq"), |
482             | | data varchar(255) ) | data varchar(255) ) |
483             +----------|------------------------------------------|------------------------------------------+
484             | SQLite | create table $table_name | create table $table_name |
485             | | (id integer primary key | (id integer autoincrement |
486             | | autoincrement, | primary key, |
487             | | data varchar(255) ) | data varchar(255) ) |
488             +----------|------------------------------------------|------------------------------------------+
489              
490             =head1 Method: db_vendor()
491              
492             Returns an upper-case string identifying the database vendor.
493              
494             Return string:
495              
496             Method: db_vendor(db_vendor).
497             Comment: Value returned.
498             +----------|------------+
499             | Vendor | String |
500             +----------|------------+
501             | MySQL | MYSQL |
502             +----------|------------+
503             | Oracle | ORACLE |
504             +----------|------------+
505             | Postgres | POSTGRESQL |
506             +----------|------------+
507             | SQLite | SQLITE |
508             +----------|------------+
509              
510             =head1 Method: drop_table($table_name, $arg)
511              
512             Returns '' (empty string).
513              
514             $table_name is the name of the table to drop.
515              
516             $arg is an optional hash ref of options, the same as for C.
517              
518             Action:
519              
520             Method: drop_table($table_name, $arg).
521             Comment: Deletion of tables and sequences.
522             Sequence: See generate_primary_sequence_name($table_name).
523             +----------|-------------------------------------------------+
524             | | Action for $$arg{$table_name} |
525             | Vendor | {no_sequence => 0} | {no_sequence => 1} |
526             +----------|----------------------------|--------------------+
527             | MySQL | Drop table | Drop table |
528             +----------|----------------------------|--------------------+
529             | Oracle | Drop sequence before table | Drop table |
530             +----------|----------------------------|--------------------+
531             | Postgres | Drop sequence after table | Drop table |
532             +----------|----------------------------|--------------------+
533             | SQLite | Drop table | Drop table |
534             +----------|----------------------------|--------------------+
535              
536             SQL:
537              
538             Method: drop_table($table_name, $arg).
539             Comment: SQL generated.
540             Sequence: See generate_primary_sequence_name($table_name).
541             +----------|---------------------------------------------------------------+
542             | | SQL for $$arg{$table_name} |
543             | Vendor | {no_sequence => 0} | {no_sequence => 1} |
544             +----------|--------------------------------------|------------------------+
545             | MySQL | drop table $table_name | drop table $table_name |
546             +----------|--------------------------------------|------------------------+
547             | Oracle | drop sequence ${table_name}_id_seq & | |
548             | | drop table $table_name | drop table $table_name |
549             +----------|--------------------------------------|------------------------+
550             | Postgres | drop table $table_name & | drop table $table_name |
551             | | drop sequence ${table_name}_id_seq | |
552             +----------|--------------------------------------|------------------------+
553             | SQLite | drop table $table_name | drop table $table_name |
554             +----------|--------------------------------------|------------------------+
555              
556             Note: drop_table() turns off RaiseError so we do not error if the sequence and table being deleted do not exist.
557             This is new in V 2.00.
558              
559             =head1 Method: generate_primary_index_name($table_name)
560              
561             Returns the name of the index corresponding to the primary key for the given table.
562              
563             The module does not call this method.
564              
565             SQL:
566              
567             Method: generate_primary_index_name($table_name).
568             Comment: Generation of name of the index for the primary key.
569             +----------|--------------------+
570             | Vendor | SQL |
571             +----------|--------------------+
572             | MySQL | |
573             +----------|--------------------+
574             | Oracle | |
575             +----------|--------------------+
576             | Postgres | ${table_name}_pkey |
577             +----------|--------------------+
578             | SQLite | |
579             +----------|--------------------+
580              
581             =head1 Method: generate_primary_key_sql($table_name)
582              
583             Returns partial SQL for declaring the primary key for the given table.
584              
585             See the Synopsis for how to use this method.
586              
587             SQL:
588              
589             Method: generate_primary_key_sql($table_name).
590             Comment: Generation of partial SQL for primary key.
591             Sequence: See generate_primary_sequence_name($table_name).
592             +----------|-----------------------------------------------------+
593             | Vendor | SQL |
594             +----------|-----------------------------------------------------+
595             | MySQL | integer primary key auto_increment |
596             +----------|-----------------------------------------------------+
597             | Oracle | integer primary key |
598             +----------|-----------------------------------------------------+
599             | Postgres | integer primary key default nextval($sequence_name) |
600             +----------|-----------------------------------------------------+
601             | SQLite | integer primary key autoincrement |
602             +----------|-----------------------------------------------------+
603              
604             =head1 Method: generate_primary_sequence_name($table_name)
605              
606             Returns the name of the sequence used to populate the primary key of the given table.
607              
608             SQL:
609              
610             Method: generate_primary_sequence_name($table_name).
611             Comment: Generation of name for sequence.
612             +----------|----------------------+
613             | Vendor | SQL |
614             +----------|----------------------+
615             | MySQL | |
616             +----------|----------------------+
617             | Oracle | ${table_name}_id_seq |
618             +----------|----------------------+
619             | Postgres | ${table_name}_id_seq |
620             +----------|----------------------+
621             | SQLite | |
622             +----------|----------------------+
623              
624             =head1 Method: reset_all_sequences($arg)
625              
626             Returns nothing.
627              
628             Resets the primary key sequence for all tables, except those marked by $arg as not having a sequence.
629              
630             Note: This method only works if called against an object which knows the names of all tables and sequences.
631             This means you must have called at least one of these, for each table:
632              
633             =over
634              
635             =item create_table
636              
637             =item drop_table
638              
639             =item generate_primary_key_sql
640              
641             =item generate_primary_sequence_name
642              
643             =back
644              
645             $arg is an optional hash ref of options, the same as for C.
646              
647             Summary:
648              
649             Method: reset_all_sequences($arg).
650             Comment: Reset all sequences.
651             +----------|-------------------------------------------------------+
652             | Vendor | Action |
653             +----------|-------------------------------------------------------+
654             | MySQL | Do nothing |
655             +----------|-------------------------------------------------------+
656             | Oracle | Call reset_sequence($table_name, $arg) for all tables |
657             +----------|-------------------------------------------------------+
658             | Postgres | Call reset_sequence($table_name, $arg) for all tables |
659             +----------|-------------------------------------------------------+
660             | SQLite | Do nothing |
661             +----------|-------------------------------------------------------+
662              
663             =head1 Method: reset_sequence($table_name, $arg)
664              
665             Returns nothing.
666              
667             Resets the primary key sequence for the given table, except if it is marked by $arg as not having a sequence.
668              
669             $arg is an optional hash ref of options, the same as for C.
670              
671             Summary:
672              
673             Method: reset_sequence($table_name, $arg).
674             Comment: Reset one sequence.
675             Sequence: The value of the sequence is set to the number of records in the table.
676             +----------|-----------------------------------------+
677             | | Action for $$arg{$table_name} |
678             | Vendor | {no_sequence => 0} | {no_sequence => 1} |
679             +----------|--------------------|--------------------+
680             | MySQL | Do nothing | Do nothing |
681             +----------|--------------------|--------------------+
682             | Oracle | Set sequence value | Do nothing |
683             +----------|--------------------|--------------------+
684             | Postgres | Set sequence value | Do nothing |
685             +----------|--------------------|--------------------+
686             | SQLite | Do nothing | Do nothing |
687             +----------|--------------------|--------------------+
688              
689             =head1 FAQ
690              
691             =head2 Which versions of the servers did you test?
692              
693             Versions as at 2014-03-07
694             +----------|------------+
695             | Vendor | V |
696             +----------|------------+
697             | MariaDB | 5.5.36 |
698             +----------|------------+
699             | Oracle | 10.2.0.1.0 | (Not tested for years)
700             +----------|------------+
701             | Postgres | 9.1.12 |
702             +----------|------------+
703             | SQLite | 3.7.17 |
704             +----------|------------+
705              
706             =head2 Do all database servers accept the same 'create table' commands?
707              
708             No. You have been warned.
709              
710             References for 'Create table':
711             L.
712             L.
713             L.
714              
715             Consider these:
716              
717             create table one
718             (
719             id integer primary key autoincrement,
720             data varchar(255)
721             ) $engine
722              
723             create table two
724             (
725             id integer primary key autoincrement,
726             one_id integer not null,
727             data varchar(255),
728             foreign key(one_id) references one(id)
729             ) $engine
730              
731             Putting the 'foreign key' clause at the end makes it a table constraint. Some database servers, e.g. MySQL and Postgres,
732             allow you to attach it to a particular column, as explained next.
733              
734             =over 4
735              
736             =item o MySQL
737              
738             The creates work as given, where $engine eq 'engine = innodb'.
739              
740             Further, you can re-order the clauses in the 2nd create:
741              
742             create table two
743             (
744             id integer primary key autoincrement,
745             one_id integer not null,
746             foreign key(one_id) references one(id),
747             data varchar(255)
748             ) $engine
749              
750             This also works, where $engine eq 'engine = innodb'.
751              
752             However, if you use:
753              
754             create table two
755             (
756             id integer primary key autoincrement,
757             one_id integer not null references one(id),
758             data varchar(255)
759             ) $engine
760              
761             Then the 'references' (foreign key) clause is parsed but discarded, even with 'engine = innodb'.
762              
763             =item o Postgres
764              
765             The creates work as given, where $engine = ''.
766              
767             And you can re-order the clauses, as in the first example for MySQL.
768              
769             =item o SQLite
770              
771             The creates work as given, where $engine = ''.
772              
773             But if you re-order the clauses:
774              
775             create table two
776             (
777             id integer primary key autoincrement,
778             one_id integer not null,
779             foreign key(one_id) references one(id),
780             data varchar(255)
781             ) $engine
782              
783             Then you get a syntax error.
784              
785             However, if you use:
786              
787             create table two
788             (
789             id integer primary key autoincrement,
790             one_id integer not null references one(id),
791             data varchar(255)
792             ) $engine
793              
794             Then the 'references' (foreign key) clause is parsed, and it does create a foreign key relationship.
795              
796             =back
797              
798             Do not forget this when using SQLite:
799              
800             $dbh -> do('pragma foreign_keys = on') if ($dsn =~ /SQLite/i);
801              
802             =head2 Do I include the name of an auto-populated column in an insert statement?
803              
804             Depends on the server. Some databases, e.g. Postgres, do I want the name of the primary key
805             in the insert statement if the server is to generate a value for a column.
806              
807             SQL for insert:
808              
809             Comment: SQL for insertion of rows containing auto-populated values.
810             Sequence: See generate_primary_sequence_name($table_name).
811             +----------|-----------------------------------------------------------------------+
812             | Vendor | SQL |
813             +----------|-----------------------------------------------------------------------+
814             | MySQL | insert into $table_name (data) values (?) |
815             +----------|-----------------------------------------------------------------------+
816             | Oracle | insert into $table_name (id, data) values ($sequence_name.nextval, ?) |
817             +----------|-----------------------------------------------------------------------+
818             | Postgres | insert into $table_name (data) values (?) |
819             +----------|-----------------------------------------------------------------------+
820             | SQLite | insert into $table_name (id, data) values (undef, ?) |
821             +----------|-----------------------------------------------------------------------+
822              
823             =head2 Do I have to use a sequence to populate a primary key?
824              
825             Well, no, actually. See next question.
826              
827             =head2 How to I override the auto-populated value for a primary key column?
828              
829             By including the name and the value in the insert statement.
830              
831             SQL for insert:
832              
833             Comment: SQL for insertion of rows overriding auto-populated values.
834             +----------|--------------------------------------------------+
835             | Vendor | SQL |
836             +----------|--------------------------------------------------+
837             | MySQL | insert into $table_name (id, data) values (?, ?) |
838             +----------|--------------------------------------------------+
839             | Oracle | insert into $table_name (id, data) values (?, ?) |
840             +----------|--------------------------------------------------+
841             | Postgres | insert into $table_name (id, data) values (?, ?) |
842             +----------|--------------------------------------------------+
843             | SQLite | insert into $table_name (id, data) values (?, ?) |
844             +----------|--------------------------------------------------+
845              
846             =head2 Are primary keys always not null and unique?
847              
848             Yes. All servers document primary key as meaning both non null and unique.
849              
850             =head2 See Also
851              
852             L.
853              
854             L.
855              
856             =head1 Version Numbers
857              
858             Version numbers < 1.00 represent development versions. From 1.00 up, they are production versions.
859              
860             =head1 Support
861              
862             Log a bug on RT: L.
863              
864             =head1 Author
865              
866             C was written by Ron Savage Iron@savage.net.auE> in 2006.
867              
868             Home page: http://savage.net.au/index.html
869              
870             =head1 Copyright
871              
872             Australian copyright (c) 2006, Ron Savage.
873             All Programs of mine are 'OSI Certified Open Source Software';
874             you can redistribute them and/or modify them under the terms of
875             the Artistic or the GPL licences, copies of which is available at:
876             http://www.opensource.org/licenses/index.html
877              
878             =cut
879