1 package SQL::Translator::Producer::SQLServer;
3 # -------------------------------------------------------------------
4 # Copyright (C) 2002-2009 SQLFairy Authors
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.
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.
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
19 # -------------------------------------------------------------------
23 SQL::Translator::Producer::SQLServer - MS SQLServer producer for SQL::Translator
29 my $t = SQL::Translator->new( parser => '...', producer => 'SQLServer' );
34 B<WARNING>B This is still fairly early code, basically a hacked version of the
35 Sybase Producer (thanks Sam, Paul and Ken for doing the real work ;-)
37 =head1 Extra Attributes
43 List of values for an enum field.
49 * !! Write some tests !!
50 * Reserved words list needs updating to SQLServer.
51 * Triggers, Procedures and Views DO NOT WORK
56 use vars qw[ $DEBUG $WARN $VERSION ];
58 $DEBUG = 1 unless defined $DEBUG;
61 use SQL::Translator::Schema::Constants;
62 use SQL::Translator::Utils qw(debug header_comment);
63 use SQL::Translator::ProducerUtils;
65 my $util = SQL::Translator::ProducerUtils->new( quote_chars => ['[', ']'] );
74 tinyblob => 'varbinary',
75 mediumblob => 'varbinary',
76 longblob => 'varbinary'
79 # If these datatypes have size appended the sql fails.
80 my @no_size = qw/tinyint smallint int integer bigint text bit image datetime/;
82 my $max_id_length = 128;
87 =head1 SQLServer Create Table Syntax
93 # -------------------------------------------------------------------
95 my $translator = shift;
96 $DEBUG = $translator->debug;
97 $WARN = $translator->show_warnings;
98 my $no_comments = $translator->no_comments;
99 my $add_drop_table = $translator->add_drop_table;
100 my $schema = $translator->schema;
102 add_drop_table => $add_drop_table,
103 show_warnings => $WARN,
104 no_comments => $no_comments,
107 %global_names = (); #reset
110 $output .= header_comment."\n" unless ($no_comments);
112 # Generate the DROP statements.
113 if ($add_drop_table) {
114 my @tables = sort { $b->order <=> $a->order } $schema->get_tables;
115 $output .= "--\n-- Turn off constraints\n--\n\n" unless $no_comments;
116 foreach my $table (@tables) {
117 my $name = $table->name;
118 my $q_name = $util->quote( $name );
119 $output .= "IF EXISTS (SELECT name FROM sysobjects WHERE name = '$name' AND type = 'U') ALTER TABLE $q_name NOCHECK CONSTRAINT all;\n"
122 $output .= "--\n-- Drop tables\n--\n\n" unless $no_comments;
123 foreach my $table (@tables) {
124 my $name = $table->name;
125 my $q_name = $util->quote( $name );
126 $output .= "IF EXISTS (SELECT name FROM sysobjects WHERE name = '$name' AND type = 'U') DROP TABLE $q_name;\n"
130 # Generate the CREATE sql
132 my @foreign_constraints = (); # these need to be added separately, as tables may not exist yet
134 for my $table ( $schema->get_tables ) {
135 my $table_name = $table->name or next;
136 my $table_name_q = $util->quote( $table_name );
138 my ( @comments, @field_defs, @index_defs, @constraint_defs );
140 push @comments, "\n\n--\n-- Table: $table_name_q\n--"
143 push @comments, map { "-- $_" } $table->comments;
148 for my $field ( $table->get_fields ) {
149 my $field_clause= build_field_clause($field, $options);
150 if (lc($field->data_type) eq 'enum') {
151 push @constraint_defs, build_enum_constraint($field, $options);
153 push @field_defs, $field_clause;
157 # Constraint Declarations
159 my @constraint_defs = ();
160 for my $constraint ( $table->get_constraints ) {
161 next unless $constraint->fields;
162 my ($stmt, $createClause)= build_constraint_stmt($constraint, $options);
163 # use a clause, if the constraint can be written that way
165 push @constraint_defs, $createClause;
167 # created a foreign key statement, which we save til the end
168 elsif ( $constraint->type eq FOREIGN_KEY ) {
169 push @foreign_constraints, $stmt;
171 # created an index statement, instead of a clause, which we append to "create table"
172 else { #if ( $constraint->type eq UNIQUE ) {
173 push @index_defs, $stmt;
180 for my $index ( $table->get_indices ) {
181 my $idx_name = $index->name || unique_name($table_name . '_idx');
182 my $idx_name_q = $util->quote($idx_name);
184 "CREATE INDEX $idx_name_q ON $table_name_q (".
185 join( ', ', map { $util->quote($_) } $index->fields ) . ");";
188 my $create_statement = "";
189 $create_statement .= "CREATE TABLE $table_name_q (\n".
191 map { " $_" } @field_defs, @constraint_defs
196 $output .= join( "\n\n",
204 $output .= join ("\n", '', @foreign_constraints) if @foreign_constraints;
206 # create view/procedure are NOT prepended to the input $sql, needs
207 # to be filled in with the proper syntax
211 # Text of view is already a 'create view' statement so no need to
213 foreach ( $schema->get_views ) {
214 my $name = $_->name();
216 $output .= "--\n-- View: $name\n--\n\n" unless $no_comments;
217 my $text = $_->sql();
219 $output .= "$text\nGO\n";
222 # Text of procedure already has the 'create procedure' stuff
223 # so there is no need to do anything fancy. However, we should
224 # think about doing fancy stuff with granting permissions and
226 foreach ( $schema->get_procedures ) {
227 my $name = $_->name();
229 $output .= "--\n-- Procedure: $name\n--\n\n" unless $no_comments;
230 my $text = $_->sql();
232 $output .= "$text\nGO\n";
240 my ($from_field, $to_field, $options) = @_;
242 my $field_clause= build_field_clause($to_field, $options);
243 my $table_name_q= $util->quote($to_field->table->name);
246 if (lc($from_field->data_type) eq 'enum') {
247 push @sql, build_drop_enum_constraint($from_field, $options).';';
250 push @sql, "ALTER TABLE $table_name_q ALTER COLUMN $field_clause;";
252 if ($from_field->name ne $to_field->name) {
253 push @sql, rename_field(@_);
256 if (lc($to_field->data_type) eq 'enum') {
257 push @sql, build_add_enum_constraint($to_field, $options).';';
260 return join("\n", @sql);
263 sub build_rename_field {
264 my ($from_field, $to_field, $options) = @_;
266 return sprintf "EXEC sp_rename \@objname = '%s', \@newname = '%s', \@objtype = 'COLUMN';",
272 my ($new_field, $options) = @_;
274 my $field_clause= build_field_clause(@_);
275 my $table_name_q= $util->quote($new_field->table->name);
277 my @sql= "ALTER TABLE $table_name_q ADD COLUMN $field_clause;";
278 if (lc($new_field->data_type) eq 'enum') {
279 push @sql, build_add_enum_constraint($new_field, $options).';';
282 return join("\n", @sql);
286 my ($old_field, $options) = @_;
288 my $table_name_q= $util->quote($old_field->table->name);
289 my $field_name_q= $util->quote($old_field->name);
292 if (lc($old_field->data_type) eq 'enum') {
293 push @sql, build_drop_enum_constraint($old_field, $options).';';
296 push @sql, "ALTER TABLE $table_name_q DROP COLUMN $field_name_q;";
298 return join("\n", @sql);
301 sub alter_create_constraint {
302 my ($constraint, $options) = @_;
303 my ($stmt, $clause)= build_constraint_stmt(@_);
307 sub alter_drop_constraint {
308 my ($constraint, $options) = @_;
309 my $table_name_q= $util->quote($constraint->table->name);
310 my $ct_name_q= $util->quote($constraint->name);
311 return "ALTER TABLE $table_name_q DROP CONSTRAINT $ct_name_q;";
314 sub alter_create_index {
315 my ($index, $options) = @_;
316 my ($stmt, $clause)= build_index_stmt(@_);
320 sub alter_drop_index {
321 my ($index, $options) = @_;
322 my $table_name_q= $util->quote($index->table->name);
323 my $index_name_q= $util->quote($index->name);
324 return "ALTER TABLE $table_name_q DROP $index_name_q";
327 sub build_field_clause {
328 my ($field, $options)= @_;
330 my $field_name = $field->name;
331 my $field_name_q = $util->quote($field_name);
332 my $field_def = $field_name_q;
337 my $data_type = lc $field->data_type;
338 my $orig_data_type = $data_type;
339 my %extra = $field->extra;
340 my $list = $extra{'list'} || [];
341 # \todo deal with embedded quotes
342 my $commalist = join( ', ', map { qq['$_'] } @$list );
343 my $size = $field->size;
345 if ( $data_type eq 'set' ) {
346 # TODO: do we need more logic here?
347 $data_type = 'varchar';
349 elsif ( defined $translate{ $data_type } ) {
350 $data_type = $translate{ $data_type };
353 warn "Unknown datatype: $data_type ",
354 "(".$field->table->name.".$field_name)\n" if $WARN;
357 if ( grep $_ eq $data_type, @no_size) {
358 # SQLServer doesn't seem to like sizes on some datatypes
361 elsif ( $data_type eq 'varbinary' ) {
362 $size ||= 255 if $orig_data_type eq 'tinyblob';
363 # SQL Server has a max specifyable size of 8000, but if you say 'max', you get 2^31. Go figure.
364 # Note that 'max' was introduced in SQL Server 2005. Before that, you need a type of 'image',
365 # which is now deprecated.
366 # TODO: add version support and return 'image' for old versions
367 $size= 'max' if $size > 8000 || !$size;
370 if ( $data_type =~ /numeric/ ) {
373 elsif ( $orig_data_type eq 'text' ) {
374 #interpret text fields as long varchars
378 $data_type eq 'varchar' &&
379 $orig_data_type eq 'boolean'
383 elsif ( $data_type eq 'varchar' ) {
388 $field_def .= " $data_type";
389 $field_def .= "($size)" if $size;
391 $field_def .= ' IDENTITY' if $field->is_auto_increment;
394 # Not null constraint
396 unless ( $field->is_nullable ) {
397 $field_def .= ' NOT NULL';
400 $field_def .= ' NULL' if $data_type ne 'bit';
406 SQL::Translator::Producer->_apply_default_value(
417 sub build_enum_constraint {
418 my ($field, $options)= @_;
419 my %extra = $field->extra;
420 my $list = $extra{'list'} || [];
421 # \todo deal with embedded quotes
422 my $commalist = join( ', ', map { qq['$_'] } @$list );
423 my $field_name_q = $util->quote($field->name);
424 my $check_name_q = $util->quote( unique_name( $field->table->name . '_' . $field->name . '_chk' ) );
425 return "CONSTRAINT $check_name_q CHECK ($field_name_q IN ($commalist))";
428 sub build_add_enum_constraint {
429 my ($field, $options)= @_;
430 my $table_name_q = $util->quote($field->table->name);
431 return "ALTER TABLE $table_name_q ADD ".build_enum_constraint(@_);
434 sub build_drop_enum_constraint {
435 my ($field, $options)= @_;
436 my $table_name_q = $util->quote($field->table->name);
437 my $check_name_q = $util->quote( unique_name( $field->table->name . '_' . $field->name . '_chk' ) );
438 return "ALTER TABLE $table_name_q DROP $check_name_q";
441 # build_constraint_stmt($constraint, $options)
442 # Returns ($stmt, $clause)
444 # Multiple return values are necessary because some things that you would
445 # like to be clauses in CREATE TABLE become separate statements.
446 # $stmt will always be returned, but $clause might be undef
448 sub build_constraint_stmt {
449 my ($constraint, $options)= @_;
450 my $table_name_q = $util->quote($constraint->table->name);
451 my $field_list = join(', ', map { $util->quote($_) } $constraint->fields );
452 my $type = $constraint->type || NORMAL;
454 if ( $type eq FOREIGN_KEY ) {
455 my $ct_name= $constraint->name || unique_name( $constraint->table->name . '_fk' );
456 my $ct_name_q= $util->quote($ct_name);
457 my $ref_tbl_q= $util->quote($constraint->reference_table);
458 my $rfield_list= join( ', ', map { $util->quote($_) } $constraint->reference_fields );
461 "ALTER TABLE $table_name_q ADD CONSTRAINT $ct_name_q ".
462 "FOREIGN KEY ($field_list) REFERENCES $ref_tbl_q ($rfield_list)";
464 # The default implicit constraint action in MSSQL is RESTRICT
465 # but you can not specify it explicitly. Go figure :)
466 my $on_delete = uc ($constraint->on_delete || '');
467 my $on_update = uc ($constraint->on_update || '');
468 if ( $on_delete && $on_delete ne "NO ACTION" && $on_delete ne "RESTRICT") {
469 $c_def .= " ON DELETE $on_delete";
471 if ( $on_update && $on_update ne "NO ACTION" && $on_delete ne "RESTRICT") {
472 $c_def .= " ON UPDATE $on_update";
475 return $c_def, undef;
477 elsif ( $type eq PRIMARY_KEY ) {
478 my $ct_name= $constraint->name || unique_name( $constraint->table->name . '_pk' );
479 my $ct_name_q= $util->quote($ct_name);
481 my $clause= "CONSTRAINT $ct_name_q PRIMARY KEY ($field_list)";
482 my $stmt= "ALTER TABLE $table_name_q ADD $clause";
483 return $stmt, $clause;
485 elsif ( $type eq UNIQUE ) {
486 my $ct_name= $constraint->name || unique_name( $constraint->table->name . '_uc' );
487 my $ct_name_q= $util->quote($ct_name);
489 my @nullable = grep { $_->is_nullable } $constraint->fields;
491 my $clause= "CONSTRAINT $ct_name_q UNIQUE ($field_list)";
492 my $stmt= "ALTER TABLE $table_name_q ADD $clause";
493 return $stmt, $clause;
496 my $where_clause= join(' AND ', map { $util->quote($_->name) . ' IS NOT NULL' } @nullable );
497 my $stmt= "CREATE UNIQUE NONCLUSTERED INDEX $ct_name_q" .
498 " ON $table_name_q ($field_list)" .
499 " WHERE $where_clause";
504 die "Unhandled constraint type $type";
507 sub build_index_stmt {
508 my ($index, $options)= @_;
509 my $table_name_q = $util->quote($index->table->name);
510 my $idx_name_q = $util->quote($index->name);
511 my $field_list = join(', ', map { $util->quote($_) } $index->fields );
513 my $stmt= "CREATE UNIQUE NONCLUSTERED INDEX $idx_name_q" .
514 " ON $table_name_q ($field_list)";
518 # -------------------------------------------------------------------
520 my ($name, $scope, $critical) = @_;
522 $scope ||= \%global_names;
523 if ( my $prev = $scope->{ $name } ) {
524 my $name_orig = $name;
525 $name .= sprintf( "%02d", ++$prev );
526 substr($name, $max_id_length - 3) = "00"
527 if length( $name ) > $max_id_length;
529 warn "The name '$name_orig' has been changed to '$name' to make it".
530 "unique.\nThis can wreak havoc if you try generating upgrade or".
531 "downgrade scripts.\n" if $WARN;
533 $scope->{ $name_orig }++;
535 $name = substr( $name, 0, $max_id_length )
536 if ((length( $name ) > $max_id_length) && $critical);
543 # -------------------------------------------------------------------
553 Mark Addison E<lt>grommit@users.sourceforge.netE<gt> - Bulk of code from
554 Sybase producer, I just tweaked it for SQLServer. Thanks.