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::Shim;
65 my $shim = SQL::Translator::Shim->new( quote_chars => ['[', ']'] );
71 #integer => 'numeric',
75 #varchar => 'varchar',
76 #varchar2 => 'varchar',
77 #timestamp => 'datetime',
79 #real => 'double precision',
82 #tinyint => 'smallint',
83 #float => 'double precision',
85 #boolean => 'varchar',
90 # If these datatypes have size appended the sql fails.
91 my @no_size = qw/tinyint smallint int integer bigint text bit image datetime/;
93 my $max_id_length = 128;
98 =head1 SQLServer Create Table Syntax
104 # -------------------------------------------------------------------
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;
113 %global_names = (); #reset
116 $output .= header_comment."\n" unless ($no_comments);
118 # Generate the DROP statements.
119 if ($add_drop_table) {
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"
128 $output .= "--\n-- Drop tables\n--\n\n" unless $no_comments;
129 foreach my $table (@tables) {
130 my $name = $table->name;
131 my $q_name = unreserve($name);
132 $output .= "IF EXISTS (SELECT name FROM sysobjects WHERE name = '$name' AND type = 'U') DROP TABLE $q_name;\n"
136 # Generate the CREATE sql
138 my @foreign_constraints = (); # these need to be added separately, as tables may not exist yet
140 for my $table ( $schema->get_tables ) {
141 my $table_name = $table->name or next;
142 my $table_name_ur = unreserve($table_name) || '';
144 my ( @comments, @field_defs, @index_defs, @constraint_defs );
146 push @comments, "\n\n--\n-- Table: $table_name_ur\n--"
149 push @comments, map { "-- $_" } $table->comments;
154 my %field_name_scope;
155 for my $field ( $table->get_fields ) {
156 my $field_name = $field->name;
157 my $field_name_ur = unreserve( $field_name );
158 my $field_def = qq["$field_name_ur"];
159 $field_def =~ s/\"//g;
160 if ( $field_def =~ /identity/ ){
161 $field_def =~ s/identity/pidentity/;
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 );
174 if ( $data_type eq 'enum' ) {
175 my $check_name = mk_name( $field_name . '_chk' );
176 push @constraint_defs,
177 "CONSTRAINT $check_name CHECK ($field_name IN ($commalist))";
178 $data_type .= 'character varying';
180 elsif ( $data_type eq 'set' ) {
181 $data_type .= 'character varying';
183 elsif ( grep { $data_type eq $_ } qw/bytea blob clob/ ) {
184 $data_type = 'varbinary';
187 if ( defined $translate{ $data_type } ) {
188 $data_type = $translate{ $data_type };
191 warn "Unknown datatype: $data_type ",
192 "($table_name.$field_name)\n" if $WARN;
196 my $size = $field->size;
197 if ( grep $_ eq $data_type, @no_size) {
198 # SQLServer doesn't seem to like sizes on some datatypes
202 if ( $data_type =~ /numeric/ ) {
205 elsif ( $orig_data_type eq 'text' ) {
206 #interpret text fields as long varchars
210 $data_type eq 'varchar' &&
211 $orig_data_type eq 'boolean'
215 elsif ( $data_type eq 'varchar' ) {
220 $field_def .= " $data_type";
221 $field_def .= "($size)" if $size;
223 $field_def .= ' IDENTITY' if $field->is_auto_increment;
226 # Not null constraint
228 unless ( $field->is_nullable ) {
229 $field_def .= ' NOT NULL';
232 $field_def .= ' NULL' if $data_type ne 'bit';
238 SQL::Translator::Producer->_apply_default_value(
246 push @field_defs, $field_def;
250 # Constraint Declarations
252 my @constraint_decs = ();
253 for my $constraint ( $table->get_constraints ) {
254 my $name = $constraint->name || '';
255 my $name_ur = unreserve($name);
256 # Make sure we get a unique name
257 my $type = $constraint->type || NORMAL;
258 my @fields = map { unreserve( $_ ) }
260 my @rfields = map { unreserve( $_ ) }
261 $constraint->reference_fields;
265 if ( $type eq FOREIGN_KEY ) {
266 $name ||= mk_name( $table_name . '_fk' );
267 my $on_delete = uc ($constraint->on_delete || '');
268 my $on_update = uc ($constraint->on_update || '');
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'
277 "ALTER TABLE $table_name_ur ADD CONSTRAINT $name_ur FOREIGN KEY".
278 ' (' . join( ', ', @fields ) . ') REFERENCES '.
279 unreserve($constraint->reference_table).
280 ' (' . join( ', ', @rfields ) . ')'
283 if ( $on_delete && $on_delete ne "NO ACTION") {
284 $c_def .= " ON DELETE $on_delete";
286 if ( $on_update && $on_update ne "NO ACTION") {
287 $c_def .= " ON UPDATE $on_update";
292 push @foreign_constraints, $c_def;
297 if ( $type eq PRIMARY_KEY ) {
298 $name = ($name ? unreserve($name) : mk_name( $table_name . '_pk' ));
300 "CONSTRAINT $name PRIMARY KEY ".
301 '(' . join( ', ', @fields ) . ')';
303 elsif ( $type eq UNIQUE ) {
304 $name = $name_ur || mk_name( $table_name . '_uc' );
306 "CONSTRAINT $name UNIQUE " .
307 '(' . join( ', ', @fields ) . ')';
309 push @constraint_defs, $c_def;
315 for my $index ( $table->get_indices ) {
316 my $idx_name = $index->name || mk_name($table_name . '_idx');
317 my $idx_name_ur = unreserve($idx_name);
319 "CREATE INDEX $idx_name_ur ON $table_name_ur (".
320 join( ', ', map unreserve($_), $index->fields ) . ");";
323 my $create_statement = "";
324 $create_statement .= qq[CREATE TABLE $table_name_ur (\n].
326 map { " $_" } @field_defs, @constraint_defs
331 $output .= join( "\n\n",
339 $output .= join ("\n", '', @foreign_constraints) if @foreign_constraints;
341 # create view/procedure are NOT prepended to the input $sql, needs
342 # to be filled in with the proper syntax
346 # Text of view is already a 'create view' statement so no need to
348 foreach ( $schema->get_views ) {
349 my $name = $_->name();
351 $output .= "--\n-- View: $name\n--\n\n" unless $no_comments;
352 my $text = $_->sql();
354 $output .= "$text\nGO\n";
357 # Text of procedure already has the 'create procedure' stuff
358 # so there is no need to do anything fancy. However, we should
359 # think about doing fancy stuff with granting permissions and
361 foreach ( $schema->get_procedures ) {
362 my $name = $_->name();
364 $output .= "--\n-- Procedure: $name\n--\n\n" unless $no_comments;
365 my $text = $_->sql();
367 $output .= "$text\nGO\n";
374 # -------------------------------------------------------------------
376 my ($name, $scope, $critical) = @_;
378 $scope ||= \%global_names;
379 if ( my $prev = $scope->{ $name } ) {
380 my $name_orig = $name;
381 $name .= sprintf( "%02d", ++$prev );
382 substr($name, $max_id_length - 3) = "00"
383 if length( $name ) > $max_id_length;
385 warn "The name '$name_orig' has been changed to ",
386 "'$name' to make it unique.\n" if $WARN;
388 $scope->{ $name_orig }++;
390 $name = substr( $name, 0, $max_id_length )
391 if ((length( $name ) > $max_id_length) && $critical);
393 return unreserve($name);
396 # -------------------------------------------------------------------
397 sub unreserve { $shim->quote($_[0]) }
401 # -------------------------------------------------------------------
411 Mark Addison E<lt>grommit@users.sourceforge.netE<gt> - Bulk of code from
412 Sybase producer, I just tweaked it for SQLServer. Thanks.