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