blib/lib/DBIx/Class/PseudoEnum.pm untested

filter: Statementstmt 0.0% 0 / 71 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 7 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 105 CC 6 SCAR 18.3
CC
6
Cov
0%
insert
12.0
_register_enumeration_methods
12.0
set_column
6.0
CRAP 6.2
1 package DBIx::Class::PseudoEnum;
2 use Modern::Perl;
3 our $VERSION = '1.0002'; # VERSION
4 our $AUTHORITY = 'cpan:GEEKRUTH'; # AUTHORITY
5 # ABSTRACT: Schema-based enumerations independent of database
6 use Carp;
7  
8 use parent 'DBIx::Class::Row';
9 use DBIx::Class::Candy::Exports;
10 use Sub::Quote qw(quote_sub);
11  
12 # Exports for DBIx::Class::Candy
13 export_methods [qw/enumerations_use_column_names enumerate/];
14  
15 # New public methods
16 sub enumerate {
17 my ( $class, $column, $values ) = @_;
18 my $info = $class->source_info();
19 $info->{enumerations} //= {};
20 $info->{enumerations}->{$column} = $values;
21 $class->source_info($info);
22 }
23  
24 sub enumerations_use_column_names {
25 my $class = shift;
26 my $info = $class->source_info();
27 $info->{enumerations} //= {};
28 $info->{enumerations}->{__use_column_names} = 1;
29 $class->source_info($info);
30 }
31  
32 # Overriden methods
33 sub new {
34 my ( $class, $attrs ) = @_;
35 my $new = $class->next::method($attrs);
36 $new->_register_enumeration_methods();
37 return $new;
38 }
39  
40 sub insert {
41 my $self = shift;
42 my %data = $self->get_columns();
43 my $info = $self->source_info()->{enumerations};
44 foreach my $data_key ( keys %$info ) {
45 # undef values will fall through and be captured by other
46 # parts of the schema, if they're not allowed.
47 next if !defined $data{$data_key};
48 if ( !grep { $_ eq $data{$data_key} } @{ $info->{$data_key} } ) {
49 croak
50 "You have attempted to assign a value to $data_key that is not valid: $data{$data_key}";
51 }
52 }
53 return $self->next::method(@_);
54 }
55  
56 sub set_column {
57 my ($self, $column_name, $value) = @_;
58  
59 my $values = $self->source_info()->{enumerations}->{$column_name};
60 if (defined $value &&!grep { $value eq $_ } @$values) {
61 croak
62 "You have attempted to assign a value to $column_name that is not valid: $value";
63 }
64 return shift->next::method(@_);
65 }
66  
67 # Internal methods
68 sub _register_enumeration_methods {
69 my $class = shift;
70 my $classname = ref $class;
71 my $rs = $class->result_source->resultset;
72 my $rs_classname = ref $rs;
73 my $enumerations = $class->source_info->{enumerations};
74 my $use_column_names = defined $enumerations->{__use_column_names};
75 foreach my $column ( keys %$enumerations ) {
76 next if $column =~ /^__/;
77 my $header = "$classname\:\:";
78 my $rs_header = "$rs_classname\:\:";
79 if ($use_column_names) {
80 $header = "$classname\:\:${column}_";
81 $rs_header = "$rs_classname\:\:${column}_";
82 }
83 foreach my $value ( @{ $enumerations->{$column} } ) {
84 my $term = lc $value;
85 $term =~ s/[[:punct:][:space:]]/_/g;
86 quote_sub "${header}is_$term", qq/
87 my \$class=shift;
88 return 0 if !\$class->$column;
89 return \$class->$column eq '$value';
90 /, { '$rel' => \$column, '$column' => \$value };
91 quote_sub "${rs_header}is_$term", qq/
92 my \$class=shift;
93 return \$class->search({ $column => '$value'});
94 /, { '$rel' => \$column, '$column' => \$value };
95 }
96 }
97 }
98  
99 1;
100  
101 __END__
102  
103 =pod
104  
105 =encoding UTF-8
106  
107 =head1 NAME
108  
109 DBIx::Class::PseudoEnum - Schema-based enumerations independent of database
110  
111 =head1 VERSION
112  
113 version 1.0002
114  
115 =head1 SYNOPSIS
116  
117 # In your Schema::Result class:
118 __PACKAGE__->load_components('PseudoEnum');
119  
120 # Load your enumerations into source_info directly
121 __PACKAGE__->table('contraption');
122 __PACKAGE__->source_info(
123 {
124 enumerations => { 'status' => [qw/Sold Packaged Shipped/] }
125 }
126  
127 # Or use the handy-dandy methods
128 # (leave off the __PACKAGE__ if you're using DBIx::Class::Candy)
129 __PACKAGE__->table('doodad');
130 __PACKAGE__->enumerate( 'status', [qw/Ordered In-Stock Out-Of-Stock/] );
131 __PACKAGE__->enumerate( 'color', [qw/Black Blue Green Red/] );
132  
133 # Properly handle value collisions in the same table
134 # (both fields here could create an 'is_blue' method!)
135 __PACKAGE__->table('doohickey');
136 __PACKAGE__->enumerations_use_column_names();
137 __PACKAGE__->enumerate( 'field1', [qw/One Two Three Four Blue/] );
138 __PACKAGE__->enumerate( 'field2', [qw/BLUE RED GREEN/] );
139  
140 # Later, in your application:
141 # On Results:
142 $doodad->is_ordered; # Boolean, true if doodad.status == 'Ordered'
143 $doodad->is_blue; # Boolean, true if doodad.color == 'Blue'
144 $doodad->update({ status => 'Dunno'}); # croaks!
145 $doodad->update({ status => 'ordered' }); # croaks!
146 $doodad->update({ color => 'Black' }); # okay!
147 # The module will try to pass this on to the rest of the update() method; if the
148 # field is nullable, it'll work.
149 $doodad->update({ color => undef });
150  
151 # On ResultSets:
152 $doodad_rs->create({ status => 'Dunno' }); # croaks!
153 $doodad_rs->create({ status => 'ordered' }); # croaks!
154 $doodad_rs->create({ color => 'Black' }); # okay!
155 $doodad_rs->is_blue # Returns a ResultSet where doodad.color == 'Blue'
156  
157 # With enumerations_use_column_names:
158 $doohickey->is_blue # "no such method"
159 $doohickey->field1_is_blue # Now it does what you want!
160  
161 =head1 DESCRIPTION
162  
163 Enumerations can be a bit of a pain. Not all databases support them equally (or at all), which reduces
164 the portability of your application. Additionally, there are some
165 L<philosophical and practical problems|https://chateau-logic.com/content/why-we-should-not-use-enums-databases>
166 with them. Lookup tables are an alternative, but maybe you don't want to clutter up your DB with single-column
167 lookup tables.
168  
169 But searching around the interwebs, no one seems to mind enumerating valid values for a data entity within
170 the application layer. So that's what this module provides: a way to put the enumeration in the C<DBIx::Class>
171 schema, and have it enforced within the application, invisibly to the DB.
172  
173 =head1 SUBROUTINES/METHODS
174  
175 =head2 enumerate( C<$field>, C<[$value1, $value2,...]>)
176  
177 This is the brains of the outfit, right here. The field must be a column in your table, and the values must be sent
178 in as a hashref. Easy and obvious.
179  
180 This method spins off methods in your Result and ResultSet classes for each value in your list, of the form
181 C<is_value>, which return a boolean (zero or one) if the current value of the enumerated field is the specified
182 value. If the field is nullable, you B<do not> get an C<is_undef> method. Yet. See LIMITATIONS below.
183  
184 =head2 enumerations_use_column_names()
185  
186 Calling this function will require the schema to create methods with the column name included. E.g. instead of
187 C<is_value>, you get C<fieldname_is_value> methods. It only operates on the Result class where you call it.
188  
189 =head1 DEPENDENCIES
190  
191 =over 4
192  
193 =item L<Carp>
194  
195 =item L<DBIx::Class>
196  
197 =item L<Modern::Perl>
198  
199 =item L<Sub::Quote>
200  
201 =back
202  
203 =head1 BUGS AND LIMITATIONS
204  
205 Bugs? What bugs? (No, really. If you find one, open an issue, please.)
206  
207 The following limitations are (currently) present:
208  
209 =over 4
210  
211 =item B<Text columns only!>:
212  
213 At present, you may only use this with text-based columns.
214  
215 =item B<Collisions>:
216  
217 If you have two enumerated fields in a table, and their lower-cased, underscore-punctuated
218 values collide, the code will choose the B<last> one that you defined with an C<enumerate>
219 statement. In this instance, you should probably use C<enumerations_use_column_names> to force
220 column names to be listed.
221  
222 If you have multiple enumerated values in a single field that collide on their lower-cased,
223 underscore-punctuated values, then B<any> of them will respond to test methods: e.g. if you
224 have C<BLUE> and C<blue> values in an enumeration, then C<is_blue> will be true for either one.
225 (...but why would you do that?)
226  
227 =item B<undef>
228  
229 If a field is nullable in the DB and the schema, you do not get an C<is_undef> method. Yet.
230  
231 =item B<Case-insensitive>
232  
233 To make the method name, this module replaces all non-alphanumeric characters with underscores,
234 and smashes case on all upper-case letters. This may contribute to collisions (see above).
235  
236 =item B<Adding to existing code>
237  
238 If you have an application where you add this module's functionality after there is data in
239 the table, it B<will not> complain about already-existing invalid values in enumerated fields.
240 You will not, of course, be able to test for those values, nor set any other record to that
241 value, unless you enumerate it.
242  
243 =back
244  
245 =head1 ROADMAP
246  
247 I have these features in mind, going forward.
248  
249 =over 4
250  
251 =item * Handle non-text columns
252  
253 =item * Automatically detect and force collision behavior
254  
255 =item * Add an C<is_undef> method for nullable fields
256  
257 =item * Option flag to make it work with case-sensitive enumerations
258  
259 =item * Method to hunt for 'invalid' values in the database and report
260  
261 =item * C<is_not_value> methods
262  
263 =back
264  
265 =head1 ACKNOWLEDGEMENTS
266  
267 My boss at Clearbuilt really, really dislikes enumerations. Hopefully, this module will make
268 them a bit easier for him to use.
269  
270 L<Jason Crome|https://metacpan.org/author/CROMEDOME> encourages this sort of craziness fairly
271 often.
272  
273 =head1 AUTHOR
274  
275 D Ruth Holloway <ruth@hiruthie.me>
276  
277 =head1 COPYRIGHT AND LICENSE
278  
279 This software is copyright (c) 2022 by D Ruth Holloway.
280  
281 This is free software; you can redistribute it and/or modify it under
282 the same terms as the Perl 5 programming language system itself.
283  
284 =cut