use future stuff for SQL Server field generation
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / SQLServer.pm
CommitLineData
7a0ceaa1 1package SQL::Translator::Producer::SQLServer;
2
7a0ceaa1 3=head1 NAME
4
5SQL::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
16B<WARNING>B This is still fairly early code, basically a hacked version of the
17Sybase 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
25List 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.
e2fb9ad3 33 * Triggers, Procedures and Views DO NOT WORK
7a0ceaa1 34
35=cut
36
37use strict;
f27f9229 38use warnings;
0c04c5a2 39our ( $DEBUG, $WARN );
40our $VERSION = '1.59';
7a0ceaa1 41$DEBUG = 1 unless defined $DEBUG;
42
43use Data::Dumper;
44use SQL::Translator::Schema::Constants;
45use SQL::Translator::Utils qw(debug header_comment);
fd9f0e09 46use SQL::Translator::Generator::Utils;
c661b77d 47use SQL::Translator::Generator::DDL::SQLServer;
0a6e5a56 48
fd9f0e09 49my $util = SQL::Translator::Generator::Utils->new( quote_chars => ['[', ']'] );
c661b77d 50my $future = SQL::Translator::Generator::DDL::SQLServer->new();
7a0ceaa1 51
52my %translate = (
53 date => 'datetime',
54 'time' => 'datetime',
55 # Sybase types
56 #integer => 'numeric',
57 #int => 'numeric',
58 #number => 'numeric',
59 #money => 'money',
60 #varchar => 'varchar',
61 #varchar2 => 'varchar',
62 #timestamp => 'datetime',
63 #text => 'varchar',
64 #real => 'double precision',
65 #comment => 'text',
66 #bit => 'bit',
67 #tinyint => 'smallint',
68 #float => 'double precision',
028386aa 69 #serial => 'numeric',
7a0ceaa1 70 #boolean => 'varchar',
71 #char => 'char',
72 #long => 'varchar',
73);
74
7a0ceaa1 75# If these datatypes have size appended the sql fails.
3e0bcbfd 76my @no_size = qw/tinyint smallint int integer bigint text bit image datetime/;
7a0ceaa1 77
3e0bcbfd 78my $max_id_length = 128;
7a0ceaa1 79my %global_names;
7a0ceaa1 80
81=pod
82
83=head1 SQLServer Create Table Syntax
84
85TODO
86
87=cut
88
7a0ceaa1 89sub produce {
90 my $translator = shift;
91 $DEBUG = $translator->debug;
92 $WARN = $translator->show_warnings;
93 my $no_comments = $translator->no_comments;
94 my $add_drop_table = $translator->add_drop_table;
95 my $schema = $translator->schema;
96
e2fb9ad3 97 %global_names = (); #reset
e2fb9ad3 98
7a0ceaa1 99 my $output;
100 $output .= header_comment."\n" unless ($no_comments);
101
d02c3cd2 102 # Generate the DROP statements.
7a0ceaa1 103 if ($add_drop_table) {
d02c3cd2 104 my @tables = sort { $b->order <=> $a->order } $schema->get_tables;
105 $output .= "--\n-- Turn off constraints\n--\n\n" unless $no_comments;
106 foreach my $table (@tables) {
107 my $name = $table->name;
108 my $q_name = unreserve($name);
109 $output .= "IF EXISTS (SELECT name FROM sysobjects WHERE name = '$name' AND type = 'U') ALTER TABLE $q_name NOCHECK CONSTRAINT all;\n"
110 }
111 $output .= "\n";
7a0ceaa1 112 $output .= "--\n-- Drop tables\n--\n\n" unless $no_comments;
d02c3cd2 113 foreach my $table (@tables) {
0a6e5a56 114 my $name = $table->name;
115 my $q_name = unreserve($name);
d02c3cd2 116 $output .= "IF EXISTS (SELECT name FROM sysobjects WHERE name = '$name' AND type = 'U') DROP TABLE $q_name;\n"
7a0ceaa1 117 }
118 }
119
120 # Generate the CREATE sql
f9a5ee79 121
122 my @foreign_constraints = (); # these need to be added separately, as tables may not exist yet
123
7a0ceaa1 124 for my $table ( $schema->get_tables ) {
125 my $table_name = $table->name or next;
7a0ceaa1 126 my $table_name_ur = unreserve($table_name) || '';
127
128 my ( @comments, @field_defs, @index_defs, @constraint_defs );
129
130 push @comments, "\n\n--\n-- Table: $table_name_ur\n--"
131 unless $no_comments;
132
133 push @comments, map { "-- $_" } $table->comments;
134
135 #
136 # Fields
137 #
138 my %field_name_scope;
139 for my $field ( $table->get_fields ) {
e2fb9ad3 140 my $field_name = $field->name;
7a0ceaa1 141
142 #
143 # Datatype
144 #
145 my $data_type = lc $field->data_type;
7a0ceaa1 146 my %extra = $field->extra;
147 my $list = $extra{'list'} || [];
148 # \todo deal with embedded quotes
149 my $commalist = join( ', ', map { qq['$_'] } @$list );
7a0ceaa1 150
151 if ( $data_type eq 'enum' ) {
e2fb9ad3 152 my $check_name = mk_name( $field_name . '_chk' );
7a0ceaa1 153 push @constraint_defs,
e2fb9ad3 154 "CONSTRAINT $check_name CHECK ($field_name IN ($commalist))";
7a0ceaa1 155 $data_type .= 'character varying';
156 }
7a0ceaa1 157
c661b77d 158 push @field_defs, $future->field($field);
7a0ceaa1 159 }
160
161 #
162 # Constraint Declarations
163 #
164 my @constraint_decs = ();
7a0ceaa1 165 for my $constraint ( $table->get_constraints ) {
166 my $name = $constraint->name || '';
0a6e5a56 167 my $name_ur = unreserve($name);
7a0ceaa1 168 # Make sure we get a unique name
7a0ceaa1 169 my $type = $constraint->type || NORMAL;
0a6e5a56 170 my @fields = map { unreserve( $_ ) }
7a0ceaa1 171 $constraint->fields;
0a6e5a56 172 my @rfields = map { unreserve( $_ ) }
7a0ceaa1 173 $constraint->reference_fields;
174 next unless @fields;
175
5bac76bc 176 my $c_def;
f9a5ee79 177 if ( $type eq FOREIGN_KEY ) {
e2fb9ad3 178 $name ||= mk_name( $table_name . '_fk' );
5bac76bc 179 my $on_delete = uc ($constraint->on_delete || '');
180 my $on_update = uc ($constraint->on_update || '');
181
182 # The default implicit constraint action in MSSQL is RESTRICT
183 # but you can not specify it explicitly. Go figure :)
184 for ($on_delete, $on_update) {
185 undef $_ if $_ eq 'RESTRICT'
186 }
187
028386aa 188 $c_def =
0a6e5a56 189 "ALTER TABLE $table_name_ur ADD CONSTRAINT $name_ur FOREIGN KEY".
7a0ceaa1 190 ' (' . join( ', ', @fields ) . ') REFERENCES '.
0a6e5a56 191 unreserve($constraint->reference_table).
f9a5ee79 192 ' (' . join( ', ', @rfields ) . ')'
193 ;
194
5bac76bc 195 if ( $on_delete && $on_delete ne "NO ACTION") {
196 $c_def .= " ON DELETE $on_delete";
197 }
198 if ( $on_update && $on_update ne "NO ACTION") {
199 $c_def .= " ON UPDATE $on_update";
200 }
f9a5ee79 201
202 $c_def .= ";";
203
204 push @foreign_constraints, $c_def;
205 next;
206 }
207
208
209 if ( $type eq PRIMARY_KEY ) {
028386aa 210 $name = ($name ? unreserve($name) : mk_name( $table_name . '_pk' ));
211 $c_def =
f9a5ee79 212 "CONSTRAINT $name PRIMARY KEY ".
213 '(' . join( ', ', @fields ) . ')';
7a0ceaa1 214 }
215 elsif ( $type eq UNIQUE ) {
0a6e5a56 216 $name = $name_ur || mk_name( $table_name . '_uc' );
66444b41 217 my @nullable = grep { $_->is_nullable } $constraint->fields;
218 if (!@nullable) {
219 $c_def =
220 "CONSTRAINT $name UNIQUE " .
221 '(' . join( ', ', @fields ) . ')';
222 } else {
223 push @index_defs,
224 "CREATE UNIQUE NONCLUSTERED INDEX $name_ur ON $table_name_ur (" .
225 join( ', ', @fields ) . ')' .
226 ' WHERE ' . join( ' AND ', map unreserve($_->name) . ' IS NOT NULL', @nullable ) . ';';
227 next;
228 }
7a0ceaa1 229 }
04a180d6 230 push @constraint_defs, $c_def;
7a0ceaa1 231 }
232
233 #
234 # Indices
235 #
236 for my $index ( $table->get_indices ) {
e2fb9ad3 237 my $idx_name = $index->name || mk_name($table_name . '_idx');
0a6e5a56 238 my $idx_name_ur = unreserve($idx_name);
7a0ceaa1 239 push @index_defs,
0a6e5a56 240 "CREATE INDEX $idx_name_ur ON $table_name_ur (".
241 join( ', ', map unreserve($_), $index->fields ) . ");";
7a0ceaa1 242 }
243
244 my $create_statement = "";
245 $create_statement .= qq[CREATE TABLE $table_name_ur (\n].
028386aa 246 join( ",\n",
7a0ceaa1 247 map { " $_" } @field_defs, @constraint_defs
248 ).
249 "\n);"
250 ;
251
252 $output .= join( "\n\n",
253 @comments,
254 $create_statement,
255 @index_defs,
7a0ceaa1 256 );
257 }
258
f9a5ee79 259# Add FK constraints
260 $output .= join ("\n", '', @foreign_constraints) if @foreign_constraints;
261
e2fb9ad3 262# create view/procedure are NOT prepended to the input $sql, needs
263# to be filled in with the proper syntax
264
6fac033a 265=pod
e2fb9ad3 266
7a0ceaa1 267 # Text of view is already a 'create view' statement so no need to
268 # be fancy
269 foreach ( $schema->get_views ) {
270 my $name = $_->name();
271 $output .= "\n\n";
5c5997ef 272 $output .= "--\n-- View: $name\n--\n\n" unless $no_comments;
3e0bcbfd 273 my $text = $_->sql();
e2fb9ad3 274 $text =~ s/\r//g;
5bb0a4ee 275 $output .= "$text\nGO\n";
7a0ceaa1 276 }
277
278 # Text of procedure already has the 'create procedure' stuff
279 # so there is no need to do anything fancy. However, we should
280 # think about doing fancy stuff with granting permissions and
281 # so on.
282 foreach ( $schema->get_procedures ) {
283 my $name = $_->name();
284 $output .= "\n\n";
5c5997ef 285 $output .= "--\n-- Procedure: $name\n--\n\n" unless $no_comments;
3e0bcbfd 286 my $text = $_->sql();
028386aa 287 $text =~ s/\r//g;
5bb0a4ee 288 $output .= "$text\nGO\n";
7a0ceaa1 289 }
e2fb9ad3 290=cut
7a0ceaa1 291
292 return $output;
293}
294
7a0ceaa1 295sub mk_name {
e2fb9ad3 296 my ($name, $scope, $critical) = @_;
7a0ceaa1 297
298 $scope ||= \%global_names;
299 if ( my $prev = $scope->{ $name } ) {
300 my $name_orig = $name;
301 $name .= sprintf( "%02d", ++$prev );
028386aa 302 substr($name, $max_id_length - 3) = "00"
7a0ceaa1 303 if length( $name ) > $max_id_length;
304
305 warn "The name '$name_orig' has been changed to ",
306 "'$name' to make it unique.\n" if $WARN;
307
308 $scope->{ $name_orig }++;
309 }
028386aa 310 $name = substr( $name, 0, $max_id_length )
7a0ceaa1 311 if ((length( $name ) > $max_id_length) && $critical);
312 $scope->{ $name }++;
0a6e5a56 313 return unreserve($name);
7a0ceaa1 314}
315
f3fccb75 316sub unreserve { $util->quote($_[0]) }
7a0ceaa1 317
3181;
319
7a0ceaa1 320=pod
321
322=head1 SEE ALSO
323
324SQL::Translator.
325
326=head1 AUTHORS
327
328Mark Addison E<lt>grommit@users.sourceforge.netE<gt> - Bulk of code from
329Sybase producer, I just tweaked it for SQLServer. Thanks.
330
331=cut