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