Skip to content

Commit ab5b719

Browse files
pilcrowMike
authored andcommitted
lazy PRECISION
1 parent c33ee74 commit ab5b719

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

lib/DBD/Sponge.pm

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -93,12 +93,13 @@ use warnings;
9393
|| [ map { "col$_" } 1..$numFields ];
9494
$sth->{TYPE} = $attribs->{TYPE}
9595
|| [ (DBI::SQL_VARCHAR()) x $numFields ];
96-
$sth->{PRECISION} = $attribs->{PRECISION}
97-
|| _max_columnar_lengths($numFields, $rows);
9896
$sth->{SCALE} = $attribs->{SCALE}
9997
|| [ (0) x $numFields ];
10098
$sth->{NULLABLE} = $attribs->{NULLABLE}
10199
|| [ (2) x $numFields ];
100+
if ($attribs->{PRECISION}) {
101+
$sth->{PRECISION} = $attribs->{PRECISION};
102+
} # else FETCH will dynamically compute
102103
}
103104

104105
$outer;
@@ -155,18 +156,6 @@ use warnings;
155156
return \@args;
156157
}
157158

158-
sub _max_columnar_lengths {
159-
my ($numFields, $rows) = @_;
160-
my @precision = (0,) x $numFields;
161-
my $len;
162-
for my $row (@$rows) {
163-
for my $i (0 .. $numFields - 1) {
164-
next unless defined $len = length($row->[$i]);
165-
$precision[$i] = $len if $len > $precision[$i];
166-
}
167-
}
168-
return wantarray ? @precision : \@precision;
169-
}
170159
}
171160

172161

@@ -214,6 +203,10 @@ use warnings;
214203
sub FETCH {
215204
my ($sth, $attrib) = @_;
216205
# would normally validate and only fetch known attributes
206+
if ($attrib eq 'PRECISION') {
207+
# prepare() did _not_ specify PRECISION. We'll only get here once.
208+
return $sth->{PRECISION} = _max_col_lengths(@{$sth}{'NUM_OF_FIELDS', 'rows'});
209+
}
217210
# else pass up to DBI to handle
218211
return $sth->SUPER::FETCH($attrib);
219212
}
@@ -224,6 +217,19 @@ use warnings;
224217
# else pass up to DBI to handle
225218
return $sth->SUPER::STORE($attrib, $value);
226219
}
220+
221+
sub _max_col_lengths {
222+
my ($numFields, $rows) = @_;
223+
my @precision = (0,) x $numFields;
224+
my $len;
225+
for my $row (@$rows) {
226+
for my $i (0 .. $numFields - 1) {
227+
next unless defined($len = length($row->[$i]));
228+
$precision[$i] = $len if $len > $precision[$i];
229+
}
230+
}
231+
return wantarray ? @precision : \@precision;
232+
}
227233
}
228234

229235
1;

0 commit comments

Comments
 (0)