1 package SQL::Translator::Utils;
3 # ----------------------------------------------------------------------
4 # Copyright (C) 2002-2009 SQLFairy Authors
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License as
8 # published by the Free Software Foundation; version 2.
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 # -------------------------------------------------------------------
22 use base qw(Exporter);
23 use vars qw($VERSION $DEFAULT_COMMENT @EXPORT_OK);
24 use Digest::SHA1 qw( sha1_hex );
28 $DEFAULT_COMMENT = '-- ';
30 debug normalize_name header_comment parse_list_arg truncate_id_uniquely
31 $DEFAULT_COMMENT parse_mysql_version parse_dbms_version
33 use constant COLLISION_TAG_LENGTH => 8;
35 # ----------------------------------------------------------------------
38 # Will send debugging messages to STDERR, if the caller's $DEBUG global
41 # This debug() function has a neat feature: Occurances of the strings
42 # PKG, LINE, and SUB in each message will be replaced with elements
45 # debug("PKG: Bad things happened on line LINE!");
49 # [SQL::Translator: Bad things happened on line 643]
51 # If called from Translator.pm, on line 643.
52 # ----------------------------------------------------------------------
54 my ($pkg, $file, $line, $sub) = caller(0);
57 return unless ${"$pkg\::DEBUG"};
65 $x =~ s/\bPKG\b/$pkg/g;
66 $x =~ s/\bLINE\b/$line/g;
67 $x =~ s/\bSUB\b/$sub/g;
68 #warn '[' . $x . "]\n";
69 print STDERR '[' . $x . "]\n";
73 # ----------------------------------------------------------------------
75 my $name = shift or return '';
77 # The name can only begin with a-zA-Z_; if there's anything
79 $name =~ s/^([^a-zA-Z_])/_$1/;
81 # anything other than a-zA-Z0-9_ in the non-first position
82 # needs to be turned into _
83 $name =~ tr/[a-zA-Z0-9_]/_/c;
85 # All duplicated _ need to be squashed into one.
94 # ----------------------------------------------------------------------
96 my $producer = shift || caller;
97 my $comment_char = shift;
98 my $now = scalar localtime;
100 $comment_char = $DEFAULT_COMMENT
101 unless defined $comment_char;
103 my $header_comment =<<"HEADER_COMMENT";
105 ${comment_char}Created by $producer
106 ${comment_char}Created on $now
110 # Any additional stuff passed in
111 for my $additional_comment (@_) {
112 $header_comment .= "${comment_char}${additional_comment}\n";
115 return $header_comment;
118 # ----------------------------------------------------------------------
121 # Meant to accept a list, an array reference, or a string of
122 # comma-separated values. Retuns an array reference of the
123 # arguments. Modified to also handle a list of references.
124 # ----------------------------------------------------------------------
126 my $list = UNIVERSAL::isa( $_[0], 'ARRAY' ) ? shift : [ @_ ];
129 # This protects stringification of references.
131 if ( @$list && ref $list->[0] ) {
135 # This processes string-like arguments.
139 map { s/^\s+|\s+$//g; $_ }
141 grep { defined && length } @$list
146 # ----------------------------------------------------------------------
147 # truncate_id_uniquely( $desired_name, $max_symbol_length )
149 # Truncates the name $desired_name to the $max_symbol_length by
150 # including part of the hash of the full name at the end of the
151 # truncated name, giving a high probability that the symbol will be
153 # ----------------------------------------------------------------------
154 sub truncate_id_uniquely {
155 my ( $desired_name, $max_symbol_length ) = @_;
158 unless defined $desired_name && length $desired_name > $max_symbol_length;
160 my $truncated_name = substr $desired_name, 0,
161 $max_symbol_length - COLLISION_TAG_LENGTH - 1;
163 # Hex isn't the most space-efficient, but it skirts around allowed
165 my $digest = sha1_hex($desired_name);
166 my $collision_tag = substr $digest, 0, COLLISION_TAG_LENGTH;
168 return $truncated_name
174 #---------------------------------------------------------------------
175 # parse_mysql_version ( $version_string, $result_target)
177 # Attempts to parse an arbitrary string as a mysql version number.
178 # Returns either a floating point perl style string, or a mysql style
179 # 5 digit string, depending on the supplied $result_target
180 #---------------------------------------------------------------------
181 sub parse_mysql_version {
182 my ($v, $target) = @_;
184 return undef unless $v;
191 if ( $v =~ / ^ (\d+) \. (\d{1,3}) (?: \. (\d{1,3}) )? $ /x ) {
192 push @vers, $1, $2, $3;
195 # XYYZZ (mysql) style
196 elsif ( $v =~ / ^ (\d) (\d{2}) (\d{2}) $ /x ) {
197 push @vers, $1, $2, $3;
200 # XX.YYYZZZ (perl) style or simply X
201 elsif ( $v =~ / ^ (\d+) (?: \. (\d{3}) (\d{3}) )? $ /x ) {
202 push @vers, $1, $2, $3;
205 #how do I croak sanely here?
206 die "Unparseable MySQL version '$v'";
209 if ($target eq 'perl') {
210 return sprintf ('%d.%03d%03d', map { $_ || 0 } (@vers) );
212 elsif ($target eq 'mysql') {
213 return sprintf ('%d%02d%02d', map { $_ || 0 } (@vers) );
216 #how do I croak sanely here?
217 die "Unknown version target '$target'";
221 #---------------------------------------------------------------------
222 # parse_dbms_version ( $version_string, $target )
224 # Attempts to parse either a native or perl-style version string into
225 # a version number format as specified by $target, which can be either
226 # 'perl' for a perl-style version number, or 'native' for an X.X.X
227 # style version number.
228 #---------------------------------------------------------------------
229 sub parse_dbms_version {
230 my ($v, $target) = @_;
232 return undef unless $v;
237 if ( $v =~ / ^ (\d+) \. (\d{1,3}) (?: \. (\d{1,3}) )? $ /x ) {
238 push @vers, $1, $2, $3;
241 # XX.YYYZZZ (perl) style or simply X
242 elsif ( $v =~ / ^ (\d+) (?: \. (\d{3}) (\d{3}) )? $ /x ) {
243 push @vers, $1, $2, $3;
246 #how do I croak sanely here?
247 die "Unparseable database server version '$v'";
250 if ($target eq 'perl') {
251 return sprintf ('%d.%03d%03d', map { $_ || 0 } (@vers) );
253 elsif ($target eq 'native') {
254 return join '.' => grep defined, @vers;
257 #how do I croak sanely here?
258 die "Unknown version target '$target'";
264 # ----------------------------------------------------------------------
270 SQL::Translator::Utils - SQL::Translator Utility functions
274 use SQL::Translator::Utils qw(debug);
275 debug("PKG: Bad things happened");
279 C<SQL::Translator::Utils> contains utility functions designed to be
280 used from the other modules within the C<SQL::Translator> modules.
282 Nothing is exported by default.
284 =head1 EXPORTED FUNCTIONS AND CONSTANTS
288 C<debug> takes 0 or more messages, which will be sent to STDERR using
289 C<warn>. Occurances of the strings I<PKG>, I<SUB>, and I<LINE>
290 will be replaced by the calling package, subroutine, and line number,
291 respectively, as reported by C<caller(1)>.
293 For example, from within C<foo> in F<SQL/Translator.pm>, at line 666:
295 debug("PKG: Error reading file at SUB/LINE");
299 [SQL::Translator: Error reading file at foo/666]
301 The entire message is enclosed within C<[> and C<]> for visual clarity
302 when STDERR is intermixed with STDOUT.
304 =head2 normalize_name
306 C<normalize_name> takes a string and ensures that it is suitable for
307 use as an identifier. This means: ensure that it starts with a letter
308 or underscore, and that the rest of the string consists of only
309 letters, numbers, and underscores. A string that begins with
310 something other than [a-zA-Z] will be prefixer with an underscore, and
311 all other characters in the string will be replaced with underscores.
312 Finally, a trailing underscore will be removed, because that's ugly.
314 normalize_name("Hello, world");
320 A more useful example, from the C<SQL::Translator::Parser::Excel> test
323 normalize_name("silly field (with random characters)");
327 silly_field_with_random_characters
329 =head2 header_comment
331 Create the header comment. Takes 1 mandatory argument (the producer
332 classname), an optional comment character (defaults to $DEFAULT_COMMENT),
333 and 0 or more additional comments, which will be appended to the header,
334 prefixed with the comment character. If additional comments are provided,
335 then a comment string must be provided ($DEFAULT_COMMENT is exported for
336 this use). For example, this:
338 package My::Producer;
340 use SQL::Translator::Utils qw(header_comment $DEFAULT_COMMENT);
342 print header_comment(__PACKAGE__,
349 -- Created by My::Prodcuer
350 -- Created on Fri Apr 25 06:56:02 2003
355 Note the gratuitous spacing.
357 =head2 parse_list_arg
359 Takes a string, list or arrayref (all of which could contain
360 comma-separated values) and returns an array reference of the values.
361 All of the following will return equivalent values:
363 parse_list_arg('id');
364 parse_list_arg('id', 'name');
365 parse_list_arg( 'id, name' );
366 parse_list_arg( [ 'id', 'name' ] );
367 parse_list_arg( qw[ id name ] );
369 =head2 truncate_id_uniquely
371 Takes a string ($desired_name) and int ($max_symbol_length). Truncates
372 $desired_name to $max_symbol_length by including part of the hash of
373 the full name at the end of the truncated name, giving a high
374 probability that the symbol will be unique. For example,
376 truncate_id_uniquely( 'a' x 100, 64 )
377 truncate_id_uniquely( 'a' x 99 . 'b', 64 );
378 truncate_id_uniquely( 'a' x 99, 64 )
380 Will give three different results; specifically:
382 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_7f900025
383 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_6191e39a
384 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_8cd96af2
386 =head2 $DEFAULT_COMMENT
388 This is the default comment string, '-- ' by default. Useful for
391 =head2 parse_mysql_version
393 Used by both L<Parser::MySQL|SQL::Translator::Parser::MySQL> and
394 L<Producer::MySQL|SQL::Translator::Producer::MySQL> in order to provide a
395 consistent format for both C<< parser_args->{mysql_parser_version} >> and
396 C<< producer_args->{mysql_version} >> respectively. Takes any of the following
397 version specifications:
403 5.001005 (perl style)
408 Darren Chamberlain E<lt>darren@cpan.orgE<gt>,
409 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.