- Removed use of $Revision$ SVN keyword to generate VERSION variables; now sub-module...
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Utils.pm
CommitLineData
1a24938d 1package SQL::Translator::Utils;
2
3# ----------------------------------------------------------------------
821a0fde 4# $Id$
1a24938d 5# ----------------------------------------------------------------------
478f608d 6# Copyright (C) 2002-2009 SQLFairy Authors
1a24938d 7#
8# This program is free software; you can redistribute it and/or
9# modify it under the terms of the GNU General Public License as
10# published by the Free Software Foundation; version 2.
11#
12# This program is distributed in the hope that it will be useful, but
13# WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15# General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20# 02111-1307 USA
21# -------------------------------------------------------------------
22
23use strict;
24use base qw(Exporter);
478f608d 25use vars qw($DEFAULT_COMMENT @EXPORT_OK);
1a24938d 26
f5405d47 27use Digest::SHA1 qw( sha1_hex );
28
1a24938d 29use Exporter;
30
a2ba36ba 31$DEFAULT_COMMENT = '-- ';
118bb73f 32@EXPORT_OK = qw(
5d666b31 33 debug normalize_name header_comment parse_list_arg truncate_id_uniquely $DEFAULT_COMMENT parse_mysql_version
118bb73f 34);
1a24938d 35
36# ----------------------------------------------------------------------
37# debug(@msg)
38#
39# Will send debugging messages to STDERR, if the caller's $DEBUG global
40# is set.
41#
42# This debug() function has a neat feature: Occurances of the strings
43# PKG, LINE, and SUB in each message will be replaced with elements
44# from caller():
45#
46# debug("PKG: Bad things happened on line LINE!");
47#
48# Will be warned as:
49#
50# [SQL::Translator: Bad things happened on line 643]
51#
52# If called from Translator.pm, on line 643.
53# ----------------------------------------------------------------------
54sub debug {
a2ba36ba 55 my ($pkg, $file, $line, $sub) = caller(0);
1a24938d 56 {
57 no strict qw(refs);
58 return unless ${"$pkg\::DEBUG"};
59 }
60
61 $sub =~ s/^$pkg\:://;
62
63 while (@_) {
64 my $x = shift;
65 chomp $x;
66 $x =~ s/\bPKG\b/$pkg/g;
67 $x =~ s/\bLINE\b/$line/g;
68 $x =~ s/\bSUB\b/$sub/g;
69 #warn '[' . $x . "]\n";
70 print STDERR '[' . $x . "]\n";
71 }
72}
73
118bb73f 74# ----------------------------------------------------------------------
93d12e9c 75sub normalize_name {
ae48473b 76 my $name = shift or return '';
93d12e9c 77
78 # The name can only begin with a-zA-Z_; if there's anything
79 # else, prefix with _
80 $name =~ s/^([^a-zA-Z_])/_$1/;
81
82 # anything other than a-zA-Z0-9_ in the non-first position
83 # needs to be turned into _
84 $name =~ tr/[a-zA-Z0-9_]/_/c;
85
86 # All duplicated _ need to be squashed into one.
87 $name =~ tr/_/_/s;
88
89 # Trim a trailing _
90 $name =~ s/_$//;
91
92 return $name;
93}
94
118bb73f 95# ----------------------------------------------------------------------
a2ba36ba 96sub header_comment {
97 my $producer = shift || caller;
98 my $comment_char = shift;
99 my $now = scalar localtime;
100
101 $comment_char = $DEFAULT_COMMENT
102 unless defined $comment_char;
103
104 my $header_comment =<<"HEADER_COMMENT";
105${comment_char}
106${comment_char}Created by $producer
107${comment_char}Created on $now
108${comment_char}
109HEADER_COMMENT
110
111 # Any additional stuff passed in
112 for my $additional_comment (@_) {
113 $header_comment .= "${comment_char}${additional_comment}\n";
114 }
115
116 return $header_comment;
117}
118
118bb73f 119# ----------------------------------------------------------------------
51bb6fe0 120# parse_list_arg
121#
122# Meant to accept a list, an array reference, or a string of
123# comma-separated values. Retuns an array reference of the
124# arguments. Modified to also handle a list of references.
125# ----------------------------------------------------------------------
e545d971 126sub parse_list_arg {
127 my $list = UNIVERSAL::isa( $_[0], 'ARRAY' ) ? shift : [ @_ ];
128
51bb6fe0 129 #
130 # This protects stringification of references.
131 #
132 if ( @$list && ref $list->[0] ) {
133 return $list;
134 }
135 #
136 # This processes string-like arguments.
137 #
138 else {
139 return [
140 map { s/^\s+|\s+$//g; $_ }
141 map { split /,/ }
142 grep { defined && length } @$list
143 ];
144 }
118bb73f 145}
146
f5405d47 147# ----------------------------------------------------------------------
148# truncate_id_uniquely( $desired_name, $max_symbol_length )
149#
150# Truncates the name $desired_name to the $max_symbol_length by
151# including part of the hash of the full name at the end of the
152# truncated name, giving a high probability that the symbol will be
153# unique.
154# ----------------------------------------------------------------------
155my $COLLISION_TAG_LENGTH = 8;
156sub truncate_id_uniquely {
157 my ( $desired_name, $max_symbol_length ) = @_;
158
159 return $desired_name unless defined $desired_name && length $desired_name > $max_symbol_length;
160
161 my $truncated_name = substr $desired_name, 0, $max_symbol_length - $COLLISION_TAG_LENGTH - 1;
162
163 # Hex isn't the most space-efficient, but it skirts around allowed
164 # charset issues
165 my $digest = sha1_hex($desired_name);
166 my $collision_tag = substr $digest, 0, $COLLISION_TAG_LENGTH;
167
168 return $truncated_name
169 . '_'
170 . $collision_tag;
171}
172
5d666b31 173
174#---------------------------------------------------------------------
175# parse_mysql_version ( $version_string, $result_target)
176#
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#---------------------------------------------------------------------
181sub parse_mysql_version {
182 my ($v, $target) = @_;
183
184 return undef unless $v;
185
186 $target ||= 'perl';
187
188 my @vers;
189
190 # X.Y.Z style
191 if ( $v =~ / ^ (\d+) \. (\d{1,3}) (?: \. (\d{1,3}) )? $ /x ) {
192 push @vers, $1, $2, $3;
193 }
194
195 # XYYZZ (mysql) style
196 elsif ( $v =~ / ^ (\d) (\d{2}) (\d{2}) $ /x ) {
197 push @vers, $1, $2, $3;
198 }
199
200 # XX.YYYZZZ (perl) style or simply X
201 elsif ( $v =~ / ^ (\d+) (?: \. (\d{3}) (\d{3}) )? $ /x ) {
202 push @vers, $1, $2, $3;
203 }
204 else {
205 #how do I croak sanely here?
206 die "Unparseable MySQL version '$v'";
207 }
208
209 if ($target eq 'perl') {
210 return sprintf ('%d.%03d%03d', map { $_ || 0 } (@vers) );
211 }
212 elsif ($target eq 'mysql') {
213 return sprintf ('%d%02d%02d', map { $_ || 0 } (@vers) );
214 }
215 else {
216 #how do I croak sanely here?
217 die "Unknown version target '$target'";
218 }
219}
220
221
1a24938d 2221;
223
118bb73f 224# ----------------------------------------------------------------------
225
226=pod
1a24938d 227
228=head1 NAME
229
230SQL::Translator::Utils - SQL::Translator Utility functions
231
232=head1 SYNOPSIS
233
234 use SQL::Translator::Utils qw(debug);
235 debug("PKG: Bad things happened");
236
237=head1 DESCSIPTION
238
239C<SQL::Translator::Utils> contains utility functions designed to be
240used from the other modules within the C<SQL::Translator> modules.
241
a2ba36ba 242Nothing is exported by default.
1a24938d 243
a2ba36ba 244=head1 EXPORTED FUNCTIONS AND CONSTANTS
1a24938d 245
246=head2 debug
247
248C<debug> takes 0 or more messages, which will be sent to STDERR using
249C<warn>. Occurances of the strings I<PKG>, I<SUB>, and I<LINE>
250will be replaced by the calling package, subroutine, and line number,
e545d971 251respectively, as reported by C<caller(1)>.
1a24938d 252
253For example, from within C<foo> in F<SQL/Translator.pm>, at line 666:
254
255 debug("PKG: Error reading file at SUB/LINE");
256
257Will warn
258
259 [SQL::Translator: Error reading file at foo/666]
260
261The entire message is enclosed within C<[> and C<]> for visual clarity
262when STDERR is intermixed with STDOUT.
93d12e9c 263
264=head2 normalize_name
265
266C<normalize_name> takes a string and ensures that it is suitable for
267use as an identifier. This means: ensure that it starts with a letter
268or underscore, and that the rest of the string consists of only
269letters, numbers, and underscores. A string that begins with
270something other than [a-zA-Z] will be prefixer with an underscore, and
271all other characters in the string will be replaced with underscores.
272Finally, a trailing underscore will be removed, because that's ugly.
273
274 normalize_name("Hello, world");
275
276Produces:
277
278 Hello_world
279
280A more useful example, from the C<SQL::Translator::Parser::Excel> test
281suite:
282
283 normalize_name("silly field (with random characters)");
284
285returns:
286
287 silly_field_with_random_characters
288
a2ba36ba 289=head2 header_comment
290
291Create the header comment. Takes 1 mandatory argument (the producer
292classname), an optional comment character (defaults to $DEFAULT_COMMENT),
293and 0 or more additional comments, which will be appended to the header,
294prefixed with the comment character. If additional comments are provided,
295then a comment string must be provided ($DEFAULT_COMMENT is exported for
296this use). For example, this:
297
298 package My::Producer;
299
300 use SQL::Translator::Utils qw(header_comment $DEFAULT_COMMENT);
301
302 print header_comment(__PACKAGE__,
e545d971 303 $DEFAULT_COMMENT,
a2ba36ba 304 "Hi mom!");
305
306produces:
307
e545d971 308 --
a2ba36ba 309 -- Created by My::Prodcuer
310 -- Created on Fri Apr 25 06:56:02 2003
e545d971 311 --
a2ba36ba 312 -- Hi mom!
e545d971 313 --
a2ba36ba 314
315Note the gratuitous spacing.
316
118bb73f 317=head2 parse_list_arg
318
319Takes a string, list or arrayref (all of which could contain
320comma-separated values) and returns an array reference of the values.
321All of the following will return equivalent values:
322
323 parse_list_arg('id');
324 parse_list_arg('id', 'name');
325 parse_list_arg( 'id, name' );
326 parse_list_arg( [ 'id', 'name' ] );
327 parse_list_arg( qw[ id name ] );
328
f5405d47 329=head2 truncate_id_uniquely
330
331Takes a string ($desired_name) and int ($max_symbol_length). Truncates
332$desired_name to $max_symbol_length by including part of the hash of
333the full name at the end of the truncated name, giving a high
334probability that the symbol will be unique. For example,
335
336 truncate_id_uniquely( 'a' x 100, 64 )
337 truncate_id_uniquely( 'a' x 99 . 'b', 64 );
338 truncate_id_uniquely( 'a' x 99, 64 )
339
340Will give three different results; specifically:
341
342 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_7f900025
343 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_6191e39a
344 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_8cd96af2
345
a2ba36ba 346=head2 $DEFAULT_COMMENT
347
348This is the default comment string, '-- ' by default. Useful for
349C<header_comment>.
350
5d666b31 351=head2 parse_mysql_version
352
353Used by both L<Parser::MySQL|SQL::Translator::Parser::MySQL> and
354L<Producer::MySQL|SQL::Translator::Producer::MySQL> in order to provide a
355consistent format for both C<< parser_args->{mysql_parser_version} >> and
356C<< producer_args->{mysql_version} >> respectively. Takes any of the following
357version specifications:
358
359 5.0.3
360 4.1
361 3.23.2
362 5
363 5.001005 (perl style)
364 30201 (mysql style)
365
118bb73f 366=head1 AUTHORS
367
368Darren Chamberlain E<lt>darren@cpan.orgE<gt>,
369Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.
370
371=cut