- Removed use of $Revision$ SVN keyword to generate VERSION variables; now sub-module...
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Parser / XML / SQLFairy.pm
1 package SQL::Translator::Parser::XML::SQLFairy;
2
3 # -------------------------------------------------------------------
4 # $Id$
5 # -------------------------------------------------------------------
6 # Copyright (C) 2003 Mark Addison <mark.addison@itn.co.uk>,
7 #
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License as
10 # published by the Free Software Foundation; version 2.
11 #
12 # This program is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20 # 02111-1307  USA
21 # -------------------------------------------------------------------
22
23 =head1 NAME
24
25 SQL::Translator::Parser::XML::SQLFairy - parser for SQL::Translator's XML.
26
27 =head1 SYNOPSIS
28
29   use SQL::Translator;
30
31   my $translator = SQL::Translator->new( show_warnings  => 1 );
32
33   my $out = $obj->translate(
34       from     => 'XML-SQLFairy',
35       to       => 'MySQL',
36       filename => 'schema.xml',
37   ) or die $translator->error;
38
39   print $out;
40
41 =head1 DESCRIPTION
42
43 This parser handles the flavor of XML used natively by the SQLFairy
44 project (L<SQL::Translator>).  The XML must be in the namespace
45 "http://sqlfairy.sourceforge.net/sqlfairy.xml."
46 See L<SQL::Translator::Producer::XML::SQLFairy> for details of this format.
47
48 You do not need to specify every attribute of the Schema objects as any missing
49 from the XML will be set to their default values. e.g. A field could be written
50 using only;
51
52  <sqlf:field name="email" data_type="varchar" size="255" />
53
54 Instead of the full;
55
56  <sqlf:field name="email" data_type="varchar" size="255" is_nullable="1"
57    is_auto_increment="0" is_primary_key="0" is_foreign_key="0" order="4">
58    <sqlf:comments></sqlf:comments>
59  </sqlf:field>
60
61 If you do not explicitly set the order of items using order attributes on the
62 tags then the order the tags appear in the XML will be used.
63
64 =head2 default_value
65
66 Leave the attribute out all together to use the default in L<Schema::Field>.
67 Use empty quotes or 'EMPTY_STRING' for a zero lenth string. 'NULL' for an
68 explicit null (currently sets default_value to undef in the
69 Schema::Field obj).
70
71   <sqlf:field default_value="" />                <!-- Empty string -->
72   <sqlf:field default_value="EMPTY_STRING" />    <!-- Empty string -->
73   <sqlf:field default_value="NULL" />            <!-- NULL -->
74
75 =head2 ARGS
76
77 Doesn't take any extra parser args at the moment.
78
79 =head1 LEGACY FORMAT
80
81 The previous version of the SQLFairy XML allowed the attributes of the the
82 schema objects to be written as either xml attributes or as data elements, in
83 any combination. While this allows for lots of flexibility in writing the XML
84 the result is a great many possible XML formats, not so good for DTD writing,
85 XPathing etc! So we have moved to a fixed version described in
86 L<SQL::Translator::Producer::XML::SQLFairy>.
87
88 This version of the parser will still parse the old formats and emmit warnings
89 when it sees them being used but they should be considered B<heavily
90 depreciated>.
91
92 To convert your old format files simply pass them through the translator :)
93
94  $ sqlt -f XML-SQLFairy -t XML-SQLFairy schema-old.xml > schema-new.xml
95
96 =cut
97
98 # -------------------------------------------------------------------
99
100 use strict;
101
102 use vars qw[ $DEBUG @EXPORT_OK ];
103 $DEBUG   = 0 unless defined $DEBUG;
104
105 use Data::Dumper;
106 use Exporter;
107 use base qw(Exporter);
108 @EXPORT_OK = qw(parse);
109
110 use base qw/SQL::Translator::Parser/;  # Doesnt do anything at the mo!
111 use SQL::Translator::Utils 'debug';
112 use XML::XPath;
113 use XML::XPath::XMLParser;
114
115 sub parse {
116     my ( $translator, $data ) = @_;
117     my $schema                = $translator->schema;
118     local $DEBUG              = $translator->debug;
119     my $xp                    = XML::XPath->new(xml => $data);
120
121     $xp->set_namespace("sqlf", "http://sqlfairy.sourceforge.net/sqlfairy.xml");
122
123     #
124     # Work our way through the tables
125     #
126     my @nodes = $xp->findnodes(
127         '/sqlf:schema/sqlf:table|/sqlf:schema/sqlf:tables/sqlf:table'
128     );
129     for my $tblnode (
130         sort {
131             ("".$xp->findvalue('sqlf:order|@order',$a) || 0)
132             <=>
133             ("".$xp->findvalue('sqlf:order|@order',$b) || 0)
134         } @nodes
135     ) {
136         debug "Adding table:".$xp->findvalue('sqlf:name',$tblnode);
137
138         my $table = $schema->add_table(
139             get_tagfields($xp, $tblnode, "sqlf:" => qw/name order extra/)
140         ) or die $schema->error;
141
142         #
143         # Fields
144         #
145         my @nodes = $xp->findnodes('sqlf:fields/sqlf:field',$tblnode);
146         foreach (
147             sort {
148                 ("".$xp->findvalue('sqlf:order',$a) || 0)
149                 <=>
150                 ("".$xp->findvalue('sqlf:order',$b) || 0)
151             } @nodes
152         ) {
153             my %fdata = get_tagfields($xp, $_, "sqlf:",
154                 qw/name data_type size default_value is_nullable extra
155                 is_auto_increment is_primary_key is_foreign_key comments/
156             );
157
158             if (
159                 exists $fdata{'default_value'} and
160                 defined $fdata{'default_value'}
161             ) {
162                 if ( $fdata{'default_value'} =~ /^\s*NULL\s*$/ ) {
163                     $fdata{'default_value'}= undef;
164                 }
165                 elsif ( $fdata{'default_value'} =~ /^\s*EMPTY_STRING\s*$/ ) {
166                     $fdata{'default_value'} = "";
167                 }
168             }
169
170             my $field = $table->add_field( %fdata ) or die $table->error;
171
172             $table->primary_key( $field->name ) if $fdata{'is_primary_key'};
173
174             #
175             # TODO:
176             # - We should be able to make the table obj spot this when
177             #   we use add_field.
178             #
179         }
180
181         #
182         # Constraints
183         #
184         @nodes = $xp->findnodes('sqlf:constraints/sqlf:constraint',$tblnode);
185         foreach (@nodes) {
186             my %data = get_tagfields($xp, $_, "sqlf:",
187                 qw/name type table fields reference_fields reference_table
188                 match_type on_delete on_update extra/
189             );
190             $table->add_constraint( %data ) or die $table->error;
191         }
192
193         #
194         # Indexes
195         #
196         @nodes = $xp->findnodes('sqlf:indices/sqlf:index',$tblnode);
197         foreach (@nodes) {
198             my %data = get_tagfields($xp, $_, "sqlf:",
199                 qw/name type fields options extra/);
200             $table->add_index( %data ) or die $table->error;
201         }
202
203         
204         #
205         # Comments
206         #
207         @nodes = $xp->findnodes('sqlf:comments/sqlf:comment',$tblnode);
208         foreach (@nodes) {
209             my $data = $_->string_value;
210             $table->comments( $data );
211         }
212
213     } # tables loop
214
215     #
216     # Views
217     #
218     @nodes = $xp->findnodes(
219         '/sqlf:schema/sqlf:view|/sqlf:schema/sqlf:views/sqlf:view'
220     );
221     foreach (@nodes) {
222         my %data = get_tagfields($xp, $_, "sqlf:",
223             qw/name sql fields order extra/
224         );
225         $schema->add_view( %data ) or die $schema->error;
226     }
227
228     #
229     # Triggers
230     #
231     @nodes = $xp->findnodes(
232         '/sqlf:schema/sqlf:trigger|/sqlf:schema/sqlf:triggers/sqlf:trigger'
233     );
234     foreach (@nodes) {
235         my %data = get_tagfields($xp, $_, "sqlf:", qw/
236             name perform_action_when database_event fields on_table action order
237             extra
238         /);
239         $schema->add_trigger( %data ) or die $schema->error;
240     }
241
242     #
243     # Procedures
244     #
245     @nodes = $xp->findnodes(
246        '/sqlf:schema/sqlf:procedure|/sqlf:schema/sqlf:procedures/sqlf:procedure'
247     );
248     foreach (@nodes) {
249         my %data = get_tagfields($xp, $_, "sqlf:",
250         qw/name sql parameters owner comments order extra/
251         );
252         $schema->add_procedure( %data ) or die $schema->error;
253     }
254
255     return 1;
256 }
257
258 # -------------------------------------------------------------------
259 sub get_tagfields {
260 #
261 # get_tagfields XP, NODE, NAMESPACE => qw/TAGNAMES/;
262 # get_tagfields $node, "sqlf:" => qw/name type fields reference/;
263 #
264 # Returns hash of data.
265 # TODO - Add handling of an explicit NULL value.
266 #
267
268     my ($xp, $node, @names) = @_;
269     my (%data, $ns);
270     foreach (@names) {
271         if ( m/:$/ ) { $ns = $_; next; }  # Set def namespace
272         my $thisns = (s/(^.*?:)// ? $1 : $ns);
273
274         my $is_attrib = m/^(sql|comments|action|extra)$/ ? 0 : 1;
275
276         my $attrib_path = "\@$thisns$_";
277         my $tag_path    = "$thisns$_";
278         if ( $xp->exists($attrib_path,$node) ) {
279             $data{$_} = "".$xp->findvalue($attrib_path,$node);
280             warn "Use of '$_' as an attribute is depricated."
281                 ." Use a child tag instead."
282                 ." To convert your file to the new version see the Docs.\n"
283                 unless $is_attrib;
284             debug "Got $_=".( defined $data{ $_ } ? $data{ $_ } : 'UNDEF' );
285         }
286         elsif ( $xp->exists($tag_path,$node) ) {
287             if ($_ eq "extra") {
288                 my %extra;
289                 my $extra_nodes = $xp->find($tag_path,$node);
290                 foreach ( $extra_nodes->pop->getAttributes ) {
291                     $extra{$_->getName} = $_->getData;
292                 }
293                 $data{$_} = \%extra;
294             }
295             else {
296                 $data{$_} = "".$xp->findvalue($tag_path,$node);
297             }
298             warn "Use of '$_' as a child tag is depricated."
299                 ." Use an attribute instead."
300                 ." To convert your file to the new version see the Docs.\n"
301                 if $is_attrib;
302             debug "Got $_=".( defined $data{ $_ } ? $data{ $_ } : 'UNDEF' );
303         }
304     }
305
306     return wantarray ? %data : \%data;
307 }
308
309 1;
310
311 # -------------------------------------------------------------------
312
313 =pod
314
315 =head1 BUGS
316
317 Ignores the order attribute for Constraints, Views, Indices,
318 Views, Triggers and Procedures, using the tag order instead. (This is the order
319 output by the SQLFairy XML producer).
320
321 =head1 SEE ALSO
322
323 L<perl>, L<SQL::Translator>, L<SQL::Translator::Producer::XML::SQLFairy>,
324 L<SQL::Translator::Schema>.
325
326 =head1 TODO
327
328 =over 4
329
330 =item *
331
332 Support options attribute.
333
334 =item *
335
336 Test foreign keys are parsed ok.
337
338 =item *
339
340 Control over defaulting.
341
342 =back
343
344 =head1 AUTHOR
345
346 Mark D. Addison E<lt>mark.addison@itn.co.ukE<gt>.
347
348 =cut