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