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
38 use vars qw[ $DEBUG $WARN $VERSION ];
40 $DEBUG = 1 unless defined $DEBUG;
43 use SQL::Translator::Schema::Constants;
44 use SQL::Translator::Utils qw(debug header_comment);
45 use SQL::Translator::ProducerUtils;
47 my $util = SQL::Translator::ProducerUtils->new( quote_chars => ['[', ']'] );
53 #integer => 'numeric',
57 #varchar => 'varchar',
58 #varchar2 => 'varchar',
59 #timestamp => 'datetime',
61 #real => 'double precision',
64 #tinyint => 'smallint',
65 #float => 'double precision',
67 #boolean => 'varchar',
72 # If these datatypes have size appended the sql fails.
73 my @no_size = qw/tinyint smallint int integer bigint text bit image datetime/;
75 my $max_id_length = 128;
80 =head1 SQLServer Create Table Syntax
87 my $translator = shift;
88 $DEBUG = $translator->debug;
89 $WARN = $translator->show_warnings;
90 my $no_comments = $translator->no_comments;
91 my $add_drop_table = $translator->add_drop_table;
92 my $schema = $translator->schema;
94 %global_names = (); #reset
97 $output .= header_comment."\n" unless ($no_comments);
99 # Generate the DROP statements.
100 if ($add_drop_table) {
101 my @tables = sort { $b->order <=> $a->order } $schema->get_tables;
102 $output .= "--\n-- Turn off constraints\n--\n\n" unless $no_comments;
103 foreach my $table (@tables) {
104 my $name = $table->name;
105 my $q_name = unreserve($name);
106 $output .= "IF EXISTS (SELECT name FROM sysobjects WHERE name = '$name' AND type = 'U') ALTER TABLE $q_name NOCHECK CONSTRAINT all;\n"
109 $output .= "--\n-- Drop tables\n--\n\n" unless $no_comments;
110 foreach my $table (@tables) {
111 my $name = $table->name;
112 my $q_name = unreserve($name);
113 $output .= "IF EXISTS (SELECT name FROM sysobjects WHERE name = '$name' AND type = 'U') DROP TABLE $q_name;\n"
117 # Generate the CREATE sql
119 my @foreign_constraints = (); # these need to be added separately, as tables may not exist yet
121 for my $table ( $schema->get_tables ) {
122 my $table_name = $table->name or next;
123 my $table_name_ur = unreserve($table_name) || '';
125 my ( @comments, @field_defs, @index_defs, @constraint_defs );
127 push @comments, "\n\n--\n-- Table: $table_name_ur\n--"
130 push @comments, map { "-- $_" } $table->comments;
135 my %field_name_scope;
136 for my $field ( $table->get_fields ) {
137 my $field_name = $field->name;
138 my $field_name_ur = unreserve( $field_name );
139 my $field_def = qq["$field_name_ur"];
140 $field_def =~ s/\"//g;
141 if ( $field_def =~ /identity/ ){
142 $field_def =~ s/identity/pidentity/;
148 my $data_type = lc $field->data_type;
149 my $orig_data_type = $data_type;
150 my %extra = $field->extra;
151 my $list = $extra{'list'} || [];
152 # \todo deal with embedded quotes
153 my $commalist = join( ', ', map { qq['$_'] } @$list );
155 if ( $data_type eq 'enum' ) {
156 my $check_name = mk_name( $field_name . '_chk' );
157 push @constraint_defs,
158 "CONSTRAINT $check_name CHECK ($field_name IN ($commalist))";
159 $data_type .= 'character varying';
161 elsif ( $data_type eq 'set' ) {
162 $data_type .= 'character varying';
164 elsif ( grep { $data_type eq $_ } qw/bytea blob clob/ ) {
165 $data_type = 'varbinary';
168 if ( defined $translate{ $data_type } ) {
169 $data_type = $translate{ $data_type };
172 warn "Unknown datatype: $data_type ",
173 "($table_name.$field_name)\n" if $WARN;
177 my $size = $field->size;
178 if ( grep $_ eq $data_type, @no_size) {
179 # SQLServer doesn't seem to like sizes on some datatypes
183 if ( $data_type =~ /numeric/ ) {
186 elsif ( $orig_data_type eq 'text' ) {
187 #interpret text fields as long varchars
191 $data_type eq 'varchar' &&
192 $orig_data_type eq 'boolean'
196 elsif ( $data_type eq 'varchar' ) {
201 $field_def .= " $data_type";
202 $field_def .= "($size)" if $size;
204 $field_def .= ' IDENTITY' if $field->is_auto_increment;
207 # Not null constraint
209 unless ( $field->is_nullable ) {
210 $field_def .= ' NOT NULL';
213 $field_def .= ' NULL' if $data_type ne 'bit';
219 SQL::Translator::Producer->_apply_default_value(
227 push @field_defs, $field_def;
231 # Constraint Declarations
233 my @constraint_decs = ();
234 for my $constraint ( $table->get_constraints ) {
235 my $name = $constraint->name || '';
236 my $name_ur = unreserve($name);
237 # Make sure we get a unique name
238 my $type = $constraint->type || NORMAL;
239 my @fields = map { unreserve( $_ ) }
241 my @rfields = map { unreserve( $_ ) }
242 $constraint->reference_fields;
246 if ( $type eq FOREIGN_KEY ) {
247 $name ||= mk_name( $table_name . '_fk' );
248 my $on_delete = uc ($constraint->on_delete || '');
249 my $on_update = uc ($constraint->on_update || '');
251 # The default implicit constraint action in MSSQL is RESTRICT
252 # but you can not specify it explicitly. Go figure :)
253 for ($on_delete, $on_update) {
254 undef $_ if $_ eq 'RESTRICT'
258 "ALTER TABLE $table_name_ur ADD CONSTRAINT $name_ur FOREIGN KEY".
259 ' (' . join( ', ', @fields ) . ') REFERENCES '.
260 unreserve($constraint->reference_table).
261 ' (' . join( ', ', @rfields ) . ')'
264 if ( $on_delete && $on_delete ne "NO ACTION") {
265 $c_def .= " ON DELETE $on_delete";
267 if ( $on_update && $on_update ne "NO ACTION") {
268 $c_def .= " ON UPDATE $on_update";
273 push @foreign_constraints, $c_def;
278 if ( $type eq PRIMARY_KEY ) {
279 $name = ($name ? unreserve($name) : mk_name( $table_name . '_pk' ));
281 "CONSTRAINT $name PRIMARY KEY ".
282 '(' . join( ', ', @fields ) . ')';
284 elsif ( $type eq UNIQUE ) {
285 $name = $name_ur || mk_name( $table_name . '_uc' );
286 my @nullable = grep { $_->is_nullable } $constraint->fields;
289 "CONSTRAINT $name UNIQUE " .
290 '(' . join( ', ', @fields ) . ')';
293 "CREATE UNIQUE NONCLUSTERED INDEX $name_ur ON $table_name_ur (" .
294 join( ', ', @fields ) . ')' .
295 ' WHERE ' . join( ' AND ', map unreserve($_->name) . ' IS NOT NULL', @nullable ) . ';';
299 push @constraint_defs, $c_def;
305 for my $index ( $table->get_indices ) {
306 my $idx_name = $index->name || mk_name($table_name . '_idx');
307 my $idx_name_ur = unreserve($idx_name);
309 "CREATE INDEX $idx_name_ur ON $table_name_ur (".
310 join( ', ', map unreserve($_), $index->fields ) . ");";
313 my $create_statement = "";
314 $create_statement .= qq[CREATE TABLE $table_name_ur (\n].
316 map { " $_" } @field_defs, @constraint_defs
321 $output .= join( "\n\n",
329 $output .= join ("\n", '', @foreign_constraints) if @foreign_constraints;
331 # create view/procedure are NOT prepended to the input $sql, needs
332 # to be filled in with the proper syntax
336 # Text of view is already a 'create view' statement so no need to
338 foreach ( $schema->get_views ) {
339 my $name = $_->name();
341 $output .= "--\n-- View: $name\n--\n\n" unless $no_comments;
342 my $text = $_->sql();
344 $output .= "$text\nGO\n";
347 # Text of procedure already has the 'create procedure' stuff
348 # so there is no need to do anything fancy. However, we should
349 # think about doing fancy stuff with granting permissions and
351 foreach ( $schema->get_procedures ) {
352 my $name = $_->name();
354 $output .= "--\n-- Procedure: $name\n--\n\n" unless $no_comments;
355 my $text = $_->sql();
357 $output .= "$text\nGO\n";
365 my ($name, $scope, $critical) = @_;
367 $scope ||= \%global_names;
368 if ( my $prev = $scope->{ $name } ) {
369 my $name_orig = $name;
370 $name .= sprintf( "%02d", ++$prev );
371 substr($name, $max_id_length - 3) = "00"
372 if length( $name ) > $max_id_length;
374 warn "The name '$name_orig' has been changed to ",
375 "'$name' to make it unique.\n" if $WARN;
377 $scope->{ $name_orig }++;
379 $name = substr( $name, 0, $max_id_length )
380 if ((length( $name ) > $max_id_length) && $critical);
382 return unreserve($name);
385 sub unreserve { $util->quote($_[0]) }
397 Mark Addison E<lt>grommit@users.sourceforge.netE<gt> - Bulk of code from
398 Sybase producer, I just tweaked it for SQLServer. Thanks.