1 package SQL::Translator::Utils;
5 use Digest::SHA qw( sha1_hex );
9 our $DEFAULT_COMMENT = '-- ';
11 use base qw(Exporter);
13 debug normalize_name header_comment parse_list_arg truncate_id_uniquely
14 $DEFAULT_COMMENT parse_mysql_version parse_dbms_version
17 use constant COLLISION_TAG_LENGTH => 8;
20 my ($pkg, $file, $line, $sub) = caller(0);
23 return unless ${"$pkg\::DEBUG"};
31 $x =~ s/\bPKG\b/$pkg/g;
32 $x =~ s/\bLINE\b/$line/g;
33 $x =~ s/\bSUB\b/$sub/g;
34 #warn '[' . $x . "]\n";
35 print STDERR '[' . $x . "]\n";
40 my $name = shift or return '';
42 # The name can only begin with a-zA-Z_; if there's anything
44 $name =~ s/^([^a-zA-Z_])/_$1/;
46 # anything other than a-zA-Z0-9_ in the non-first position
47 # needs to be turned into _
48 $name =~ tr/[a-zA-Z0-9_]/_/c;
50 # All duplicated _ need to be squashed into one.
60 my $producer = shift || caller;
61 my $comment_char = shift;
62 my $now = scalar localtime;
64 $comment_char = $DEFAULT_COMMENT
65 unless defined $comment_char;
67 my $header_comment =<<"HEADER_COMMENT";
69 ${comment_char}Created by $producer
70 ${comment_char}Created on $now
74 # Any additional stuff passed in
75 for my $additional_comment (@_) {
76 $header_comment .= "${comment_char}${additional_comment}\n";
79 return $header_comment;
83 my $list = UNIVERSAL::isa( $_[0], 'ARRAY' ) ? shift : [ @_ ];
86 # This protects stringification of references.
88 if ( @$list && ref $list->[0] ) {
92 # This processes string-like arguments.
96 map { s/^\s+|\s+$//g; $_ }
98 grep { defined && length } @$list
103 sub truncate_id_uniquely {
104 my ( $desired_name, $max_symbol_length ) = @_;
107 unless defined $desired_name && length $desired_name > $max_symbol_length;
109 my $truncated_name = substr $desired_name, 0,
110 $max_symbol_length - COLLISION_TAG_LENGTH - 1;
112 # Hex isn't the most space-efficient, but it skirts around allowed
114 my $digest = sha1_hex($desired_name);
115 my $collision_tag = substr $digest, 0, COLLISION_TAG_LENGTH;
117 return $truncated_name
123 sub parse_mysql_version {
124 my ($v, $target) = @_;
126 return undef unless $v;
133 if ( $v =~ / ^ (\d+) \. (\d{1,3}) (?: \. (\d{1,3}) )? $ /x ) {
134 push @vers, $1, $2, $3;
137 # XYYZZ (mysql) style
138 elsif ( $v =~ / ^ (\d) (\d{2}) (\d{2}) $ /x ) {
139 push @vers, $1, $2, $3;
142 # XX.YYYZZZ (perl) style or simply X
143 elsif ( $v =~ / ^ (\d+) (?: \. (\d{3}) (\d{3}) )? $ /x ) {
144 push @vers, $1, $2, $3;
147 #how do I croak sanely here?
148 die "Unparseable MySQL version '$v'";
151 if ($target eq 'perl') {
152 return sprintf ('%d.%03d%03d', map { $_ || 0 } (@vers) );
154 elsif ($target eq 'mysql') {
155 return sprintf ('%d%02d%02d', map { $_ || 0 } (@vers) );
158 #how do I croak sanely here?
159 die "Unknown version target '$target'";
163 sub parse_dbms_version {
164 my ($v, $target) = @_;
166 return undef unless $v;
171 if ( $v =~ / ^ (\d+) \. (\d{1,3}) (?: \. (\d{1,3}) )? $ /x ) {
172 push @vers, $1, $2, $3;
175 # XX.YYYZZZ (perl) style or simply X
176 elsif ( $v =~ / ^ (\d+) (?: \. (\d{3}) (\d{3}) )? $ /x ) {
177 push @vers, $1, $2, $3;
180 #how do I croak sanely here?
181 die "Unparseable database server version '$v'";
184 if ($target eq 'perl') {
185 return sprintf ('%d.%03d%03d', map { $_ || 0 } (@vers) );
187 elsif ($target eq 'native') {
188 return join '.' => grep defined, @vers;
191 #how do I croak sanely here?
192 die "Unknown version target '$target'";
196 #my ($parsers_libdir, $checkout_dir);
197 sub ddl_parser_instance {
201 # it may differ from our caller, even though currently this is not the case
202 eval "require SQL::Translator::Parser::$type"
203 or die "Unable to load grammar-spec container SQL::Translator::Parser::$type:\n$@";
205 # handle DB2 in a special way, since the grammar source was lost :(
206 if ($type eq 'DB2') {
207 require SQL::Translator::Parser::DB2::Grammar;
208 return SQL::Translator::Parser::DB2::Grammar->new;
211 require Parse::RecDescent;
212 return Parse::RecDescent->new(do {
214 ${"SQL::Translator::Parser::${type}::GRAMMAR"}
215 || die "No \$SQL::Translator::Parser::${type}::GRAMMAR defined, unable to instantiate PRD parser\n"
218 # this is disabled until RT#74593 is resolved
219 =begin for general sadness
221 unless ($parsers_libdir) {
223 # are we in a checkout?
224 if ($checkout_dir = _find_co_root()) {
225 $parsers_libdir = File::Spec->catdir($checkout_dir, 'share', 'PrecompiledParsers');
228 require File::ShareDir;
229 $parsers_libdir = File::Spec->catdir(
230 File::ShareDir::dist_dir('SQL-Translator'),
235 unshift @INC, $parsers_libdir;
238 my $precompiled_mod = "Parse::RecDescent::DDL::SQLT::$type";
241 # Parse::RecDescent has horrible architecture where each precompiled parser
242 # instance shares global state with all its siblings
243 # What we do here is gross, but scarily efficient - the parser compilation
244 # is much much slower than an unload/reload cycle
245 require Class::Unload;
246 Class::Unload->unload($precompiled_mod);
248 # There is also a sub-namespace that P::RD uses, but simply unsetting
249 # $^W to stop redefine warnings seems to be enough
250 #Class::Unload->unload("Parse::RecDescent::$precompiled_mod");
252 eval "local \$^W; require $precompiled_mod" or do {
254 die "Unable to find precompiled grammar for $type - run Makefile.PL to generate it\n";
257 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 my $grammar_spec_fn = $INC{"SQL/Translator/Parser/$type.pm"};
262 my $precompiled_fn = $INC{"Parse/RecDescent/DDL/SQLT/$type.pm"};
265 (stat($grammar_spec_fn))[9]
267 (stat($precompiled_fn))[9]
270 "Grammar spec '$grammar_spec_fn' is newer than precompiled parser '$precompiled_fn'"
272 ? " - run Makefile.PL to regenerate stale versions\n"
273 : "... this is not supposed to happen if you are not in a checkout, please file a bugreport\n"
278 return $precompiled_mod->new;
283 # Try to determine the root of a checkout/untar if possible
287 my @mod_parts = split /::/, (__PACKAGE__ . '.pm');
288 my $rel_path = join ('/', @mod_parts); # %INC stores paths with / regardless of OS
290 return undef unless ($INC{$rel_path});
292 # a bit convoluted, but what we do here essentially is:
293 # - get the file name of this particular module
294 # - do 'cd ..' as many times as necessary to get to lib/SQL/Translator/../../..
296 my $root = (File::Spec::Unix->splitpath($INC{$rel_path}))[1];
297 for (1 .. @mod_parts) {
298 $root = File::Spec->catdir($root, File::Spec->updir);
301 return ( -f File::Spec->catfile($root, 'Makefile.PL') )
313 SQL::Translator::Utils - SQL::Translator Utility functions
317 use SQL::Translator::Utils qw(debug);
318 debug("PKG: Bad things happened");
322 C<SQL::Translator::Utils> contains utility functions designed to be
323 used from the other modules within the C<SQL::Translator> modules.
325 Nothing is exported by default.
327 =head1 EXPORTED FUNCTIONS AND CONSTANTS
331 C<debug> takes 0 or more messages, which will be sent to STDERR using
332 C<warn>. Occurances of the strings I<PKG>, I<SUB>, and I<LINE>
333 will be replaced by the calling package, subroutine, and line number,
334 respectively, as reported by C<caller(1)>.
336 For example, from within C<foo> in F<SQL/Translator.pm>, at line 666:
338 debug("PKG: Error reading file at SUB/LINE");
342 [SQL::Translator: Error reading file at foo/666]
344 The entire message is enclosed within C<[> and C<]> for visual clarity
345 when STDERR is intermixed with STDOUT.
347 =head2 normalize_name
349 C<normalize_name> takes a string and ensures that it is suitable for
350 use as an identifier. This means: ensure that it starts with a letter
351 or underscore, and that the rest of the string consists of only
352 letters, numbers, and underscores. A string that begins with
353 something other than [a-zA-Z] will be prefixer with an underscore, and
354 all other characters in the string will be replaced with underscores.
355 Finally, a trailing underscore will be removed, because that's ugly.
357 normalize_name("Hello, world");
363 A more useful example, from the C<SQL::Translator::Parser::Excel> test
366 normalize_name("silly field (with random characters)");
370 silly_field_with_random_characters
372 =head2 header_comment
374 Create the header comment. Takes 1 mandatory argument (the producer
375 classname), an optional comment character (defaults to $DEFAULT_COMMENT),
376 and 0 or more additional comments, which will be appended to the header,
377 prefixed with the comment character. If additional comments are provided,
378 then a comment string must be provided ($DEFAULT_COMMENT is exported for
379 this use). For example, this:
381 package My::Producer;
383 use SQL::Translator::Utils qw(header_comment $DEFAULT_COMMENT);
385 print header_comment(__PACKAGE__,
392 -- Created by My::Prodcuer
393 -- Created on Fri Apr 25 06:56:02 2003
398 Note the gratuitous spacing.
400 =head2 parse_list_arg
402 Takes a string, list or arrayref (all of which could contain
403 comma-separated values) and returns an array reference of the values.
404 All of the following will return equivalent values:
406 parse_list_arg('id');
407 parse_list_arg('id', 'name');
408 parse_list_arg( 'id, name' );
409 parse_list_arg( [ 'id', 'name' ] );
410 parse_list_arg( qw[ id name ] );
412 =head2 truncate_id_uniquely
414 Takes a string ($desired_name) and int ($max_symbol_length). Truncates
415 $desired_name to $max_symbol_length by including part of the hash of
416 the full name at the end of the truncated name, giving a high
417 probability that the symbol will be unique. For example,
419 truncate_id_uniquely( 'a' x 100, 64 )
420 truncate_id_uniquely( 'a' x 99 . 'b', 64 );
421 truncate_id_uniquely( 'a' x 99, 64 )
423 Will give three different results; specifically:
425 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_7f900025
426 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_6191e39a
427 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_8cd96af2
429 =head2 $DEFAULT_COMMENT
431 This is the default comment string, '-- ' by default. Useful for
434 =head2 parse_mysql_version
436 Used by both L<Parser::MySQL|SQL::Translator::Parser::MySQL> and
437 L<Producer::MySQL|SQL::Translator::Producer::MySQL> in order to provide a
438 consistent format for both C<< parser_args->{mysql_parser_version} >> and
439 C<< producer_args->{mysql_version} >> respectively. Takes any of the following
440 version specifications:
446 5.001005 (perl style)
449 =head2 parse_dbms_version
451 Takes a version string (X.Y.Z) or perl style (XX.YYYZZZ) and a target ('perl'
452 or 'native') transforms the string to the given target style.
457 Darren Chamberlain E<lt>darren@cpan.orgE<gt>,
458 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.