blib/lib/Mojolicious/Plugin/DbicSchemaViewer.pm

filter: Statementstmt 94.4% 34 / 36 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 12 / 12 Podpod n/a totaltotal 95.8% 46 / 48 CC 1 SCAR 0.2
CC
1
Cov
94%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 package Mojolicious::Plugin::DbicSchemaViewer;
5  
6 # ABSTRACT: Viewer for DBIx::Class schema definitions
7 our $AUTHORITY = 'cpan:CSSON'; # AUTHORITY
8 our $VERSION = '0.0200';
9  
10 2 ▶use Mojo::Base 'Mojolicious::Plugin';
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use Mojo::Home;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶use File::ShareDir 'dist_dir';
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 2 ▶use Data::Dump::Streamer;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 2 ▶use Safe::Isa;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 2 ▶use DateTime::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 2 ▶use PerlX::Maybe;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 2 ▶use List::Util qw/none/;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 0 ▶use DBIx::Class::Visualizer;
Subroutine BEGIN: called CC=1 SCAR=2.6
20  
21 use experimental qw/signatures postderef/;
22  
23 has schemas => sub { +{} };
24 has allowed_schemas => sub { [] };
25  
26 sub register($self, $app, $conf) {
27 $app->plugin('BootstrapHelpers');
28  
29 # Check configuration
30 if(exists $conf->{'router'} && exists $conf->{'condition'}) {
31 my $exception = "Can't use both 'router' and 'condition' in M::P::DbicSchemaViewer";
32 $app->log->fatal($exception);
33 $app->reply->exception($exception);
34 return;
35 }
36 # Preload all (if any) allowed schemas
37 if(exists $conf->{'allowed_schemas'} && scalar $conf->{'allowed_schemas'}->@*) {
38 $self->allowed_schemas->@* = $conf->{'allowed_schemas'}->@*;
39  
40 for my $allowed ($self->allowed_schemas->@*) {
41 if(eval "require $allowed") {
42 $self->schemas->{ $allowed } = $allowed->connect;
43 }
44 }
45 }
46  
47 # set MOJO_DBIC_SCHEMA_VIEWER_LOCAL to a true value to use the template in the distribution
48 # rather than those installed
49 my $dirroot = $ENV{'MOJO_DBIC_SCHEMA_VIEWER_LOCAL'} ? path(Mojo::Home->new->rel_dir('share'))
50 : path(dist_dir('Mojolicious-Plugin-DbicSchemaViewer'))
51 ;
52  
53  
54 # add our template directory
55 my $template_dir = $dirroot->child('templates');
56  
57 if($template_dir->is_dir) {
58 push $app->renderer->paths->@* => $template_dir->realpath;
59 $app->log->debug(sprintf '[M::P::DbicSchemaViewer] Adds %s to renderer paths', $template_dir->stringify);
60 }
61  
62 my $router = exists $conf->{'router'} ? $conf->{'router'}
63 : exists $conf->{'condition'} ? $app->routes->over($conf->{'condition'})
64 : $app->routes
65 ;
66  
67 my $url = $conf->{'url'} || 'dbic-schema-viewer';
68  
69 push @{ $app->static->paths }, $dirroot->child('public')->stringify;
70  
71  
72 # Routes
73 my $base = $router->get($url);
74  
75 # home / schema
76 $base->get('/:schema')->to(cb => sub ($c) {
77 my $schema = $self->get_schema($app, $c);
78  
79 if(!defined $schema) {
80 $c->flash(bad_schema => 1);
81 $c->redirect_to('home');
82 return;
83 }
84  
85 $self->render($c, 'overview', db => $self->schema_info($schema), title => ref $schema);
86 })->name('overview');
87  
88 # visualizer
89 $base->get('visualizer/:schema')->to(cb => sub ($c) {
90 my $schema = $self->get_schema($app, $c);
91 if(!defined $schema) {
92 $c->flash(bad_schema => 1);
93 $c->redirect_to('home');
94 return;
95 }
96  
97 my(%wanted_result_source_names, %skip_result_source_names);
98  
99 if($c->param('wanted_result_source_names')) {
100 my $wanted_result_source_names = [split /,/ => $c->param('wanted_result_source_names')];
101 %wanted_result_source_names = scalar $wanted_result_source_names->@* ? (wanted_result_source_names => $wanted_result_source_names) : ();
102 }
103 if($c->param('skip_result_source_names')) {
104 my $skip_result_source_names = [split /,/ => $c->param('skip_result_source_names')];
105 %skip_result_source_names = scalar $skip_result_source_names->@* ? (skip_result_source_names => $skip_result_source_names) : ();
106 }
107  
108 $self->render($c, 'visualizer',
109 title => ref $schema,
110 svg => DBIx::Class::Visualizer->new(
111 schema => $schema,
112 %wanted_result_source_names,
113 %skip_result_source_names,
114 maybe degrees_of_separation => $c->param('degrees_of_separation'),
115 maybe only_keys => $c->param('only_keys'),
116 )->transformed_svg
117 );
118 })->name('visualizer');
119  
120 # Reconnect all schemas, useful when schemas are updated.
121 $base->get('refresh/:schema/:destination')->to(cb => sub ($c) {
122 foreach my $schema (keys $self->schemas->%*) {
123 if(eval "require $schema") {
124 $c->app->log->debug(qq{M::P::DbicSchemaViewer reconnects with $schema});
125 $self->schemas->{ $schema } = $schema->connect;
126 }
127 }
128 $c->redirect_to($c->param('destination'));
129 })->name('refresh');
130  
131 # home
132 $base->get('/')->to(cb => sub ($c) {
133 $c->redirect_to('overview', schema => $c->param('schema')) && return if $c->param('schema');
134 $self->render($c, 'home', title => 'Home', bad_schema => $c->param('bad_schema'));
135 })->name('home');
136  
137 }
138  
139 sub render($self, $c, $template, @args) {
140 my %layout = (layout => 'plugin-dbic-schema-viewer-default');
141 $c->render(%layout, template => "viewer/$template", @args, all_schemas => $self->schemas);
142 }
143  
144 sub get_schema {
145 my $self = shift;
146 my $app = shift;
147 my $c = shift;
148  
149 my $schema;
150 if($c->param('schema')) {
151 if(scalar $self->allowed_schemas->@* && (none { $c->param('schema') eq $_ } $self->allowed_schemas->@*)) {
152 $app->log->warn($c->param('schema') . ' is not in the list of allowed schemas');
153 }
154 if(exists $self->schemas->{ $c->param('schema') }) {
155 return $self->schemas->{ $c->param('schema') };
156 }
157 elsif(eval "require @{[ $c->param('schema') ]}") {
158 $schema = ($c->param('schema'))->connect;
159 }
160 else {
161 $app->log->warn("Could not load @{[ $c->param('schema') ]}");
162 }
163 }
164 else {
165 $app->log->warn(q{M::P::DbicSchemaViewer is missing mandatory 'schema' parameter.});
166 return;
167 }
168  
169 if($schema->$_isa('DBIx::Class::Schema')) {
170 $self->schemas->{ $c->param('schema') } = $schema;
171 }
172 else {
173 $app->log->warn("'schema' must be an DBIx::Class::Schema instance in M::P::DbicSchemaViewer, @{[ $c->param('schema') ]} is not");
174 return;
175 }
176 return $schema;
177 }
178 sub schema_info($self, $schema) {
179  
180 my $db = { sources => [] };
181  
182 # put View:: result sources last
183 my @sorted_sources = sort grep { !/^View::/ } $schema->sources;
184 push @sorted_sources => sort grep { /^View::/ } $schema->sources;
185  
186 foreach my $source_name (@sorted_sources) {
187 my $rs = $schema->resultset($source_name)->result_source;
188  
189 my $uniques = {};
190 my %unique_constraints = $rs->unique_constraints;
191  
192 foreach my $unique_constraint (keys %unique_constraints) {
193 foreach my $column ($unique_constraints{ $unique_constraint }->@*) {
194 if(!exists $uniques->{ $column }) {
195 $uniques->{ $column } = [];
196 }
197 push $uniques->{ $column }->@* => $unique_constraint;
198 }
199 }
200 my $clean_name = lc $source_name =~ s{::}{_}gr;
201  
202 my $source = {
203 name => $source_name,
204 clean_name => $clean_name,
205 primary_columns => [$rs->primary_columns],
206 unique_constraints => [$rs->unique_constraints],
207 uniques => $uniques,
208 columns_info => [],
209 relationships => [],
210 };
211  
212 foreach my $column_name ($rs->columns) {
213 my $column_info = { $rs->column_info($column_name)->%* };
214 my $data_type = delete $column_info->{'data_type'};
215 $data_type = $column_info->{'is_enum'} && scalar $column_info->{'extra'}{'list'}->@* ? "enum/$data_type" : $data_type;
216  
217 push $source->{'columns'}->@* => {
218 name => $column_name,
219 $column_info->%*,
220 data_type => $data_type,
221 };
222 }
223  
224 foreach my $relation_name (sort $rs->relationships) {
225 my $relation = $rs->relationship_info($relation_name);
226 my $class_name = $relation->{'class'} =~ s{^.*?::Result::}{}r;
227  
228 my $condition;
229 # simple one column to one column relation: this_result_id => relation_name.that_result_id
230 if(ref $relation->{'cond'} eq 'HASH' && scalar keys $relation->{'cond'}->%* == 1) {
231 my @cleaned_condition = ((values $relation->{'cond'}->%*)[0] =~ s{^self\.}{}rx);
232 push @cleaned_condition => (keys $relation->{'cond'}->%*)[0] =~ s{^foreign(?=\.)}{$relation_name}rx;
233 $condition = join ' => ', @cleaned_condition;
234 }
235 # more complicated relation: dump relation to text and remove boilerplate
236 else {
237 $condition = Dump($relation->{'cond'})->Out;
238  
239 # cleanup the dump
240 $condition =~ s{^.*?\{}{\{};
241 $condition =~ s{\n\s*?package .*?\n}{\n};
242 $condition =~ s{\n\s*?BEGIN.*?\n}{\n};
243 $condition =~ s{\n\s*?use strict.*?\n}{\n}g;
244 $condition =~ s{\n\s*?use feature.*?\n}{\n}g;
245 $condition =~ s{\n\s*?no feature.*?\n}{\n}g;
246 $condition =~ s{\n\s{3,}\}}{\n\}};
247 $condition =~ s{\n\s{8,8}}{\n }g;
248 }
249  
250 my $on_cascade = [ sort map { $_ =~ s{^cascade_}{}rm } grep { m/^cascade/ && $relation->{'attrs'}{ $_ } } keys $relation->{'attrs'}->%* ];
251  
252 # do not reorder
253 my $relation_type = $relation->{'attrs'}{'accessor'} eq 'multi' ? 'has_many'
254 : $relation->{'attrs'}{'is_depends_on'} ? 'belongs_to'
255 : exists $relation->{'attrs'}{'join_type'} ? 'might_have'
256 : 'has_one'
257 ;
258  
259 push $source->{'relationships'}->@* => {
260 name => $relation_name,
261 class_name => $class_name,
262 clean_name => lc $class_name =~ s{::}{_}rg,
263 condition => $condition,
264 on_cascade => $on_cascade,
265 $relation->%*,
266 relation_type => $relation_type,
267 has_reverse_relation => keys $rs->reverse_relationship_info($relation_name)->%* ? 1 : 0,
268 };
269 }
270  
271 push $db->{'sources'}->@* => $source;
272 }
273 return $db;
274 }
275  
276 1;
277  
278 __END__
↑ Summary