/
Base.pm
666 lines (510 loc) · 17.7 KB
/
Base.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
package Elastic::Model::TypeMap::Base;
use strict;
use warnings;
use Sub::Exporter qw(build_exporter);
use Class::MOP();
use List::MoreUtils qw(uniq);
use Moose::Util qw(does_role);
use Scalar::Util qw(blessed);
use Moose::Util::TypeConstraints qw(find_type_constraint);
use namespace::autoclean;
sub deflate_via (&) { deflator => $_[0] }
sub inflate_via (&) { inflator => $_[0] }
sub map_via (&) { mapper => $_[0] }
#===================================
sub import {
#===================================
my ( $class, @args ) = @_;
my $callee = caller;
return if $callee->isa(__PACKAGE__) || @args == 0;
{
no strict 'refs';
unshift @{ $callee . '::ISA' }, __PACKAGE__;
}
build_exporter( {
into => $callee,
exports => [
qw(deflate_via inflate_via map_via),
has_type => sub {
sub { $callee->_has_type(@_) }
},
]
}
)->( $class, ':all' );
for (@args) {
next if /^[:-]/;
Class::MOP::load_class($_);
$callee->import_types( $_->typemap );
}
}
#===================================
sub find_deflator {
#===================================
my ( $map, $attr ) = @_;
$attr->can('deflator') && $attr->deflator
|| eval { $map->find( 'deflator', $attr->type_constraint, $attr ) }
|| die _type_error( 'deflator', $attr, $@ );
}
#===================================
sub find_inflator {
#===================================
my ( $map, $attr ) = @_;
$attr->can('inflator') && $attr->inflator
|| eval { $map->find( 'inflator', $attr->type_constraint, $attr ) }
|| die _type_error( 'inflator', $attr, $@ );
}
#===================================
sub find_mapper {
#===================================
my ( $map, $attr ) = @_;
my $mapping;
$mapping = $attr->mapping if $attr->can('mapping');
return %$mapping if $mapping && %$mapping;
my %mapping;
eval {
my @mapping = $map->find( 'mapper', $attr->type_constraint, $attr );
die "Expected an even number of elements "
. "to be returned by the mapper.\n"
if @mapping % 2;
%mapping = @mapping;
};
die _type_error( 'mapper', $_[1], $@ )
unless %mapping;
return %mapping;
}
#===================================
sub _type_error {
#===================================
my ( $type, $attr, $error ) = @_;
my $name = $attr->name;
my $class = $attr->associated_class->name;
return $error
? "Error finding $type for attribute ($name) in class $class:\n$error"
: "No $type found for attribute ($name) in class $class";
}
#===================================
sub find {
#===================================
my ( $map, $type, $tc, $attr ) = @_;
$tc ||= find_type_constraint('Any');
my $types = $type . 's';
my $handlers = $map->$types;
my $name = $tc->name;
if ( my $handler = $handlers->{$name} || $handlers->{ ref $tc } ) {
return $handler->( $tc, $attr, $map );
}
my $parent = $tc->can('parent') && $tc->parent or return;
$map->find( $type, $parent, $attr );
}
#===================================
sub class_deflator {
#===================================
my ( $map, $class, $attrs ) = @_;
$attrs ||= $map->indexable_attrs($class);
my %deflators = map { $_ => $map->find_deflator( $attrs->{$_} ) }
keys %$attrs;
my $has_uid = $class->can('uid');
return sub {
my $obj = shift;
my %hash;
for ( keys %deflators ) {
my $attr = $attrs->{$_};
unless ( $attr->has_value($obj) ) {
next unless $attr->has_builder || $attr->has_default;
$attr->get_read_method_ref->($obj);
}
my $val = $attr->get_raw_value($obj);
eval { $hash{$_} = $deflators{$_}->($val); 1 } and next;
die "Error deflating attribute ($_) in class "
. blessed($obj) . ":\n "
. ( $@ || 'Unknown error' );
}
return \%hash;
};
}
#===================================
sub class_inflator {
#===================================
my ( $map, $class, $attrs ) = @_;
$attrs ||= $map->indexable_attrs($class);
my %inflators = map { $_ => $map->find_inflator( $attrs->{$_} ) }
keys %$attrs;
return sub {
my ( $obj, $hash ) = @_;
for ( keys %$hash ) {
my $attr = $attrs->{$_} or next;
my $val = $inflators{$_}->( $hash->{$_} );
$attr->set_raw_value( $obj, $val );
$attr->_weaken_value($obj) if $attr->is_weak_ref;
}
return $obj;
};
}
our %Allowed_Attrs = (
string => {
'index_name' => 1,
'store' => 1,
'index' => 1,
'term_vector' => 1,
'boost' => 1,
'null_value' => 1,
'omit_norms' => 1,
'omit_term_freq_and_positions' => 1,
'analyzer' => 1,
'index_analyzer' => 1,
'search_analyzer' => 1,
'search_quote_analyzer' => 1,
'include_in_all' => 1,
'multi' => 1,
},
integer => {
'index_name' => 1,
'store' => 1,
'index' => 1,
'precision_step' => 1,
'boost' => 1,
'null_value' => 1,
'include_in_all' => 1,
'multi' => 1,
},
date => {
'index_name' => 1,
'format' => 1,
'store' => 1,
'index' => 1,
'precision_step' => 1,
'boost' => 1,
'null_value' => 1,
'include_in_all' => 1,
'multi' => 1,
},
boolean => {
'index_name' => 1,
'store' => 1,
'index' => 1,
'boost' => 1,
'null_value' => 1,
'include_in_all' => 1,
'multi' => 1,
},
binary => {
'index_name' => 1,
'store' => 1
},
object => {
'dynamic' => 1,
'enabled' => 1,
'path' => 1,
'include_in_all' => 1,
},
nested => {
'include_in_parent' => 1,
'include_in_root' => 1,
'include_in_all' => 1,
'dynamic' => 1,
'path' => 1,
},
ip => {
'index_name' => 1,
'store' => 1,
'index' => 1,
'precision_step' => 1,
'boost' => 1,
'null_value' => 1,
'include_in_all' => 1,
'multi' => 1,
},
geo_point => {
'lat_lon' => 1,
'geohash' => 1,
'geohash_precision' => 1,
'index_name' => 1,
'store' => 1,
'multi' => 1,
},
# TODO: attachment => {}
);
our @All_Keys = uniq map { keys %$_ } values %Allowed_Attrs;
$Allowed_Attrs{$_} = $Allowed_Attrs{integer}
for qw(long float double short byte);
#===================================
sub class_mapping {
#===================================
my ( $map, $class, $attrs ) = @_;
$attrs ||= $map->indexable_attrs($class);
my %props = map { $_ => $map->attribute_mapping( $attrs->{$_} ) }
keys %$attrs;
return ( type => 'object', enabled => 0 )
unless %props;
return (
type => 'object',
dynamic => 'strict',
properties => \%props
);
}
#===================================
sub attribute_mapping {
#===================================
my ( $map, $attr ) = @_;
my $mapping = $attr->can('mapping') && $attr->mapping
|| { $map->find_mapper($attr) };
my $type = $mapping->{type} || '';
if ( $attr->can('type') ) {
my $new_type = $attr->type;
if ( $new_type and $new_type ne $type ) {
delete $mapping->{enabled}
if $type eq 'object';
$mapping->{type} = $type = $new_type;
}
}
die "Missing field type" unless $type;
my $allowed = $Allowed_Attrs{$type} or die "Unknown field type ($type)";
return $mapping unless does_role( $attr, 'Elastic::Model::Trait::Field' );
for my $key (@All_Keys) {
my $val = $attr->$key;
next unless defined $val;
die "Attribute has type '$type', which doesn't "
. "understand '$key'\n"
unless $allowed->{$key};
$mapping->{$key} = $val;
}
$mapping = $map->_fixup_mapping($mapping);
my $multi = delete $mapping->{multi}
or return $mapping;
my $main = $attr->name;
my %new = ( type => 'multi_field', fields => { $main => $mapping } );
for my $name ( keys %$multi ) {
die "Multi-field name '$name' clashes with the attribute name\n"
if $name eq $main;
my $defn = $multi->{$name};
my $multi_type = $defn->{type} ||= $type;
$allowed = $Allowed_Attrs{$multi_type}
or die "Uknown field type ($type)";
for my $key ( keys %$defn ) {
die "Attribute has type '$multi_type', which doesn't "
. "understand '$key'\n"
unless $allowed->{$key} || $key eq 'type';
}
$new{fields}{$name} = $map->_fixup_mapping($defn);
}
return \%new;
}
#===================================
sub _fixup_mapping {
#===================================
my ( $map, $defn ) = @_;
delete $defn->{analyzer}
if $defn->{index_analyzer} && $defn->{search_analyzer};
# make 'undef' a false value for boolean fields
$defn->{null_value} = 0
if $defn->{type} eq 'boolean'
and not exists $defn->{null_value};
return $defn;
}
#===================================
sub deflators { shift->typemap->{deflator} }
sub inflators { shift->typemap->{inflator} }
sub mappers { shift->typemap->{mapper} }
#===================================
#===================================
sub _has_type {
#===================================
my ( $class, $type, %params ) = @_;
my $map = $class->typemap();
for ( keys %params ) {
$map->{$_}{$type} = $params{$_};
}
}
#===================================
sub indexable_attrs {
#===================================
my $map = shift;
my $class = shift;
$class = $map->model->class_for($class) || $class;
my $meta = Class::MOP::class_of($class);
return {
map { $_->name => $_ }
grep { !( $_->can('exclude') && $_->exclude ) }
$meta->get_all_attributes
};
}
#===================================
sub typemap {
#===================================
my $class = shift;
$class = $class->original_class
if $class->can('original_class');
# return a reference to the storage in ourself
{
no strict 'refs';
return \%{ $class . '::__ES_TYPE_MAP' };
}
}
#===================================
sub import_types {
#===================================
my $class = shift;
my $import = shift;
my $map = $class->typemap;
for (qw(deflator inflator mapper)) {
my $types = $import->{$_} or next;
@{ $map->{$_} }{ keys %$types } = values %$types;
}
}
1;
__END__
# ABSTRACT: A base class for all TypeMaps
=head1 SYNOPSIS
=head2 Define your own type map
package MyApp::TypeMap;
use Elastic::Model::TypeMap::Base qw(
Elastic::Model::TypeMap::Default
);
has_type 'MyCustomType',
deflate_via { sub { ... }},
inflate_via { sub { ... }},
map_via { type => 'string' };
=head2 Use your type map by declaring it in your Model
package MyApp;
use Elastic::Model;
has_namespace 'myapp', {
user => 'MyApp::User',
post => 'MyApp::Post'
};
has_typemap 'MyApp::TypeMap';
=head1 DESCRIPTION
Moose's L<type constraints|Moose::Util::TypeConstraints> and introspection
allows Elastic::Model to figure out how to map your data model to the
ElasticSearch backend with the minimum of effort on your part.
What YOU need to do is: B<Be specific about the type constraint for each attribute.>
For instance, if you have an attribute called C<count>, then specify the
type constraint C<< isa => 'Int' >>.
That way, we know how to define the field in ElasticSearch, and how to deflate
and inflate the value.
Type constraints can inherit their mapping, inflator and deflator from
their parent type-constraints. For instance, if you were to assign
C<count> the type constraint C<PositiveInt>, although we don't know about that
constraint, we do know about its parent, C<Int>, so we could
still handle the field correctly.
Type maps are used to define:
=over
=item *
what mapping Elastic::Model will generate for each attribute when you
L<create an index|Elastic::Model::Domain::Admin/"create_index()">
or L<update the mapping|Elastic::Model::Domain::Admin/"update_mapping()"> of an
existing index.
=item *
how Elastic::Model will deflate and inflate each attribute when saving or
retrieving docs stored in ElasticSearch.
=back
=head1 BUILT-IN TYPE MAPS
See L<Elastic::Model::TypeMap::Default> for the type-maps provided by
default in Elastic::Model.
=head1 DEFINING YOUR OWN TYPE MAP
If you define your own types which need custom mapping or custom deflators/inflators
then you can add these definitions in your own type-map, while still falling
back to the built-in type-maps for other types.
First, you need to name your type map class:
package MyApp::TypeMap;
Then import the helper functions from L<Elastic::Model::TypeMap::Base>
and load any other typemaps that you want to inherit from:
use Elastic::Model::TypeMap::Base qw(
Elastic::Model::TypeMap::Default
Useful::TypeMap::From::CPAN
);
Now you can define your type maps:
has_type 'MyCustomType',
deflate_via { sub { ... }},
inflate_via { sub { ... }},
map_via { type => 'string' };
The type name passed to C<has_type> should be a string, eg C<'Str'> for the
core Moose string type, or the fully qualified name for the types you have
defined with L<MooseX::Types>, eg C<'MyApp::Types::SomeType'>.
C<deflate_via> and C<inflate_via> each expect a coderef which, when called
returns a coderef:
sub {
my ($type_constraint, $attr, $typemap_class) = @_;
return sub {
my ($val) = @_;
return do_something($val)
}
}
C<map_via> expects a coderef which returns the mapping for that type as a list,
not as a hashref:
sub {
my ($type_constraint, $attr, $typemap_class) = @_;
return (type => 'string', ..... );
}
=head2 A simple example
Here is an example of how to define a type map for DateTime objects:
use DateTime;
has_type 'DateTime',
deflate_via {
sub { $_[0]->set_time_zone('UTC')->iso8601 };
},
inflate_via {
sub {
my %args;
@args{ (qw(year month day hour minute second)) } = split /\D/, shift;
DateTime->new(%args);
};
},
map_via { type => 'date' };
=head1 ATTRIBUTES
It is unlikely that you will need to know about any of these attributes, but
they are documented here for completeness.
=head2 deflators
$deflators = $class->deflators
Returns a hashref of all deflators known to C<$class>.
=head2 inflators
$inflators = $class->inflators
Returns a hashref of all inflators known to C<$class>.
=head2 mappers
$mappers = $class->mappers
Returns a hashref of all mappers known to C<$class>.
=head2 typemap
$map = $class->typemap
Returns a hashref containing the L</"deflators">, L</"inflators"> and
L</"mappers"> known to C<$class>.
=head1 METHODS
It is unlikely that you will need to know about any of these methods, but
they are documented here for completeness.
L<Elastic::Model::TypeMap::Base> only has class methods, no instance methods,
and no C<new()>.
=head2 find_deflator()
$deflator = $class->find_deflator($attr)
Returns a coderef which knows how to deflate C<$attr>, or throws an exception.
=head2 find_inflator()
$inflator = $class->find_inflator($attr)
Returns a coderef which knows how to inflate C<$attr>, or throws an exception.
=head2 find_mapper()
$mapping = $class->find_mapper($attr)
Returns a mapping for C<$attr>, or throws an exception.
=head2 find()
$result = $class->find($thing, $type_constraint, $attr);
Finds a C<$thing> (C<deflator>, C<inflator>, C<mapper>) or returns C<undef>.
=head2 class_deflator()
$deflator = $class->class_deflator( $class_to_deflate, $attrs );
Returns a coderef which knows how to deflate an object of class
C<$class_to_deflate>, including the attributes listed in C<$attr> (or all
attributes if not specified).
=head2 class_inflator()
$inflator = $class->class_inflator( $class_to_inflate, $attrs );
Returns a coderef which knows how to inflate deflated data for class
C<$class_to_inflate>, including the attributes listed in C<$attr> (or all
attributes if not specified).
=head2 class_mapping()
$mapping = $class->class_mapping( $class_to_map, $attrs );
Returns a hashref of the mapping for class C<$class_to_map>,
including the attributes listed in C<$attr> (or all attributes if not specified).
=head2 attribute_mapping()
$mapping = $class->attribute_mapping($attr);
Returns a hashref of the mapping for attribute C<$attr>.
=head2 indexable_attrs()
$attrs = $class->indexable_attrs($some_class);
Returns an array ref all all attributes in C<$some_class> which don't
have C<exclude> set to true.
=head2 import_types()
$class->import_types($other_class);
Imports the deflators, inflators and mappers from another typemap class into
the current class.