use warnings
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / SQLServer.pm
1 package SQL::Translator::Producer::SQLServer;
2
3 =head1 NAME
4
5 SQL::Translator::Producer::SQLServer - MS SQLServer producer for SQL::Translator
6
7 =head1 SYNOPSIS
8
9   use SQL::Translator;
10
11   my $t = SQL::Translator->new( parser => '...', producer => 'SQLServer' );
12   $t->translate;
13
14 =head1 DESCRIPTION
15
16 B<WARNING>B This is still fairly early code, basically a hacked version of the
17 Sybase Producer (thanks Sam, Paul and Ken for doing the real work ;-)
18
19 =head1 Extra Attributes
20
21 =over 4
22
23 =item field.list
24
25 List of values for an enum field.
26
27 =back
28
29 =head1 TODO
30
31  * !! Write some tests !!
32  * Reserved words list needs updating to SQLServer.
33  * Triggers, Procedures and Views DO NOT WORK
34
35 =cut
36
37 use strict;
38 use warnings;
39 use vars qw[ $DEBUG $WARN $VERSION ];
40 $VERSION = '1.59';
41 $DEBUG = 1 unless defined $DEBUG;
42
43 use Data::Dumper;
44 use SQL::Translator::Schema::Constants;
45 use SQL::Translator::Utils qw(debug header_comment);
46 use SQL::Translator::ProducerUtils;
47
48 my $util = SQL::Translator::ProducerUtils->new( quote_chars => ['[', ']'] );
49
50 my %translate  = (
51     date      => 'datetime',
52     'time'    => 'datetime',
53     # Sybase types
54     #integer   => 'numeric',
55     #int       => 'numeric',
56     #number    => 'numeric',
57     #money     => 'money',
58     #varchar   => 'varchar',
59     #varchar2  => 'varchar',
60     #timestamp => 'datetime',
61     #text      => 'varchar',
62     #real      => 'double precision',
63     #comment   => 'text',
64     #bit       => 'bit',
65     #tinyint   => 'smallint',
66     #float     => 'double precision',
67     #serial    => 'numeric',
68     #boolean   => 'varchar',
69     #char      => 'char',
70     #long      => 'varchar',
71 );
72
73 # If these datatypes have size appended the sql fails.
74 my @no_size = qw/tinyint smallint int integer bigint text bit image datetime/;
75
76 my $max_id_length    = 128;
77 my %global_names;
78
79 =pod
80
81 =head1 SQLServer Create Table Syntax
82
83 TODO
84
85 =cut
86
87 sub produce {
88     my $translator     = shift;
89     $DEBUG             = $translator->debug;
90     $WARN              = $translator->show_warnings;
91     my $no_comments    = $translator->no_comments;
92     my $add_drop_table = $translator->add_drop_table;
93     my $schema         = $translator->schema;
94
95     %global_names = (); #reset
96
97     my $output;
98     $output .= header_comment."\n" unless ($no_comments);
99
100     # Generate the DROP statements.
101     if ($add_drop_table) {
102         my @tables = sort { $b->order <=> $a->order } $schema->get_tables;
103         $output .= "--\n-- Turn off constraints\n--\n\n" unless $no_comments;
104         foreach my $table (@tables) {
105             my $name = $table->name;
106             my $q_name = unreserve($name);
107             $output .= "IF EXISTS (SELECT name FROM sysobjects WHERE name = '$name' AND type = 'U') ALTER TABLE $q_name NOCHECK CONSTRAINT all;\n"
108         }
109         $output .= "\n";
110         $output .= "--\n-- Drop tables\n--\n\n" unless $no_comments;
111         foreach my $table (@tables) {
112             my $name = $table->name;
113             my $q_name = unreserve($name);
114             $output .= "IF EXISTS (SELECT name FROM sysobjects WHERE name = '$name' AND type = 'U') DROP TABLE $q_name;\n"
115         }
116     }
117
118     # Generate the CREATE sql
119
120     my @foreign_constraints = (); # these need to be added separately, as tables may not exist yet
121
122     for my $table ( $schema->get_tables ) {
123         my $table_name    = $table->name or next;
124         my $table_name_ur = unreserve($table_name) || '';
125
126         my ( @comments, @field_defs, @index_defs, @constraint_defs );
127
128         push @comments, "\n\n--\n-- Table: $table_name_ur\n--"
129         unless $no_comments;
130
131         push @comments, map { "-- $_" } $table->comments;
132
133         #
134         # Fields
135         #
136         my %field_name_scope;
137         for my $field ( $table->get_fields ) {
138             my $field_name    = $field->name;
139             my $field_name_ur = unreserve( $field_name );
140             my $field_def     = qq["$field_name_ur"];
141             $field_def        =~ s/\"//g;
142             if ( $field_def =~ /identity/ ){
143                 $field_def =~ s/identity/pidentity/;
144             }
145
146             #
147             # Datatype
148             #
149             my $data_type      = lc $field->data_type;
150             my $orig_data_type = $data_type;
151             my %extra          = $field->extra;
152             my $list           = $extra{'list'} || [];
153             # \todo deal with embedded quotes
154             my $commalist      = join( ', ', map { qq['$_'] } @$list );
155
156             if ( $data_type eq 'enum' ) {
157                 my $check_name = mk_name( $field_name . '_chk' );
158                 push @constraint_defs,
159                   "CONSTRAINT $check_name CHECK ($field_name IN ($commalist))";
160                 $data_type .= 'character varying';
161             }
162             elsif ( $data_type eq 'set' ) {
163                 $data_type .= 'character varying';
164             }
165             elsif ( grep { $data_type eq $_ } qw/bytea blob clob/ ) {
166                 $data_type = 'varbinary';
167             }
168             else {
169                 if ( defined $translate{ $data_type } ) {
170                     $data_type = $translate{ $data_type };
171                 }
172                 else {
173                     warn "Unknown datatype: $data_type ",
174                         "($table_name.$field_name)\n" if $WARN;
175                 }
176             }
177
178             my $size = $field->size;
179             if ( grep $_ eq $data_type, @no_size) {
180             # SQLServer doesn't seem to like sizes on some datatypes
181                 $size = undef;
182             }
183             elsif ( !$size ) {
184                 if ( $data_type =~ /numeric/ ) {
185                     $size = '9,0';
186                 }
187                 elsif ( $orig_data_type eq 'text' ) {
188                     #interpret text fields as long varchars
189                     $size = '255';
190                 }
191                 elsif (
192                     $data_type eq 'varchar' &&
193                     $orig_data_type eq 'boolean'
194                 ) {
195                     $size = '6';
196                 }
197                 elsif ( $data_type eq 'varchar' ) {
198                     $size = '255';
199                 }
200             }
201
202             $field_def .= " $data_type";
203             $field_def .= "($size)" if $size;
204
205             $field_def .= ' IDENTITY' if $field->is_auto_increment;
206
207             #
208             # Not null constraint
209             #
210             unless ( $field->is_nullable ) {
211                 $field_def .= ' NOT NULL';
212             }
213             else {
214                 $field_def .= ' NULL' if $data_type ne 'bit';
215             }
216
217             #
218             # Default value
219             #
220             SQL::Translator::Producer->_apply_default_value(
221               $field,
222               \$field_def,
223               [
224                 'NULL'       => \'NULL',
225               ],
226             );
227
228             push @field_defs, $field_def;
229         }
230
231         #
232         # Constraint Declarations
233         #
234         my @constraint_decs = ();
235         for my $constraint ( $table->get_constraints ) {
236             my $name    = $constraint->name || '';
237             my $name_ur = unreserve($name);
238             # Make sure we get a unique name
239             my $type    = $constraint->type || NORMAL;
240             my @fields  = map { unreserve( $_ ) }
241                 $constraint->fields;
242             my @rfields = map { unreserve( $_ ) }
243                 $constraint->reference_fields;
244             next unless @fields;
245
246             my $c_def;
247             if ( $type eq FOREIGN_KEY ) {
248                 $name ||= mk_name( $table_name . '_fk' );
249                 my $on_delete = uc ($constraint->on_delete || '');
250                 my $on_update = uc ($constraint->on_update || '');
251
252                 # The default implicit constraint action in MSSQL is RESTRICT
253                 # but you can not specify it explicitly. Go figure :)
254                 for ($on_delete, $on_update) {
255                   undef $_ if $_ eq 'RESTRICT'
256                 }
257
258                 $c_def =
259                     "ALTER TABLE $table_name_ur ADD CONSTRAINT $name_ur FOREIGN KEY".
260                     ' (' . join( ', ', @fields ) . ') REFERENCES '.
261                     unreserve($constraint->reference_table).
262                     ' (' . join( ', ', @rfields ) . ')'
263                 ;
264
265                 if ( $on_delete && $on_delete ne "NO ACTION") {
266                   $c_def .= " ON DELETE $on_delete";
267                 }
268                 if ( $on_update && $on_update ne "NO ACTION") {
269                   $c_def .= " ON UPDATE $on_update";
270                 }
271
272                 $c_def .= ";";
273
274                 push @foreign_constraints, $c_def;
275                 next;
276             }
277
278
279             if ( $type eq PRIMARY_KEY ) {
280                 $name = ($name ? unreserve($name) : mk_name( $table_name . '_pk' ));
281                 $c_def =
282                     "CONSTRAINT $name PRIMARY KEY ".
283                     '(' . join( ', ', @fields ) . ')';
284             }
285             elsif ( $type eq UNIQUE ) {
286                 $name = $name_ur || mk_name( $table_name . '_uc' );
287                 my @nullable = grep { $_->is_nullable } $constraint->fields;
288                 if (!@nullable) {
289                   $c_def =
290                       "CONSTRAINT $name UNIQUE " .
291                       '(' . join( ', ', @fields ) . ')';
292                 } else {
293                    push @index_defs,
294                        "CREATE UNIQUE NONCLUSTERED INDEX $name_ur ON $table_name_ur (" .
295                           join( ', ', @fields ) . ')' .
296                           ' WHERE ' . join( ' AND ', map unreserve($_->name) . ' IS NOT NULL', @nullable ) . ';';
297                    next;
298                 }
299             }
300             push @constraint_defs, $c_def;
301         }
302
303         #
304         # Indices
305         #
306         for my $index ( $table->get_indices ) {
307             my $idx_name = $index->name || mk_name($table_name . '_idx');
308             my $idx_name_ur = unreserve($idx_name);
309             push @index_defs,
310                 "CREATE INDEX $idx_name_ur ON $table_name_ur (".
311                 join( ', ', map unreserve($_), $index->fields ) . ");";
312         }
313
314         my $create_statement = "";
315         $create_statement .= qq[CREATE TABLE $table_name_ur (\n].
316             join( ",\n",
317                 map { "  $_" } @field_defs, @constraint_defs
318             ).
319             "\n);"
320         ;
321
322         $output .= join( "\n\n",
323             @comments,
324             $create_statement,
325             @index_defs,
326         );
327     }
328
329 # Add FK constraints
330     $output .= join ("\n", '', @foreign_constraints) if @foreign_constraints;
331
332 # create view/procedure are NOT prepended to the input $sql, needs
333 # to be filled in with the proper syntax
334
335 =pod
336
337     # Text of view is already a 'create view' statement so no need to
338     # be fancy
339     foreach ( $schema->get_views ) {
340         my $name = $_->name();
341         $output .= "\n\n";
342         $output .= "--\n-- View: $name\n--\n\n" unless $no_comments;
343         my $text = $_->sql();
344         $text =~ s/\r//g;
345         $output .= "$text\nGO\n";
346     }
347
348     # Text of procedure already has the 'create procedure' stuff
349     # so there is no need to do anything fancy. However, we should
350     # think about doing fancy stuff with granting permissions and
351     # so on.
352     foreach ( $schema->get_procedures ) {
353         my $name = $_->name();
354         $output .= "\n\n";
355         $output .= "--\n-- Procedure: $name\n--\n\n" unless $no_comments;
356         my $text = $_->sql();
357       $text =~ s/\r//g;
358         $output .= "$text\nGO\n";
359     }
360 =cut
361
362     return $output;
363 }
364
365 sub mk_name {
366     my ($name, $scope, $critical) = @_;
367
368     $scope ||= \%global_names;
369     if ( my $prev = $scope->{ $name } ) {
370         my $name_orig = $name;
371         $name        .= sprintf( "%02d", ++$prev );
372         substr($name, $max_id_length - 3) = "00"
373             if length( $name ) > $max_id_length;
374
375         warn "The name '$name_orig' has been changed to ",
376              "'$name' to make it unique.\n" if $WARN;
377
378         $scope->{ $name_orig }++;
379     }
380     $name = substr( $name, 0, $max_id_length )
381                         if ((length( $name ) > $max_id_length) && $critical);
382     $scope->{ $name }++;
383     return unreserve($name);
384 }
385
386 sub unreserve { $util->quote($_[0]) }
387
388 1;
389
390 =pod
391
392 =head1 SEE ALSO
393
394 SQL::Translator.
395
396 =head1 AUTHORS
397
398 Mark Addison E<lt>grommit@users.sourceforge.netE<gt> - Bulk of code from
399 Sybase producer, I just tweaked it for SQLServer. Thanks.
400
401 =cut