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 $DEFAULT_COMMENT parse_mysql_version
32 use constant COLLISION_TAG_LENGTH => 8;
34 # ----------------------------------------------------------------------
37 # Will send debugging messages to STDERR, if the caller's $DEBUG global
40 # This debug() function has a neat feature: Occurances of the strings
41 # PKG, LINE, and SUB in each message will be replaced with elements
44 # debug("PKG: Bad things happened on line LINE!");
48 # [SQL::Translator: Bad things happened on line 643]
50 # If called from Translator.pm, on line 643.
51 # ----------------------------------------------------------------------
53 my ($pkg, $file, $line, $sub) = caller(0);
56 return unless ${"$pkg\::DEBUG"};
64 $x =~ s/\bPKG\b/$pkg/g;
65 $x =~ s/\bLINE\b/$line/g;
66 $x =~ s/\bSUB\b/$sub/g;
67 #warn '[' . $x . "]\n";
68 print STDERR '[' . $x . "]\n";
72 # ----------------------------------------------------------------------
74 my $name = shift or return '';
76 # The name can only begin with a-zA-Z_; if there's anything
78 $name =~ s/^([^a-zA-Z_])/_$1/;
80 # anything other than a-zA-Z0-9_ in the non-first position
81 # needs to be turned into _
82 $name =~ tr/[a-zA-Z0-9_]/_/c;
84 # All duplicated _ need to be squashed into one.
93 # ----------------------------------------------------------------------
95 my $producer = shift || caller;
96 my $comment_char = shift;
97 my $now = scalar localtime;
99 $comment_char = $DEFAULT_COMMENT
100 unless defined $comment_char;
102 my $header_comment =<<"HEADER_COMMENT";
104 ${comment_char}Created by $producer
105 ${comment_char}Created on $now
109 # Any additional stuff passed in
110 for my $additional_comment (@_) {
111 $header_comment .= "${comment_char}${additional_comment}\n";
114 return $header_comment;
117 # ----------------------------------------------------------------------
120 # Meant to accept a list, an array reference, or a string of
121 # comma-separated values. Retuns an array reference of the
122 # arguments. Modified to also handle a list of references.
123 # ----------------------------------------------------------------------
125 my $list = UNIVERSAL::isa( $_[0], 'ARRAY' ) ? shift : [ @_ ];
128 # This protects stringification of references.
130 if ( @$list && ref $list->[0] ) {
134 # This processes string-like arguments.
138 map { s/^\s+|\s+$//g; $_ }
140 grep { defined && length } @$list
145 # ----------------------------------------------------------------------
146 # truncate_id_uniquely( $desired_name, $max_symbol_length )
148 # Truncates the name $desired_name to the $max_symbol_length by
149 # including part of the hash of the full name at the end of the
150 # truncated name, giving a high probability that the symbol will be
152 # ----------------------------------------------------------------------
153 sub truncate_id_uniquely {
154 my ( $desired_name, $max_symbol_length ) = @_;
157 unless defined $desired_name && length $desired_name > $max_symbol_length;
159 my $truncated_name = substr $desired_name, 0,
160 $max_symbol_length - COLLISION_TAG_LENGTH - 1;
162 # Hex isn't the most space-efficient, but it skirts around allowed
164 my $digest = sha1_hex($desired_name);
165 my $collision_tag = substr $digest, 0, COLLISION_TAG_LENGTH;
167 return $truncated_name
173 #---------------------------------------------------------------------
174 # parse_mysql_version ( $version_string, $result_target)
176 # Attempts to parse an arbitrary string as a mysql version number.
177 # Returns either a floating point perl style string, or a mysql style
178 # 5 digit string, depending on the supplied $result_target
179 #---------------------------------------------------------------------
180 sub parse_mysql_version {
181 my ($v, $target) = @_;
183 return undef unless $v;
190 if ( $v =~ / ^ (\d+) \. (\d{1,3}) (?: \. (\d{1,3}) )? $ /x ) {
191 push @vers, $1, $2, $3;
194 # XYYZZ (mysql) style
195 elsif ( $v =~ / ^ (\d) (\d{2}) (\d{2}) $ /x ) {
196 push @vers, $1, $2, $3;
199 # XX.YYYZZZ (perl) style or simply X
200 elsif ( $v =~ / ^ (\d+) (?: \. (\d{3}) (\d{3}) )? $ /x ) {
201 push @vers, $1, $2, $3;
204 #how do I croak sanely here?
205 die "Unparseable MySQL version '$v'";
208 if ($target eq 'perl') {
209 return sprintf ('%d.%03d%03d', map { $_ || 0 } (@vers) );
211 elsif ($target eq 'mysql') {
212 return sprintf ('%d%02d%02d', map { $_ || 0 } (@vers) );
215 #how do I croak sanely here?
216 die "Unknown version target '$target'";
223 # ----------------------------------------------------------------------
229 SQL::Translator::Utils - SQL::Translator Utility functions
233 use SQL::Translator::Utils qw(debug);
234 debug("PKG: Bad things happened");
238 C<SQL::Translator::Utils> contains utility functions designed to be
239 used from the other modules within the C<SQL::Translator> modules.
241 Nothing is exported by default.
243 =head1 EXPORTED FUNCTIONS AND CONSTANTS
247 C<debug> takes 0 or more messages, which will be sent to STDERR using
248 C<warn>. Occurances of the strings I<PKG>, I<SUB>, and I<LINE>
249 will be replaced by the calling package, subroutine, and line number,
250 respectively, as reported by C<caller(1)>.
252 For example, from within C<foo> in F<SQL/Translator.pm>, at line 666:
254 debug("PKG: Error reading file at SUB/LINE");
258 [SQL::Translator: Error reading file at foo/666]
260 The entire message is enclosed within C<[> and C<]> for visual clarity
261 when STDERR is intermixed with STDOUT.
263 =head2 normalize_name
265 C<normalize_name> takes a string and ensures that it is suitable for
266 use as an identifier. This means: ensure that it starts with a letter
267 or underscore, and that the rest of the string consists of only
268 letters, numbers, and underscores. A string that begins with
269 something other than [a-zA-Z] will be prefixer with an underscore, and
270 all other characters in the string will be replaced with underscores.
271 Finally, a trailing underscore will be removed, because that's ugly.
273 normalize_name("Hello, world");
279 A more useful example, from the C<SQL::Translator::Parser::Excel> test
282 normalize_name("silly field (with random characters)");
286 silly_field_with_random_characters
288 =head2 header_comment
290 Create the header comment. Takes 1 mandatory argument (the producer
291 classname), an optional comment character (defaults to $DEFAULT_COMMENT),
292 and 0 or more additional comments, which will be appended to the header,
293 prefixed with the comment character. If additional comments are provided,
294 then a comment string must be provided ($DEFAULT_COMMENT is exported for
295 this use). For example, this:
297 package My::Producer;
299 use SQL::Translator::Utils qw(header_comment $DEFAULT_COMMENT);
301 print header_comment(__PACKAGE__,
308 -- Created by My::Prodcuer
309 -- Created on Fri Apr 25 06:56:02 2003
314 Note the gratuitous spacing.
316 =head2 parse_list_arg
318 Takes a string, list or arrayref (all of which could contain
319 comma-separated values) and returns an array reference of the values.
320 All of the following will return equivalent values:
322 parse_list_arg('id');
323 parse_list_arg('id', 'name');
324 parse_list_arg( 'id, name' );
325 parse_list_arg( [ 'id', 'name' ] );
326 parse_list_arg( qw[ id name ] );
328 =head2 truncate_id_uniquely
330 Takes a string ($desired_name) and int ($max_symbol_length). Truncates
331 $desired_name to $max_symbol_length by including part of the hash of
332 the full name at the end of the truncated name, giving a high
333 probability that the symbol will be unique. For example,
335 truncate_id_uniquely( 'a' x 100, 64 )
336 truncate_id_uniquely( 'a' x 99 . 'b', 64 );
337 truncate_id_uniquely( 'a' x 99, 64 )
339 Will give three different results; specifically:
341 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_7f900025
342 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_6191e39a
343 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_8cd96af2
345 =head2 $DEFAULT_COMMENT
347 This is the default comment string, '-- ' by default. Useful for
350 =head2 parse_mysql_version
352 Used by both L<Parser::MySQL|SQL::Translator::Parser::MySQL> and
353 L<Producer::MySQL|SQL::Translator::Producer::MySQL> in order to provide a
354 consistent format for both C<< parser_args->{mysql_parser_version} >> and
355 C<< producer_args->{mysql_version} >> respectively. Takes any of the following
356 version specifications:
362 5.001005 (perl style)
367 Darren Chamberlain E<lt>darren@cpan.orgE<gt>,
368 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.