1 package SQL::Translator::Producer::SQLServer;
5 SQL::Translator::Producer::SQLServer - MS SQLServer producer for SQL::Translator
11 my $t = SQL::Translator->new( parser => '...', producer => 'SQLServer' );
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 ;-)
19 =head1 Extra Attributes
25 List of values for an enum field.
31 * !! Write some tests !!
32 * Reserved words list needs updating to SQLServer.
33 * Triggers, Procedures and Views DO NOT WORK
39 our ( $DEBUG, $WARN );
40 our $VERSION = '1.59';
41 $DEBUG = 1 unless defined $DEBUG;
44 use SQL::Translator::Schema::Constants;
45 use SQL::Translator::Utils qw(debug header_comment);
46 use SQL::Translator::Generator::Utils;
48 my $util = SQL::Translator::Generator::Utils->new( quote_chars => ['[', ']'] );
54 #integer => 'numeric',
58 #varchar => 'varchar',
59 #varchar2 => 'varchar',
60 #timestamp => 'datetime',
62 #real => 'double precision',
65 #tinyint => 'smallint',
66 #float => 'double precision',
68 #boolean => 'varchar',
73 # If these datatypes have size appended the sql fails.
74 my @no_size = qw/tinyint smallint int integer bigint text bit image datetime/;
76 my $max_id_length = 128;
81 =head1 SQLServer Create Table Syntax
88 my $translator = shift;
89 $DEBUG = $translator->debug;
90 $WARN = $translator->show_warnings;
91 my $no_comments = $translator->no_comments;
92 my $add_drop_table = $translator->add_drop_table;
93 my $schema = $translator->schema;
95 %global_names = (); #reset
98 $output .= header_comment."\n" unless ($no_comments);
100 # Generate the DROP statements.
101 if ($add_drop_table) {
102 my @tables = sort { $b->order <=> $a->order } $schema->get_tables;
103 $output .= "--\n-- Turn off constraints\n--\n\n" unless $no_comments;
104 foreach my $table (@tables) {
105 my $name = $table->name;
106 my $q_name = unreserve($name);
107 $output .= "IF EXISTS (SELECT name FROM sysobjects WHERE name = '$name' AND type = 'U') ALTER TABLE $q_name NOCHECK CONSTRAINT all;\n"
110 $output .= "--\n-- Drop tables\n--\n\n" unless $no_comments;
111 foreach my $table (@tables) {
112 my $name = $table->name;
113 my $q_name = unreserve($name);
114 $output .= "IF EXISTS (SELECT name FROM sysobjects WHERE name = '$name' AND type = 'U') DROP TABLE $q_name;\n"
118 # Generate the CREATE sql
120 my @foreign_constraints = (); # these need to be added separately, as tables may not exist yet
122 for my $table ( $schema->get_tables ) {
123 my $table_name = $table->name or next;
124 my $table_name_ur = unreserve($table_name) || '';
126 my ( @comments, @field_defs, @index_defs, @constraint_defs );
128 push @comments, "\n\n--\n-- Table: $table_name_ur\n--"
131 push @comments, map { "-- $_" } $table->comments;
136 my %field_name_scope;
137 for my $field ( $table->get_fields ) {
138 my $field_name = $field->name;
139 my $field_name_ur = unreserve( $field_name );
140 my $field_def = qq["$field_name_ur"];
141 $field_def =~ s/\"//g;
142 if ( $field_def =~ /identity/ ){
143 $field_def =~ s/identity/pidentity/;
149 my $data_type = lc $field->data_type;
150 my $orig_data_type = $data_type;
151 my %extra = $field->extra;
152 my $list = $extra{'list'} || [];
153 # \todo deal with embedded quotes
154 my $commalist = join( ', ', map { qq['$_'] } @$list );
156 if ( $data_type eq 'enum' ) {
157 my $check_name = mk_name( $field_name . '_chk' );
158 push @constraint_defs,
159 "CONSTRAINT $check_name CHECK ($field_name IN ($commalist))";
160 $data_type .= 'character varying';
162 elsif ( $data_type eq 'set' ) {
163 $data_type .= 'character varying';
165 elsif ( grep { $data_type eq $_ } qw/bytea blob clob/ ) {
166 $data_type = 'varbinary';
169 if ( defined $translate{ $data_type } ) {
170 $data_type = $translate{ $data_type };
173 warn "Unknown datatype: $data_type ",
174 "($table_name.$field_name)\n" if $WARN;
178 my $size = $field->size;
179 if ( grep $_ eq $data_type, @no_size) {
180 # SQLServer doesn't seem to like sizes on some datatypes
184 if ( $data_type =~ /numeric/ ) {
187 elsif ( $orig_data_type eq 'text' ) {
188 #interpret text fields as long varchars
192 $data_type eq 'varchar' &&
193 $orig_data_type eq 'boolean'
197 elsif ( $data_type eq 'varchar' ) {
202 $field_def .= " $data_type";
203 $field_def .= "($size)" if $size;
205 $field_def .= ' IDENTITY' if $field->is_auto_increment;
208 # Not null constraint
210 unless ( $field->is_nullable ) {
211 $field_def .= ' NOT NULL';
214 $field_def .= ' NULL' if $data_type ne 'bit';
220 SQL::Translator::Producer->_apply_default_value(
228 push @field_defs, $field_def;
232 # Constraint Declarations
234 my @constraint_decs = ();
235 for my $constraint ( $table->get_constraints ) {
236 my $name = $constraint->name || '';
237 my $name_ur = unreserve($name);
238 # Make sure we get a unique name
239 my $type = $constraint->type || NORMAL;
240 my @fields = map { unreserve( $_ ) }
242 my @rfields = map { unreserve( $_ ) }
243 $constraint->reference_fields;
247 if ( $type eq FOREIGN_KEY ) {
248 $name ||= mk_name( $table_name . '_fk' );
249 my $on_delete = uc ($constraint->on_delete || '');
250 my $on_update = uc ($constraint->on_update || '');
252 # The default implicit constraint action in MSSQL is RESTRICT
253 # but you can not specify it explicitly. Go figure :)
254 for ($on_delete, $on_update) {
255 undef $_ if $_ eq 'RESTRICT'
259 "ALTER TABLE $table_name_ur ADD CONSTRAINT $name_ur FOREIGN KEY".
260 ' (' . join( ', ', @fields ) . ') REFERENCES '.
261 unreserve($constraint->reference_table).
262 ' (' . join( ', ', @rfields ) . ')'
265 if ( $on_delete && $on_delete ne "NO ACTION") {
266 $c_def .= " ON DELETE $on_delete";
268 if ( $on_update && $on_update ne "NO ACTION") {
269 $c_def .= " ON UPDATE $on_update";
274 push @foreign_constraints, $c_def;
279 if ( $type eq PRIMARY_KEY ) {
280 $name = ($name ? unreserve($name) : mk_name( $table_name . '_pk' ));
282 "CONSTRAINT $name PRIMARY KEY ".
283 '(' . join( ', ', @fields ) . ')';
285 elsif ( $type eq UNIQUE ) {
286 $name = $name_ur || mk_name( $table_name . '_uc' );
287 my @nullable = grep { $_->is_nullable } $constraint->fields;
290 "CONSTRAINT $name UNIQUE " .
291 '(' . join( ', ', @fields ) . ')';
294 "CREATE UNIQUE NONCLUSTERED INDEX $name_ur ON $table_name_ur (" .
295 join( ', ', @fields ) . ')' .
296 ' WHERE ' . join( ' AND ', map unreserve($_->name) . ' IS NOT NULL', @nullable ) . ';';
300 push @constraint_defs, $c_def;
306 for my $index ( $table->get_indices ) {
307 my $idx_name = $index->name || mk_name($table_name . '_idx');
308 my $idx_name_ur = unreserve($idx_name);
310 "CREATE INDEX $idx_name_ur ON $table_name_ur (".
311 join( ', ', map unreserve($_), $index->fields ) . ");";
314 my $create_statement = "";
315 $create_statement .= qq[CREATE TABLE $table_name_ur (\n].
317 map { " $_" } @field_defs, @constraint_defs
322 $output .= join( "\n\n",
330 $output .= join ("\n", '', @foreign_constraints) if @foreign_constraints;
332 # create view/procedure are NOT prepended to the input $sql, needs
333 # to be filled in with the proper syntax
337 # Text of view is already a 'create view' statement so no need to
339 foreach ( $schema->get_views ) {
340 my $name = $_->name();
342 $output .= "--\n-- View: $name\n--\n\n" unless $no_comments;
343 my $text = $_->sql();
345 $output .= "$text\nGO\n";
348 # Text of procedure already has the 'create procedure' stuff
349 # so there is no need to do anything fancy. However, we should
350 # think about doing fancy stuff with granting permissions and
352 foreach ( $schema->get_procedures ) {
353 my $name = $_->name();
355 $output .= "--\n-- Procedure: $name\n--\n\n" unless $no_comments;
356 my $text = $_->sql();
358 $output .= "$text\nGO\n";
366 my ($name, $scope, $critical) = @_;
368 $scope ||= \%global_names;
369 if ( my $prev = $scope->{ $name } ) {
370 my $name_orig = $name;
371 $name .= sprintf( "%02d", ++$prev );
372 substr($name, $max_id_length - 3) = "00"
373 if length( $name ) > $max_id_length;
375 warn "The name '$name_orig' has been changed to ",
376 "'$name' to make it unique.\n" if $WARN;
378 $scope->{ $name_orig }++;
380 $name = substr( $name, 0, $max_id_length )
381 if ((length( $name ) > $max_id_length) && $critical);
383 return unreserve($name);
386 sub unreserve { $util->quote($_[0]) }
398 Mark Addison E<lt>grommit@users.sourceforge.netE<gt> - Bulk of code from
399 Sybase producer, I just tweaked it for SQLServer. Thanks.