MetaCurator/Database.pm untested

filter: Statementstmt 0.0% 0 / 203 Branchbran 0.0% 0 / 14 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 274 CC 8 SCAR 16.2
CC
8
Cov
0%
init_db
20.0
build_pad
6.0
get_special_para_names_regexp
6.0
CRAP 5.1
1 package CPAN::MetaCurator::Database;
2  
3 use boolean;
4 use feature 'say';
5 use parent 'CPAN::MetaCurator::Config';
6 use warnings qw(FATAL utf8); # Fatalize encoding glitches.
7  
8 use Data::Dumper::Concise; # For Dumper().
9 use DateTime::Tiny;
10  
11 use DBI;
12 use DBIx::Admin::CreateTable;
13 use DBIx::Simple;
14  
15 use Data::Dumper::Concise; # For Dumper().
16  
17 use File::Spec;
18 use File::Slurper 'read_lines';
19  
20 use Mew;
21 use Mojo::JSON qw/from_json/;
22  
23 use Text::CSV::Encoded;
24  
25 has -column_names => (ArrayRef, default => sub{return []}, chained => 1);
26  
27 has -creator => (Object, default => sub{return Ref}, chained => 1);
28  
29 has -db => (Any, default => sub{return ''}, chained => 1);
30  
31 has -dbh => (Any, default => sub{return ''}, chained => 1);
32  
33 has -engine => (Str, default => sub{return ''}, chained => 1);
34  
35 has -include_packages => (Bool, default => sub{return 0}, chained => 1);
36  
37 has input_path => (Str, default => sub{return ''}, chained => 1);
38  
39 has -metapackager_db => (Any, default => sub{return ''}, chained => 1);
40  
41 has -metapackager_dbh => (Any, default => sub{return ''}, chained => 1);
42  
43 has output_path => (Str, default => sub{return ''}, chained => 1);
44  
45 has -packages_path => (Str, default => sub{return '/tmp/02packages.details.txt'}, chained => 1);
46  
47 has -pad => (HashRef, default => sub{return {} }, chained => 1);
48  
49 has -time_option => (Str, default => sub{return ''}, chained => 1);
50  
51 our $VERSION = '1.33';
52  
53 # -----------------------------------------------
54  
55 sub build_pad
56 {
57 my($self) = @_;
58  
59 $self -> logger -> debug("Entered Database.build_pad()");
60  
61 my($pad) = {};
62 $$pad{count} = {};
63 $$pad{count}{$_} = 0 for (@{$self -> node_types});
64  
65 # Special case. See HTML.pm's build_html().
66  
67 my($packages_path) = $self -> packages_path;
68 $$pad{packages_id} = `head -8 $packages_path | tail -1`;
69  
70 # Read all tables into the pad.
71  
72 for (@{$self -> table_names}) {$$pad{$_} = $self -> read_table($_) };
73  
74 $$pad{module_names} = {};
75  
76 for my $item (@{$$pad{modules} })
77 {
78 $$pad{module_names}{$$item{name} } = $item;
79 }
80  
81 # Constants. Eg: encoding.
82 # The constants table used to contain page_name=html/cpan.metacurator.tree.html.
83 # Now we get the value from export.tree.pl & its parameter jstree_html_path.
84  
85 $$pad{$$_{name} } = $$_{value} for (@{$$pad{constants} });
86  
87 # MetaPackager.
88  
89 if ($self -> include_packages)
90 {
91 my($table_name) = $self -> read_metapackager_table($pad);
92  
93 $self -> logger -> info("Including metapackager table 'packages'");
94 $self -> logger -> info("Size of cpan.metapackager.sqlite table '$table_name': $$pad{count}{$table_name}");
95 }
96 else
97 {
98 $self -> logger -> info("Excluding metapackager table 'packages'");
99 }
100  
101 # Topics.
102 # There is a db table called topics so we need another name for the hash
103 # where the keys are the names of the topics and the values are db ids.
104 # For useage, see $leaf_id in Export.pm.
105  
106 $$pad{topic_ids} = {};
107 $$pad{topic_names} = {};
108  
109 for (@{$$pad{topics} })
110 {
111 $$pad{count}{topic}++;
112  
113 $$pad{topic_ids}{$$_{id} } = $$_{title};
114 $$pad{topic_names}{$$_{title} } = $$_{id};
115 }
116  
117 # Dates.
118 # DateTime::Tiny does not handle time_zone.
119  
120 $_ = DateTime::Tiny -> now;
121 $$pad{now} = $_ -> as_string;
122 $$pad{current_year} = substr($$pad{now}, 0, 4);
123  
124 $self -> pad($pad);
125 $self -> logger -> debug("Leaving Database.build_pad()");
126  
127 return $pad;
128  
129 } # End of build_pad.
130  
131 # -----------------------------------------------
132  
133 sub get_special_para_names_regexp
134 {
135 my($self, $pad) = @_;
136 $$pad{constants} = $self -> read_table('constants');
137  
138 my($special_para_names);
139  
140 for my $row (@{$$pad{constants} })
141 {
142 $special_para_names = $$row{value} if ($$row{name} eq 'special_para_names');
143 }
144  
145 return qr/($special_para_names)/o;
146  
147 } # End of get_special_para_names_regexp.
148  
149 # -----------------------------------------------
150  
151 sub get_table_column_names
152 {
153 my($self, $discard_id, $table_name) = @_;
154 my($sth) = $self -> dbh -> prepare("PRAGMA table_info($table_name)");
155  
156 $sth -> execute;
157  
158 my($row);
159 my(@column_names);
160  
161 while ($row = $sth -> fetchrow_hashref)
162 {
163 push @column_names, $$row{name} if (! $discard_id);
164 }
165  
166 $sth -> finish;
167 $self -> column_names(\@column_names);
168  
169 } # End of get_table_column_names;
170  
171 # -----------------------------------------------
172  
173 sub init_db
174 {
175 my($self) = @_;
176 my($config) = $self -> config;
177  
178 my(%attributes) =
179 (
180 AutoCommit => $$config{AutoCommit},
181 mysql_enable_utf8 => $$config{mysql_enable_utf8}, # Ignored if not using MySQL.
182 mysql_enable_utf8mb4 => $$config{mysql_enable_utf8mb4}, # Ignored if not using MySQL.
183 pg_enable_utf8 => $$config{pg_enable_utf8}, # Ignored if not using Pg.
184 RaiseError => $$config{RaiseError},
185 sqlite_unicode => $$config{sqlite_unicode}, # Ignored if not using SQLite.
186 );
187  
188 my(@dsn) = split('=', $$config{dsn});
189 $dsn[1] = File::Spec -> catfile($self -> home_path, $dsn[1]);
190 $dsn[0] = "$dsn[0]=$dsn[1]";
191  
192 $self -> dbh(DBI -> connect($dsn[0], $$config{username}, $$config{password}, \%attributes) );
193 $self -> dbh -> do('PRAGMA foreign_keys = ON') if ($$config{dsn} =~ /SQLite/i);
194 $self -> db(DBIx::Simple -> new($self -> dbh) );
195 $self -> creator(DBIx::Admin::CreateTable -> new(dbh => $self -> dbh, verbose => 0) );
196 $self -> engine($self -> creator -> db_vendor =~ /(?:Mysql)/i ? 'engine=innodb' : '');
197 $self -> time_option($self -> creator -> db_vendor =~ /(?:MySQL|Postgres)/i ? '(0) without time zone' : '');
198 $self -> logger -> info("Database.init_db(). Connected to $dsn[0]");
199  
200 } # End of init_db.
201  
202 # -----------------------------------------------
203  
204 sub insert_hashref
205 {
206 my($self, $table_name, $hashref) = @_;
207  
208 $self -> db -> insert($table_name, {map{($_ => $$hashref{$_})} keys %$hashref})
209 || die $self -> db -> error;
210  
211 return $self -> db -> last_insert_id(undef, undef, $table_name, undef);
212  
213 } # End of insert_hashref.
214  
215 # -----------------------------------------------
216  
217 sub init_metapackager_db
218 {
219 my($self) = @_;
220 my($config) = $self -> metapackager_config;
221  
222 my(%attributes) =
223 (
224 AutoCommit => $$config{AutoCommit},
225 mysql_enable_utf8 => $$config{mysql_enable_utf8}, # Ignored if not using MySQL.
226 mysql_enable_utf8mb4 => $$config{mysql_enable_utf8mb4}, # Ignored if not using MySQL.
227 pg_enable_utf8 => $$config{pg_enable_utf8}, # Ignored if not using Pg.
228 RaiseError => $$config{RaiseError},
229 sqlite_unicode => $$config{sqlite_unicode}, # Ignored if not using SQLite.
230 );
231  
232 my(@dsn) = split('=', $$config{dsn});
233 $dsn[1] = File::Spec -> catfile($dsn[1]);
234 $dsn[0] = "$dsn[0]=$dsn[1]";
235  
236 $self -> metapackager_dbh(DBI -> connect($dsn[0], $$config{username}, $$config{password}, \%attributes) );
237 $self -> metapackager_dbh -> do('PRAGMA foreign_keys = ON') if ($$config{dsn} =~ /SQLite/i);
238 $self -> metapackager_db(DBIx::Simple -> new($self -> metapackager_dbh) );
239 $self -> logger -> info("Database.init_metapackager_db(). Connected to $dsn[0]");
240  
241 } # End of init_metapackager_db.
242  
243 # -----------------------------------------------
244  
245 sub read_csv_file
246 {
247 my($self, $path) = @_;
248  
249 my($csv) = Text::CSV::Encoded -> new
250 ({
251 allow_whitespace => 1,
252 encoding_in => 'utf-8',
253 strict => 1,
254 });
255  
256 open(my $io, '<', $path) || die "Can't open($path): $!\n";
257  
258 my(@column_names) = $csv -> column_names($csv -> getline($io) );
259 my($count) = 0;
260  
261 my(@records);
262  
263 for my $item (@{$csv -> getline_hr_all($io) })
264 {
265 $count++;
266  
267 push @records, $$item{$column_names[0]};
268 }
269  
270 close $io;
271  
272 $self -> logger -> info("Read 1 heading + $count records from '$path'");
273  
274 return [@records];
275  
276 } # End of read_csv_file.
277  
278 # --------------------------------------------------
279  
280 sub read_metapackager_table
281 {
282 my($self, $pad) = @_;
283  
284 $self -> init_metapackager_config;
285 $self -> init_metapackager_db;
286  
287 # Return an arrayref of hashrefs.
288  
289 my($table_name) = 'packages';
290 my($sql) = "select * from $table_name";
291 my($set) = $self -> metapackager_db -> query($sql) || die $self -> metapackager_db -> error;
292 $set = [$set -> hashes];
293 $$pad{count}{$table_name} = $#$set + 1;
294 $$pad{$table_name} = {};
295 $$pad{$table_name}{$$_{name} } = $$_{id} for (@$set);
296  
297 $self -> metapackager_dbh -> disconnect;
298  
299 return $table_name;
300  
301 } # End of read_metapackager_table.
302  
303 # --------------------------------------------------
304  
305 sub read_1_record
306 {
307 my($self, $table_name, $id) = @_;
308 my($sql) = "select * from $table_name where id = $id";
309 my($set) = $self -> db -> query($sql) || die $self -> db -> error;
310  
311 # Return a hashref.
312  
313 return ${$set -> hashes}[0];
314  
315 } # End of read_1_record.
316  
317 # --------------------------------------------------
318  
319 sub read_table
320 {
321 my($self, $table_name) = @_;
322 my($sql) = "select * from $table_name";
323 my($set) = $self -> db -> query($sql) || die $self -> db -> error;
324  
325 # Return an arrayref of hashrefs.
326  
327 return [$set -> hashes];
328  
329 } # End of read_table.
330  
331 # --------------------------------------------------
332  
333 sub read_tiddlers_file
334 {
335 my($self) = @_;
336  
337 $self -> init_config;
338 $self -> init_db;
339  
340 my($file_name) = File::Spec -> catfile($self -> home_path, $self -> tiddlers_path);
341 my($data) = join('', read_lines($file_name, 'UTF-8') );
342  
343 return from_json $data;
344  
345 } # End of read_tiddlers_file.
346  
347 # --------------------------------------------------
348  
349 sub update_table
350 {
351 my($self, $table_name, $id, $columns) = @_;
352 my($sql) = "update $table_name set $columns where id = $id";
353 my($set) = $self -> db -> query($sql) || die $self -> db -> error;
354  
355 return $set;
356  
357 } # End of update_table.
358  
359 # --------------------------------------------------
360  
361 1;
362  
363 =pod
364  
365 =head1 NAME
366  
367 CPAN::MetaCurator::Database - Manage the cpan.metacurator.sqlite database
368  
369 =head1 Machine-Readable Change Log
370  
371 The file Changes was converted into Changelog.ini by L<Module::Metadata::Changes>.
372  
373 =head1 Version Numbers
374  
375 Version numbers < 1.00 represent development versions. From 1.00 up, they are production versions.
376  
377 =head1 Support
378  
379 Email the author.
380  
381 =head1 Author
382  
383 L<CPAN::MetaCurator> was written by Ron Savage I<E<lt>ron@savage.net.auE<gt>> in 2025.
384  
385 My homepage: L<https://savage.net.au/>.
386  
387 =head1 Copyright
388  
389 Australian copyright (c) 2025, Ron Savage.
390  
391 All Programs of mine are 'OSI Certified Open Source Software';
392 you can redistribute them and/or modify them under the terms of
393 The Perl License, a copy of which is available at:
394 http://dev.perl.org/licenses/
395  
396 =cut