Commit | Line | Data |
1a24938d |
1 | package SQL::Translator::Utils; |
2 | |
1a24938d |
3 | use strict; |
f27f9229 |
4 | use warnings; |
c092c5b3 |
5 | use Digest::SHA qw( sha1_hex ); |
bdf60588 |
6 | use File::Spec; |
45287c81 |
7 | use Scalar::Util qw(blessed); |
8 | use Try::Tiny; |
1a24938d |
9 | |
0c04c5a2 |
10 | our $VERSION = '1.59'; |
11 | our $DEFAULT_COMMENT = '-- '; |
bdf60588 |
12 | |
13 | use base qw(Exporter); |
0c04c5a2 |
14 | our @EXPORT_OK = qw( |
7b4b17aa |
15 | debug normalize_name header_comment parse_list_arg truncate_id_uniquely |
16 | $DEFAULT_COMMENT parse_mysql_version parse_dbms_version |
bdf60588 |
17 | ddl_parser_instance |
45287c81 |
18 | throw ex2err |
118bb73f |
19 | ); |
11ad2df9 |
20 | use constant COLLISION_TAG_LENGTH => 8; |
1a24938d |
21 | |
1a24938d |
22 | sub debug { |
a2ba36ba |
23 | my ($pkg, $file, $line, $sub) = caller(0); |
1a24938d |
24 | { |
25 | no strict qw(refs); |
26 | return unless ${"$pkg\::DEBUG"}; |
27 | } |
28 | |
29 | $sub =~ s/^$pkg\:://; |
30 | |
31 | while (@_) { |
32 | my $x = shift; |
33 | chomp $x; |
34 | $x =~ s/\bPKG\b/$pkg/g; |
35 | $x =~ s/\bLINE\b/$line/g; |
36 | $x =~ s/\bSUB\b/$sub/g; |
37 | #warn '[' . $x . "]\n"; |
38 | print STDERR '[' . $x . "]\n"; |
39 | } |
40 | } |
41 | |
93d12e9c |
42 | sub normalize_name { |
ae48473b |
43 | my $name = shift or return ''; |
93d12e9c |
44 | |
45 | # The name can only begin with a-zA-Z_; if there's anything |
46 | # else, prefix with _ |
47 | $name =~ s/^([^a-zA-Z_])/_$1/; |
48 | |
49 | # anything other than a-zA-Z0-9_ in the non-first position |
50 | # needs to be turned into _ |
51 | $name =~ tr/[a-zA-Z0-9_]/_/c; |
52 | |
53 | # All duplicated _ need to be squashed into one. |
54 | $name =~ tr/_/_/s; |
55 | |
56 | # Trim a trailing _ |
57 | $name =~ s/_$//; |
58 | |
59 | return $name; |
60 | } |
61 | |
a2ba36ba |
62 | sub header_comment { |
63 | my $producer = shift || caller; |
64 | my $comment_char = shift; |
65 | my $now = scalar localtime; |
66 | |
67 | $comment_char = $DEFAULT_COMMENT |
68 | unless defined $comment_char; |
69 | |
70 | my $header_comment =<<"HEADER_COMMENT"; |
71 | ${comment_char} |
72 | ${comment_char}Created by $producer |
73 | ${comment_char}Created on $now |
74 | ${comment_char} |
75 | HEADER_COMMENT |
76 | |
77 | # Any additional stuff passed in |
78 | for my $additional_comment (@_) { |
79 | $header_comment .= "${comment_char}${additional_comment}\n"; |
80 | } |
81 | |
82 | return $header_comment; |
83 | } |
84 | |
e545d971 |
85 | sub parse_list_arg { |
86 | my $list = UNIVERSAL::isa( $_[0], 'ARRAY' ) ? shift : [ @_ ]; |
87 | |
51bb6fe0 |
88 | # |
89 | # This protects stringification of references. |
90 | # |
91 | if ( @$list && ref $list->[0] ) { |
92 | return $list; |
93 | } |
94 | # |
95 | # This processes string-like arguments. |
96 | # |
97 | else { |
ea93df61 |
98 | return [ |
51bb6fe0 |
99 | map { s/^\s+|\s+$//g; $_ } |
100 | map { split /,/ } |
101 | grep { defined && length } @$list |
102 | ]; |
103 | } |
118bb73f |
104 | } |
105 | |
f5405d47 |
106 | sub truncate_id_uniquely { |
107 | my ( $desired_name, $max_symbol_length ) = @_; |
108 | |
16fa91c0 |
109 | return $desired_name |
110 | unless defined $desired_name && length $desired_name > $max_symbol_length; |
f5405d47 |
111 | |
16fa91c0 |
112 | my $truncated_name = substr $desired_name, 0, |
11ad2df9 |
113 | $max_symbol_length - COLLISION_TAG_LENGTH - 1; |
f5405d47 |
114 | |
115 | # Hex isn't the most space-efficient, but it skirts around allowed |
116 | # charset issues |
117 | my $digest = sha1_hex($desired_name); |
11ad2df9 |
118 | my $collision_tag = substr $digest, 0, COLLISION_TAG_LENGTH; |
f5405d47 |
119 | |
120 | return $truncated_name |
121 | . '_' |
122 | . $collision_tag; |
123 | } |
124 | |
5d666b31 |
125 | |
5d666b31 |
126 | sub parse_mysql_version { |
127 | my ($v, $target) = @_; |
128 | |
129 | return undef unless $v; |
130 | |
131 | $target ||= 'perl'; |
132 | |
133 | my @vers; |
134 | |
ea93df61 |
135 | # X.Y.Z style |
5d666b31 |
136 | if ( $v =~ / ^ (\d+) \. (\d{1,3}) (?: \. (\d{1,3}) )? $ /x ) { |
137 | push @vers, $1, $2, $3; |
138 | } |
139 | |
ea93df61 |
140 | # XYYZZ (mysql) style |
5d666b31 |
141 | elsif ( $v =~ / ^ (\d) (\d{2}) (\d{2}) $ /x ) { |
142 | push @vers, $1, $2, $3; |
143 | } |
144 | |
ea93df61 |
145 | # XX.YYYZZZ (perl) style or simply X |
5d666b31 |
146 | elsif ( $v =~ / ^ (\d+) (?: \. (\d{3}) (\d{3}) )? $ /x ) { |
147 | push @vers, $1, $2, $3; |
148 | } |
149 | else { |
150 | #how do I croak sanely here? |
151 | die "Unparseable MySQL version '$v'"; |
152 | } |
153 | |
154 | if ($target eq 'perl') { |
155 | return sprintf ('%d.%03d%03d', map { $_ || 0 } (@vers) ); |
156 | } |
157 | elsif ($target eq 'mysql') { |
158 | return sprintf ('%d%02d%02d', map { $_ || 0 } (@vers) ); |
159 | } |
160 | else { |
161 | #how do I croak sanely here? |
162 | die "Unknown version target '$target'"; |
163 | } |
164 | } |
165 | |
7b4b17aa |
166 | sub parse_dbms_version { |
167 | my ($v, $target) = @_; |
168 | |
169 | return undef unless $v; |
170 | |
171 | my @vers; |
172 | |
ea93df61 |
173 | # X.Y.Z style |
7b4b17aa |
174 | if ( $v =~ / ^ (\d+) \. (\d{1,3}) (?: \. (\d{1,3}) )? $ /x ) { |
175 | push @vers, $1, $2, $3; |
176 | } |
177 | |
ea93df61 |
178 | # XX.YYYZZZ (perl) style or simply X |
7b4b17aa |
179 | elsif ( $v =~ / ^ (\d+) (?: \. (\d{3}) (\d{3}) )? $ /x ) { |
180 | push @vers, $1, $2, $3; |
181 | } |
182 | else { |
183 | #how do I croak sanely here? |
184 | die "Unparseable database server version '$v'"; |
185 | } |
186 | |
187 | if ($target eq 'perl') { |
188 | return sprintf ('%d.%03d%03d', map { $_ || 0 } (@vers) ); |
189 | } |
190 | elsif ($target eq 'native') { |
e0d18105 |
191 | return join '.' => grep defined, @vers; |
7b4b17aa |
192 | } |
193 | else { |
194 | #how do I croak sanely here? |
195 | die "Unknown version target '$target'"; |
196 | } |
197 | } |
5d666b31 |
198 | |
0eb3b94a |
199 | #my ($parsers_libdir, $checkout_dir); |
bdf60588 |
200 | sub ddl_parser_instance { |
0eb3b94a |
201 | |
bdf60588 |
202 | my $type = shift; |
203 | |
204 | # it may differ from our caller, even though currently this is not the case |
205 | eval "require SQL::Translator::Parser::$type" |
206 | or die "Unable to load grammar-spec container SQL::Translator::Parser::$type:\n$@"; |
207 | |
7e666ece |
208 | # handle DB2 in a special way, since the grammar source was lost :( |
209 | if ($type eq 'DB2') { |
210 | require SQL::Translator::Parser::DB2::Grammar; |
211 | return SQL::Translator::Parser::DB2::Grammar->new; |
212 | } |
213 | |
0eb3b94a |
214 | require Parse::RecDescent; |
215 | return Parse::RecDescent->new(do { |
216 | no strict 'refs'; |
217 | ${"SQL::Translator::Parser::${type}::GRAMMAR"} |
218 | || die "No \$SQL::Translator::Parser::${type}::GRAMMAR defined, unable to instantiate PRD parser\n" |
219 | }); |
220 | |
221 | # this is disabled until RT#74593 is resolved |
222 | =begin for general sadness |
223 | |
bdf60588 |
224 | unless ($parsers_libdir) { |
225 | |
226 | # are we in a checkout? |
227 | if ($checkout_dir = _find_co_root()) { |
228 | $parsers_libdir = File::Spec->catdir($checkout_dir, 'share', 'PrecompiledParsers'); |
229 | } |
230 | else { |
231 | require File::ShareDir; |
232 | $parsers_libdir = File::Spec->catdir( |
233 | File::ShareDir::dist_dir('SQL-Translator'), |
234 | 'PrecompiledParsers' |
235 | ); |
236 | } |
237 | |
238 | unshift @INC, $parsers_libdir; |
239 | } |
240 | |
241 | my $precompiled_mod = "Parse::RecDescent::DDL::SQLT::$type"; |
242 | |
243 | # FIXME FIXME FIXME |
244 | # Parse::RecDescent has horrible architecture where each precompiled parser |
245 | # instance shares global state with all its siblings |
246 | # What we do here is gross, but scarily efficient - the parser compilation |
247 | # is much much slower than an unload/reload cycle |
f2ab5843 |
248 | require Class::Unload; |
bdf60588 |
249 | Class::Unload->unload($precompiled_mod); |
250 | |
251 | # There is also a sub-namespace that P::RD uses, but simply unsetting |
252 | # $^W to stop redefine warnings seems to be enough |
253 | #Class::Unload->unload("Parse::RecDescent::$precompiled_mod"); |
254 | |
255 | eval "local \$^W; require $precompiled_mod" or do { |
256 | if ($checkout_dir) { |
257 | die "Unable to find precompiled grammar for $type - run Makefile.PL to generate it\n"; |
258 | } |
259 | else { |
260 | die "Unable to load precompiled grammar for $type... this is not supposed to happen if you are not in a checkout, please file a bugreport:\n$@" |
261 | } |
262 | }; |
263 | |
264 | my $grammar_spec_fn = $INC{"SQL/Translator/Parser/$type.pm"}; |
265 | my $precompiled_fn = $INC{"Parse/RecDescent/DDL/SQLT/$type.pm"}; |
266 | |
267 | if ( |
268 | (stat($grammar_spec_fn))[9] |
269 | > |
270 | (stat($precompiled_fn))[9] |
271 | ) { |
272 | die ( |
273 | "Grammar spec '$grammar_spec_fn' is newer than precompiled parser '$precompiled_fn'" |
274 | . ($checkout_dir |
275 | ? " - run Makefile.PL to regenerate stale versions\n" |
276 | : "... this is not supposed to happen if you are not in a checkout, please file a bugreport\n" |
277 | ) |
278 | ); |
279 | } |
280 | |
281 | return $precompiled_mod->new; |
0eb3b94a |
282 | =cut |
283 | |
bdf60588 |
284 | } |
285 | |
286 | # Try to determine the root of a checkout/untar if possible |
287 | # or return undef |
288 | sub _find_co_root { |
289 | |
290 | my @mod_parts = split /::/, (__PACKAGE__ . '.pm'); |
291 | my $rel_path = join ('/', @mod_parts); # %INC stores paths with / regardless of OS |
292 | |
293 | return undef unless ($INC{$rel_path}); |
294 | |
295 | # a bit convoluted, but what we do here essentially is: |
296 | # - get the file name of this particular module |
297 | # - do 'cd ..' as many times as necessary to get to lib/SQL/Translator/../../.. |
298 | |
299 | my $root = (File::Spec::Unix->splitpath($INC{$rel_path}))[1]; |
300 | for (1 .. @mod_parts) { |
301 | $root = File::Spec->catdir($root, File::Spec->updir); |
302 | } |
303 | |
304 | return ( -f File::Spec->catfile($root, 'Makefile.PL') ) |
305 | ? $root |
306 | : undef |
307 | ; |
308 | } |
309 | |
45287c81 |
310 | { |
311 | package SQL::Translator::Utils::Error; |
312 | |
313 | use overload |
314 | '""' => sub { ${$_[0]} }, |
315 | fallback => 1; |
316 | |
317 | sub new { |
318 | my ($class, $msg) = @_; |
319 | bless \$msg, $class; |
320 | } |
321 | } |
322 | |
323 | sub throw { |
324 | die SQL::Translator::Utils::Error->new($_[0]); |
325 | } |
326 | |
327 | sub ex2err { |
328 | my ($orig, $self, @args) = @_; |
329 | return try { |
330 | $self->$orig(@args); |
331 | } catch { |
332 | die $_ unless blessed($_) && $_->isa("SQL::Translator::Utils::Error"); |
333 | $self->error("$_"); |
334 | }; |
335 | } |
336 | |
1a24938d |
337 | 1; |
338 | |
118bb73f |
339 | =pod |
1a24938d |
340 | |
341 | =head1 NAME |
342 | |
343 | SQL::Translator::Utils - SQL::Translator Utility functions |
344 | |
345 | =head1 SYNOPSIS |
346 | |
347 | use SQL::Translator::Utils qw(debug); |
348 | debug("PKG: Bad things happened"); |
349 | |
350 | =head1 DESCSIPTION |
351 | |
352 | C<SQL::Translator::Utils> contains utility functions designed to be |
353 | used from the other modules within the C<SQL::Translator> modules. |
354 | |
a2ba36ba |
355 | Nothing is exported by default. |
1a24938d |
356 | |
a2ba36ba |
357 | =head1 EXPORTED FUNCTIONS AND CONSTANTS |
1a24938d |
358 | |
359 | =head2 debug |
360 | |
361 | C<debug> takes 0 or more messages, which will be sent to STDERR using |
362 | C<warn>. Occurances of the strings I<PKG>, I<SUB>, and I<LINE> |
363 | will be replaced by the calling package, subroutine, and line number, |
e545d971 |
364 | respectively, as reported by C<caller(1)>. |
1a24938d |
365 | |
366 | For example, from within C<foo> in F<SQL/Translator.pm>, at line 666: |
367 | |
368 | debug("PKG: Error reading file at SUB/LINE"); |
369 | |
370 | Will warn |
371 | |
372 | [SQL::Translator: Error reading file at foo/666] |
373 | |
374 | The entire message is enclosed within C<[> and C<]> for visual clarity |
375 | when STDERR is intermixed with STDOUT. |
93d12e9c |
376 | |
377 | =head2 normalize_name |
378 | |
379 | C<normalize_name> takes a string and ensures that it is suitable for |
380 | use as an identifier. This means: ensure that it starts with a letter |
381 | or underscore, and that the rest of the string consists of only |
382 | letters, numbers, and underscores. A string that begins with |
383 | something other than [a-zA-Z] will be prefixer with an underscore, and |
384 | all other characters in the string will be replaced with underscores. |
385 | Finally, a trailing underscore will be removed, because that's ugly. |
386 | |
387 | normalize_name("Hello, world"); |
388 | |
389 | Produces: |
390 | |
391 | Hello_world |
392 | |
393 | A more useful example, from the C<SQL::Translator::Parser::Excel> test |
394 | suite: |
395 | |
396 | normalize_name("silly field (with random characters)"); |
397 | |
398 | returns: |
399 | |
400 | silly_field_with_random_characters |
401 | |
a2ba36ba |
402 | =head2 header_comment |
403 | |
404 | Create the header comment. Takes 1 mandatory argument (the producer |
405 | classname), an optional comment character (defaults to $DEFAULT_COMMENT), |
406 | and 0 or more additional comments, which will be appended to the header, |
407 | prefixed with the comment character. If additional comments are provided, |
408 | then a comment string must be provided ($DEFAULT_COMMENT is exported for |
409 | this use). For example, this: |
410 | |
411 | package My::Producer; |
412 | |
413 | use SQL::Translator::Utils qw(header_comment $DEFAULT_COMMENT); |
414 | |
415 | print header_comment(__PACKAGE__, |
e545d971 |
416 | $DEFAULT_COMMENT, |
a2ba36ba |
417 | "Hi mom!"); |
418 | |
419 | produces: |
420 | |
e545d971 |
421 | -- |
a2ba36ba |
422 | -- Created by My::Prodcuer |
423 | -- Created on Fri Apr 25 06:56:02 2003 |
e545d971 |
424 | -- |
a2ba36ba |
425 | -- Hi mom! |
e545d971 |
426 | -- |
a2ba36ba |
427 | |
428 | Note the gratuitous spacing. |
429 | |
118bb73f |
430 | =head2 parse_list_arg |
431 | |
432 | Takes a string, list or arrayref (all of which could contain |
433 | comma-separated values) and returns an array reference of the values. |
434 | All of the following will return equivalent values: |
435 | |
436 | parse_list_arg('id'); |
437 | parse_list_arg('id', 'name'); |
438 | parse_list_arg( 'id, name' ); |
439 | parse_list_arg( [ 'id', 'name' ] ); |
440 | parse_list_arg( qw[ id name ] ); |
441 | |
f5405d47 |
442 | =head2 truncate_id_uniquely |
443 | |
444 | Takes a string ($desired_name) and int ($max_symbol_length). Truncates |
445 | $desired_name to $max_symbol_length by including part of the hash of |
446 | the full name at the end of the truncated name, giving a high |
447 | probability that the symbol will be unique. For example, |
448 | |
449 | truncate_id_uniquely( 'a' x 100, 64 ) |
450 | truncate_id_uniquely( 'a' x 99 . 'b', 64 ); |
451 | truncate_id_uniquely( 'a' x 99, 64 ) |
452 | |
453 | Will give three different results; specifically: |
454 | |
455 | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_7f900025 |
456 | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_6191e39a |
457 | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_8cd96af2 |
458 | |
a2ba36ba |
459 | =head2 $DEFAULT_COMMENT |
460 | |
461 | This is the default comment string, '-- ' by default. Useful for |
462 | C<header_comment>. |
463 | |
5d666b31 |
464 | =head2 parse_mysql_version |
465 | |
ea93df61 |
466 | Used by both L<Parser::MySQL|SQL::Translator::Parser::MySQL> and |
5d666b31 |
467 | L<Producer::MySQL|SQL::Translator::Producer::MySQL> in order to provide a |
468 | consistent format for both C<< parser_args->{mysql_parser_version} >> and |
469 | C<< producer_args->{mysql_version} >> respectively. Takes any of the following |
470 | version specifications: |
471 | |
472 | 5.0.3 |
473 | 4.1 |
474 | 3.23.2 |
475 | 5 |
476 | 5.001005 (perl style) |
477 | 30201 (mysql style) |
478 | |
282bf498 |
479 | =head2 parse_dbms_version |
480 | |
481 | Takes a version string (X.Y.Z) or perl style (XX.YYYZZZ) and a target ('perl' |
482 | or 'native') transforms the string to the given target style. |
483 | to |
484 | |
118bb73f |
485 | =head1 AUTHORS |
486 | |
487 | Darren Chamberlain E<lt>darren@cpan.orgE<gt>, |
11ad2df9 |
488 | Ken Y. Clark E<lt>kclark@cpan.orgE<gt>. |
118bb73f |
489 | |
490 | =cut |