Fixed "database_events."
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / XML / SQLFairy.pm
1 package SQL::Translator::Producer::XML::SQLFairy;
2
3 # -------------------------------------------------------------------
4 # Copyright (C) 2003 Ken Y. Clark <kclark@cpan.org>,
5 #                    darren chamberlain <darren@cpan.org>,
6 #                    Chris Mungall <cjm@fruitfly.org>,
7 #                    Mark Addison <mark.addison@itn.co.uk>.
8 #
9 # This program is free software; you can redistribute it and/or
10 # modify it under the terms of the GNU General Public License as
11 # published by the Free Software Foundation; version 2.
12 #
13 # This program is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 # General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21 # 02111-1307  USA
22 # -------------------------------------------------------------------
23
24 =pod
25
26 =head1 NAME
27
28 SQL::Translator::Producer::XML::SQLFairy - SQLFairy's default XML format
29
30 =head1 SYNOPSIS
31
32   use SQL::Translator;
33
34   my $t              = SQL::Translator->new(
35       from           => 'MySQL',
36       to             => 'XML-SQLFairy',
37       filename       => 'schema.sql',
38       show_warnings  => 1,
39   );
40
41   print $t->translate;
42
43 =head1 DESCRIPTION
44
45 Creates XML output of a schema, in the flavor of XML used natively by the
46 SQLFairy project (L<SQL::Translator>). This format is detailed here.
47
48 The XML lives in the C<http://sqlfairy.sourceforge.net/sqlfairy.xml> namespace.
49 With a root element of <schema>.
50
51 Objects in the schema are mapped to tags of the same name as the objects class
52 (all lowercase).
53
54 The attributes of the objects (e.g. $field->name) are mapped to attributes of
55 the tag, except for sql, comments and action, which get mapped to child data
56 elements.
57
58 List valued attributes (such as the list of fields in an index)
59 get mapped to comma seperated lists of values in the attribute.
60
61 Child objects, such as a tables fields, get mapped to child tags wrapped in a
62 set of container tags using the plural of their contained classes name.
63
64 An objects's extra attribute (a hash of arbitary data) is
65 mapped to a tag called extra, with the hash of data as attributes, sorted into
66 alphabetical order.
67
68 e.g.
69
70     <schema name="" database=""
71       xmlns="http://sqlfairy.sourceforge.net/sqlfairy.xml">
72
73       <tables>
74         <table name="Story" order="1">
75           <fields>
76             <field name="id" data_type="BIGINT" size="20"
77               is_nullable="0" is_auto_increment="1" is_primary_key="1"
78               is_foreign_key="0" order="3">
79               <extra ZEROFILL="1" />
80               <comments></comments>
81             </field>
82             <field name="created" data_type="datetime" size="0"
83               is_nullable="1" is_auto_increment="0" is_primary_key="0"
84               is_foreign_key="0" order="1">
85               <extra />
86               <comments></comments>
87             </field>
88             ...
89           </fields>
90           <indices>
91             <index name="foobar" type="NORMAL" fields="foo,bar" options="" />
92           </indices>
93         </table>
94       </tables>
95
96       <views>
97         <view name="email_list" fields="email" order="1">
98           <sql>SELECT email FROM Basic WHERE email IS NOT NULL</sql>
99         </view>
100       </views>
101
102     </schema>
103
104 To see a complete example of the XML translate one of your schema :)
105
106   $ sqlt -f MySQL -t XML-SQLFairy schema.sql
107
108 =head1 ARGS
109
110 =over 4
111
112 =item add_prefix
113
114 Set to true to use the default namespace prefix of 'sqlf', instead of using
115 the default namespace for
116 C<http://sqlfairy.sourceforge.net/sqlfairy.xml namespace>
117
118 e.g.
119
120  <!-- add_prefix=0 -->
121  <field name="foo" />
122
123  <!-- add_prefix=1 -->
124  <sqlf:field name="foo" />
125
126 =item prefix
127
128 Set to the namespace prefix you want to use for the
129 C<http://sqlfairy.sourceforge.net/sqlfairy.xml namespace>
130
131 e.g.
132
133  <!-- prefix='foo' -->
134  <foo:field name="foo" />
135
136 =item newlines
137
138 If true (the default) inserts newlines around the XML, otherwise the schema is
139 written on one line.
140
141 =item indent
142
143 When using newlines the number of whitespace characters to use as the indent.
144 Default is 2, set to 0 to turn off indenting.
145
146 =back
147
148 =head1 LEGACY FORMAT
149
150 The previous version of the SQLFairy XML allowed the attributes of the the
151 schema objects to be written as either xml attributes or as data elements, in
152 any combination. The old producer could produce attribute only or data element
153 only versions. While this allowed for lots of flexibility in writing the XML
154 the result is a great many possible XML formats, not so good for DTD writing,
155 XPathing etc! So we have moved to a fixed version described above.
156
157 This version of the producer will now only produce the new style XML.
158 To convert your old format files simply pass them through the translator :)
159
160  $ sqlt -f XML-SQLFairy -t XML-SQLFairy schema-old.xml > schema-new.xml
161
162 =cut
163
164 use strict;
165 use vars qw[ $VERSION @EXPORT_OK ];
166 $VERSION = '1.59';
167
168 use Exporter;
169 use base qw(Exporter);
170 @EXPORT_OK = qw(produce);
171
172 use IO::Scalar;
173 use SQL::Translator::Utils qw(header_comment debug);
174 BEGIN {
175     # Will someone fix XML::Writer already?
176     local $^W = 0;
177     require XML::Writer;
178     import XML::Writer;
179 }
180
181 # Which schema object attributes (methods) to write as xml elements rather than
182 # as attributes. e.g. <comments>blah, blah...</comments>
183 my @MAP_AS_ELEMENTS = qw/sql comments action extra/;
184
185
186
187 my $Namespace = 'http://sqlfairy.sourceforge.net/sqlfairy.xml';
188 my $Name      = 'sqlf';
189 my $PArgs     = {};
190
191 sub produce {
192     my $translator  = shift;
193     my $schema      = $translator->schema;
194     $PArgs          = $translator->producer_args;
195     my $newlines    = defined $PArgs->{newlines} ? $PArgs->{newlines} : 1;
196     my $indent      = defined $PArgs->{indent}   ? $PArgs->{indent}   : 2;
197     my $io          = IO::Scalar->new;
198
199     # Setup the XML::Writer and set the namespace
200     my $prefix = "";
201     $prefix    = $Name            if $PArgs->{add_prefix};
202     $prefix    = $PArgs->{prefix} if $PArgs->{prefix};
203     my $xml         = XML::Writer->new(
204         OUTPUT      => $io,
205         NAMESPACES  => 1,
206         PREFIX_MAP  => { $Namespace => $prefix },
207         DATA_MODE   => $newlines,
208         DATA_INDENT => $indent,
209     );
210
211     # Start the document
212     $xml->xmlDecl('UTF-8');
213     $xml->comment(header_comment('', ''));
214     xml_obj($xml, $schema,
215         tag => "schema", methods => [qw/name database extra/], end_tag => 0 );
216
217     #
218     # Table
219     #
220     $xml->startTag( [ $Namespace => "tables" ] );
221     for my $table ( $schema->get_tables ) {
222         debug "Table:",$table->name;
223         xml_obj($xml, $table,
224              tag => "table",
225              methods => [qw/name order extra/],
226              end_tag => 0
227          );
228
229         #
230         # Fields
231         #
232         xml_obj_children( $xml, $table,
233             tag   => 'field',
234             methods =>[qw/
235                 name data_type size is_nullable default_value is_auto_increment
236                 is_primary_key is_foreign_key extra comments order
237             /],
238         );
239
240         #
241         # Indices
242         #
243         xml_obj_children( $xml, $table,
244             tag   => 'index',
245             collection_tag => "indices",
246             methods => [qw/name type fields options extra/],
247         );
248
249         #
250         # Constraints
251         #
252         xml_obj_children( $xml, $table,
253             tag   => 'constraint',
254             methods => [qw/
255                 name type fields reference_table reference_fields
256                 on_delete on_update match_type expression options deferrable
257                 extra
258             /],
259         );
260
261         #
262         # Comments
263         #
264         xml_obj_children( $xml, $table,
265             tag   => 'comment',
266             collection_tag => "comments",
267             methods => [qw/
268                 comments
269             /],
270         );
271
272         $xml->endTag( [ $Namespace => 'table' ] );
273     }
274     $xml->endTag( [ $Namespace => 'tables' ] );
275
276     #
277     # Views
278     #
279     xml_obj_children( $xml, $schema,
280         tag   => 'view',
281         methods => [qw/name sql fields order extra/],
282     );
283
284     #
285     # Tiggers
286     #
287     xml_obj_children( $xml, $schema,
288         tag    => 'trigger',
289         methods => [qw/name database_events action on_table perform_action_when
290             fields order extra/],
291     );
292
293     #
294     # Procedures
295     #
296     xml_obj_children( $xml, $schema,
297         tag   => 'procedure',
298         methods => [qw/name sql parameters owner comments order extra/],
299     );
300
301     $xml->endTag([ $Namespace => 'schema' ]);
302     $xml->end;
303
304     return $io;
305 }
306
307
308 #
309 # Takes and XML::Write object, Schema::* parent object, the tag name,
310 # the collection name and a list of methods (of the children) to write as XML.
311 # The collection name defaults to the name with an s on the end and is used to
312 # work out the method to get the children with. eg a name of 'foo' gives a
313 # collection of foos and gets the members using ->get_foos.
314 #
315 sub xml_obj_children {
316     my ($xml,$parent) = (shift,shift);
317     my %args = @_;
318     my ($name,$collection_name,$methods)
319         = @args{qw/tag collection_tag methods/};
320     $collection_name ||= "${name}s";
321
322     my $meth;
323     if ( $collection_name eq 'comments' ) {
324       $meth = 'comments';
325     } else {
326       $meth = "get_$collection_name";
327     }
328
329     my @kids = $parent->$meth;
330     #@kids || return;
331     $xml->startTag( [ $Namespace => $collection_name ] );
332
333     for my $obj ( @kids ) {
334         if ( $collection_name eq 'comments' ){
335             $xml->dataElement( [ $Namespace => 'comment' ], $obj );
336         } else {
337             xml_obj($xml, $obj,
338                 tag     => "$name",
339                 end_tag => 1,
340                 methods => $methods,
341             );
342         }
343     }
344     $xml->endTag( [ $Namespace => $collection_name ] );
345 }
346
347 #
348 # Takes an XML::Writer, Schema::* object and list of method names
349 # and writes the obect out as XML. All methods values are written as attributes
350 # except for the methods listed in @MAP_AS_ELEMENTS which get written as child
351 # data elements.
352 #
353 # The attributes/tags are written in the same order as the method names are
354 # passed.
355 #
356 # TODO
357 # - Should the Namespace be passed in instead of global? Pass in the same
358 #   as Writer ie [ NS => TAGNAME ]
359 #
360 my $elements_re = join("|", @MAP_AS_ELEMENTS);
361 $elements_re = qr/^($elements_re)$/;
362 sub xml_obj {
363     my ($xml, $obj, %args) = @_;
364     my $tag                = $args{'tag'}              || '';
365     my $end_tag            = $args{'end_tag'}          || '';
366     my @meths              = @{ $args{'methods'} };
367     my $empty_tag          = 0;
368
369     # Use array to ensure consistant (ie not hash) ordering of attribs
370     # The order comes from the meths list passed in.
371     my @tags;
372     my @attr;
373     foreach ( grep { defined $obj->$_ } @meths ) {
374         my $what = m/$elements_re/ ? \@tags : \@attr;
375         my $val = $_ eq 'extra'
376             ? { $obj->$_ }
377             : $obj->$_;
378         $val = ref $val eq 'ARRAY' ? join(',', @$val) : $val;
379         push @$what, $_ => $val;
380     };
381     my $child_tags = @tags;
382     $end_tag && !$child_tags
383         ? $xml->emptyTag( [ $Namespace => $tag ], @attr )
384         : $xml->startTag( [ $Namespace => $tag ], @attr );
385     while ( my ($name,$val) = splice @tags,0,2 ) {
386         if ( ref $val eq 'HASH' ) {
387              $xml->emptyTag( [ $Namespace => $name ],
388                  map { ($_, $val->{$_}) } sort keys %$val );
389         }
390         else {
391             $xml->dataElement( [ $Namespace => $name ], $val );
392         }
393     }
394     $xml->endTag( [ $Namespace => $tag ] ) if $child_tags && $end_tag;
395 }
396
397 1;
398
399 # -------------------------------------------------------------------
400 # The eyes of fire, the nostrils of air,
401 # The mouth of water, the beard of earth.
402 # William Blake
403 # -------------------------------------------------------------------
404
405 =pod
406
407 =head1 AUTHORS
408
409 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
410 Darren Chamberlain E<lt>darren@cpan.orgE<gt>,
411 Mark Addison E<lt>mark.addison@itn.co.ukE<gt>.
412
413 =head1 SEE ALSO
414
415 L<perl(1)>, L<SQL::Translator>, L<SQL::Translator::Parser::XML::SQLFairy>,
416 L<SQL::Translator::Schema>, L<XML::Writer>.
417
418 =cut