1 package SQL::Translator::Utils;
5 use Digest::SHA qw( sha1_hex );
10 our $DEFAULT_COMMENT = '-- ';
12 use base qw(Exporter);
14 debug normalize_name header_comment parse_list_arg truncate_id_uniquely
15 $DEFAULT_COMMENT parse_mysql_version parse_dbms_version
18 use constant COLLISION_TAG_LENGTH => 8;
21 my ($pkg, $file, $line, $sub) = caller(0);
24 return unless ${"$pkg\::DEBUG"};
32 $x =~ s/\bPKG\b/$pkg/g;
33 $x =~ s/\bLINE\b/$line/g;
34 $x =~ s/\bSUB\b/$sub/g;
35 #warn '[' . $x . "]\n";
36 print STDERR '[' . $x . "]\n";
41 my $name = shift or return '';
43 # The name can only begin with a-zA-Z_; if there's anything
45 $name =~ s/^([^a-zA-Z_])/_$1/;
47 # anything other than a-zA-Z0-9_ in the non-first position
48 # needs to be turned into _
49 $name =~ tr/[a-zA-Z0-9_]/_/c;
51 # All duplicated _ need to be squashed into one.
61 my $producer = shift || caller;
62 my $comment_char = shift;
63 my $now = scalar localtime;
65 $comment_char = $DEFAULT_COMMENT
66 unless defined $comment_char;
68 my $header_comment =<<"HEADER_COMMENT";
70 ${comment_char}Created by $producer
71 ${comment_char}Created on $now
75 # Any additional stuff passed in
76 for my $additional_comment (@_) {
77 $header_comment .= "${comment_char}${additional_comment}\n";
80 return $header_comment;
84 my $list = UNIVERSAL::isa( $_[0], 'ARRAY' ) ? shift : [ @_ ];
87 # This protects stringification of references.
89 if ( @$list && ref $list->[0] ) {
93 # This processes string-like arguments.
97 map { s/^\s+|\s+$//g; $_ }
99 grep { defined && length } @$list
104 sub truncate_id_uniquely {
105 my ( $desired_name, $max_symbol_length ) = @_;
108 unless defined $desired_name && length $desired_name > $max_symbol_length;
110 my $truncated_name = substr $desired_name, 0,
111 $max_symbol_length - COLLISION_TAG_LENGTH - 1;
113 # Hex isn't the most space-efficient, but it skirts around allowed
115 my $digest = sha1_hex($desired_name);
116 my $collision_tag = substr $digest, 0, COLLISION_TAG_LENGTH;
118 return $truncated_name
124 sub parse_mysql_version {
125 my ($v, $target) = @_;
127 return undef unless $v;
134 if ( $v =~ / ^ (\d+) \. (\d{1,3}) (?: \. (\d{1,3}) )? $ /x ) {
135 push @vers, $1, $2, $3;
138 # XYYZZ (mysql) style
139 elsif ( $v =~ / ^ (\d) (\d{2}) (\d{2}) $ /x ) {
140 push @vers, $1, $2, $3;
143 # XX.YYYZZZ (perl) style or simply X
144 elsif ( $v =~ / ^ (\d+) (?: \. (\d{3}) (\d{3}) )? $ /x ) {
145 push @vers, $1, $2, $3;
148 #how do I croak sanely here?
149 die "Unparseable MySQL version '$v'";
152 if ($target eq 'perl') {
153 return sprintf ('%d.%03d%03d', map { $_ || 0 } (@vers) );
155 elsif ($target eq 'mysql') {
156 return sprintf ('%d%02d%02d', map { $_ || 0 } (@vers) );
159 #how do I croak sanely here?
160 die "Unknown version target '$target'";
164 sub parse_dbms_version {
165 my ($v, $target) = @_;
167 return undef unless $v;
172 if ( $v =~ / ^ (\d+) \. (\d{1,3}) (?: \. (\d{1,3}) )? $ /x ) {
173 push @vers, $1, $2, $3;
176 # XX.YYYZZZ (perl) style or simply X
177 elsif ( $v =~ / ^ (\d+) (?: \. (\d{3}) (\d{3}) )? $ /x ) {
178 push @vers, $1, $2, $3;
181 #how do I croak sanely here?
182 die "Unparseable database server version '$v'";
185 if ($target eq 'perl') {
186 return sprintf ('%d.%03d%03d', map { $_ || 0 } (@vers) );
188 elsif ($target eq 'native') {
189 return join '.' => grep defined, @vers;
192 #how do I croak sanely here?
193 die "Unknown version target '$target'";
197 my ($parsers_libdir, $checkout_dir);
198 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 unless ($parsers_libdir) {
207 # are we in a checkout?
208 if ($checkout_dir = _find_co_root()) {
209 $parsers_libdir = File::Spec->catdir($checkout_dir, 'share', 'PrecompiledParsers');
212 require File::ShareDir;
213 $parsers_libdir = File::Spec->catdir(
214 File::ShareDir::dist_dir('SQL-Translator'),
219 unshift @INC, $parsers_libdir;
222 my $precompiled_mod = "Parse::RecDescent::DDL::SQLT::$type";
225 # Parse::RecDescent has horrible architecture where each precompiled parser
226 # instance shares global state with all its siblings
227 # What we do here is gross, but scarily efficient - the parser compilation
228 # is much much slower than an unload/reload cycle
229 Class::Unload->unload($precompiled_mod);
231 # There is also a sub-namespace that P::RD uses, but simply unsetting
232 # $^W to stop redefine warnings seems to be enough
233 #Class::Unload->unload("Parse::RecDescent::$precompiled_mod");
235 eval "local \$^W; require $precompiled_mod" or do {
237 die "Unable to find precompiled grammar for $type - run Makefile.PL to generate it\n";
240 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$@"
244 my $grammar_spec_fn = $INC{"SQL/Translator/Parser/$type.pm"};
245 my $precompiled_fn = $INC{"Parse/RecDescent/DDL/SQLT/$type.pm"};
248 (stat($grammar_spec_fn))[9]
250 (stat($precompiled_fn))[9]
253 "Grammar spec '$grammar_spec_fn' is newer than precompiled parser '$precompiled_fn'"
255 ? " - run Makefile.PL to regenerate stale versions\n"
256 : "... this is not supposed to happen if you are not in a checkout, please file a bugreport\n"
261 return $precompiled_mod->new;
264 # Try to determine the root of a checkout/untar if possible
268 my @mod_parts = split /::/, (__PACKAGE__ . '.pm');
269 my $rel_path = join ('/', @mod_parts); # %INC stores paths with / regardless of OS
271 return undef unless ($INC{$rel_path});
273 # a bit convoluted, but what we do here essentially is:
274 # - get the file name of this particular module
275 # - do 'cd ..' as many times as necessary to get to lib/SQL/Translator/../../..
277 my $root = (File::Spec::Unix->splitpath($INC{$rel_path}))[1];
278 for (1 .. @mod_parts) {
279 $root = File::Spec->catdir($root, File::Spec->updir);
282 return ( -f File::Spec->catfile($root, 'Makefile.PL') )
294 SQL::Translator::Utils - SQL::Translator Utility functions
298 use SQL::Translator::Utils qw(debug);
299 debug("PKG: Bad things happened");
303 C<SQL::Translator::Utils> contains utility functions designed to be
304 used from the other modules within the C<SQL::Translator> modules.
306 Nothing is exported by default.
308 =head1 EXPORTED FUNCTIONS AND CONSTANTS
312 C<debug> takes 0 or more messages, which will be sent to STDERR using
313 C<warn>. Occurances of the strings I<PKG>, I<SUB>, and I<LINE>
314 will be replaced by the calling package, subroutine, and line number,
315 respectively, as reported by C<caller(1)>.
317 For example, from within C<foo> in F<SQL/Translator.pm>, at line 666:
319 debug("PKG: Error reading file at SUB/LINE");
323 [SQL::Translator: Error reading file at foo/666]
325 The entire message is enclosed within C<[> and C<]> for visual clarity
326 when STDERR is intermixed with STDOUT.
328 =head2 normalize_name
330 C<normalize_name> takes a string and ensures that it is suitable for
331 use as an identifier. This means: ensure that it starts with a letter
332 or underscore, and that the rest of the string consists of only
333 letters, numbers, and underscores. A string that begins with
334 something other than [a-zA-Z] will be prefixer with an underscore, and
335 all other characters in the string will be replaced with underscores.
336 Finally, a trailing underscore will be removed, because that's ugly.
338 normalize_name("Hello, world");
344 A more useful example, from the C<SQL::Translator::Parser::Excel> test
347 normalize_name("silly field (with random characters)");
351 silly_field_with_random_characters
353 =head2 header_comment
355 Create the header comment. Takes 1 mandatory argument (the producer
356 classname), an optional comment character (defaults to $DEFAULT_COMMENT),
357 and 0 or more additional comments, which will be appended to the header,
358 prefixed with the comment character. If additional comments are provided,
359 then a comment string must be provided ($DEFAULT_COMMENT is exported for
360 this use). For example, this:
362 package My::Producer;
364 use SQL::Translator::Utils qw(header_comment $DEFAULT_COMMENT);
366 print header_comment(__PACKAGE__,
373 -- Created by My::Prodcuer
374 -- Created on Fri Apr 25 06:56:02 2003
379 Note the gratuitous spacing.
381 =head2 parse_list_arg
383 Takes a string, list or arrayref (all of which could contain
384 comma-separated values) and returns an array reference of the values.
385 All of the following will return equivalent values:
387 parse_list_arg('id');
388 parse_list_arg('id', 'name');
389 parse_list_arg( 'id, name' );
390 parse_list_arg( [ 'id', 'name' ] );
391 parse_list_arg( qw[ id name ] );
393 =head2 truncate_id_uniquely
395 Takes a string ($desired_name) and int ($max_symbol_length). Truncates
396 $desired_name to $max_symbol_length by including part of the hash of
397 the full name at the end of the truncated name, giving a high
398 probability that the symbol will be unique. For example,
400 truncate_id_uniquely( 'a' x 100, 64 )
401 truncate_id_uniquely( 'a' x 99 . 'b', 64 );
402 truncate_id_uniquely( 'a' x 99, 64 )
404 Will give three different results; specifically:
406 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_7f900025
407 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_6191e39a
408 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_8cd96af2
410 =head2 $DEFAULT_COMMENT
412 This is the default comment string, '-- ' by default. Useful for
415 =head2 parse_mysql_version
417 Used by both L<Parser::MySQL|SQL::Translator::Parser::MySQL> and
418 L<Producer::MySQL|SQL::Translator::Producer::MySQL> in order to provide a
419 consistent format for both C<< parser_args->{mysql_parser_version} >> and
420 C<< producer_args->{mysql_version} >> respectively. Takes any of the following
421 version specifications:
427 5.001005 (perl style)
430 =head2 parse_dbms_version
432 Takes a version string (X.Y.Z) or perl style (XX.YYYZZZ) and a target ('perl'
433 or 'native') transforms the string to the given target style.
438 Darren Chamberlain E<lt>darren@cpan.orgE<gt>,
439 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.