File Coverage

blib/lib/DR/Tarantool/Spaces.pm
Criterion Covered Total %
statement 252 262 96.1
branch 125 182 68.6
condition 24 52 46.1
subroutine 34 35 97.1
pod 7 7 100.0
total 442 538 82.1


line stmt bran cond sub pod time code
1 10     10   106946 use utf8;
  10         18  
  10         75  
2 10     10   269 use strict;
  10         33  
  10         296  
3 10     10   46 use warnings;
  10         19  
  10         391  
4              
5             package DR::Tarantool::Spaces;
6 10     10   53 use Carp;
  10         18  
  10         7991  
7             $Carp::Internal{ (__PACKAGE__) }++;
8              
9             my $LE = $] > 5.01 ? '<' : '';
10              
11             =head1 NAME
12              
13             DR::Tarantool::Spaces - Tarantool schema description
14              
15             =head1 SYNOPSIS
16              
17             use DR::Tarantool::Spaces;
18             my $s = new DR::Tarantool::Spaces({
19             1 => {
20             name => 'users', # space name
21             default_type => 'STR', # undescribed fields
22             fields => [
23             qw(login password role),
24             {
25             name => 'counter',
26             type => 'NUM'
27             },
28             {
29             name => 'something',
30             type => 'UTF8STR',
31             },
32             {
33             name => 'opts',
34             type => 'JSON',
35             }
36             ],
37             indexes => {
38             0 => 'login',
39             1 => [ qw(login password) ],
40             2 => {
41             name => 'my_idx',
42             fields => 'login',
43             },
44             3 => {
45             name => 'my_idx2',
46             fields => [ 'counter', 'something' ]
47             }
48             }
49             },
50              
51             0 => {
52             ...
53             }
54             });
55              
56             my $f = $s->pack_field('users', 'counter', 10);
57             my $f = $s->pack_field('users', 3, 10); # the same
58             my $f = $s->pack_field(1, 3, 10); # the same
59              
60             my $ts = $s->pack_keys([1,2,3] => 'my_idx');
61             my $t = $s->pack_primary_key([1,2,3]);
62              
63              
64             =head1 DESCRIPTION
65              
66             The package describes all spaces used in an application.
67             It supports the following field types:
68              
69             =over
70              
71             =item NUM, NUM64, STR
72              
73             The standard L<Tarantool|http://tarantool.org> types.
74              
75             =item UTF8STR
76              
77             The same as B<STR>, but the string is utf8-decoded
78             after it's received from the server.
79              
80             =item INT & INT64
81              
82             The same as B<NUM> and B<NUM64>, but contain signed values.
83              
84             =item JSON
85              
86             The field is encoded with L<JSON::XS> when putting
87             into a database, and decoded after is received back
88             from the server.
89              
90             =back
91              
92             =head1 METHODS
93              
94             =head2 new
95              
96             my $spaces = DR::Tarantool::Spaces->new( $spaces );
97              
98             =cut
99              
100             sub new {
101 5     5 1 898 my ($class, $spaces) = @_;
102 5 100       14 $spaces = {} unless defined $spaces;
103 5 100       205 croak 'spaces must be a HASHREF' unless 'HASH' eq ref $spaces;
104              
105 4         5 my (%spaces, %fast);
106 4         14 for (keys %$spaces) {
107 4         21 my $s = new DR::Tarantool::Space($_ => $spaces->{ $_ });
108 3         14 $spaces{ $s->name } = $s;
109 3         7 $fast{ $_ } = $s->name;
110             }
111              
112 3   33     34 return bless {
113             spaces => \%spaces,
114             fast => \%fast,
115             } => ref($class) || $class;
116             }
117              
118              
119             =head2 space
120              
121             Return space object by number or name.
122              
123             my $space = $spaces->space('name');
124             my $space = $spaces->space(0);
125              
126             =cut
127              
128             sub space {
129 92     92 1 32367 my ($self, $space) = @_;
130 92 100       323 croak 'space name or number is not defined' unless defined $space;
131 91 100       255 if ($space =~ /^\d+$/) {
132 6 50       21 croak "space '$space' is not defined"
133             unless exists $self->{fast}{$space};
134 6         31 return $self->{spaces}{ $self->{fast}{$space} };
135             }
136 85 50       219 croak "space '$space' is not defined"
137             unless exists $self->{spaces}{$space};
138 85         397 return $self->{spaces}{$space};
139             }
140              
141              
142             =head2 space_number
143              
144             Return space number by its name.
145              
146             =cut
147              
148             sub space_number {
149 3     3 1 815 my ($self, $space) = @_;
150 3         8 return $self->space($space)->number;
151             }
152              
153              
154             =head2 pack_field
155              
156             Packs one field into a format suitable for making a database request:
157              
158             my $field = $spaces->pack_field('space', 'field', $data);
159              
160             =cut
161              
162             sub pack_field {
163 23     23 1 14945 my ($self, $space, $field, $value) = @_;
164 23 50       62 croak q{Usage: $spaces->pack_field('space', 'field', $value)}
165             unless @_ == 4;
166 23         57 return $self->space($space)->pack_field($field => $value);
167             }
168              
169              
170             =head2 unpack_field
171              
172             Unpack one field after getting it from the server:
173              
174             my $field = $spaces->unpack_field('space', 'field', $data);
175              
176             =cut
177              
178             sub unpack_field {
179 19     19 1 10143 my ($self, $space, $field, $value) = @_;
180 19 50       54 croak q{Usage: $spaces->unpack_field('space', 'field', $value)}
181             unless @_ == 4;
182              
183 19         42 return $self->space($space)->unpack_field($field => $value);
184             }
185              
186              
187             =head2 pack_tuple
188              
189             Pack a tuple before making database request.
190              
191             my $t = $spaces->pack_tuple('space', [ 1, 2, 3 ]);
192              
193             =cut
194              
195             sub pack_tuple {
196 1     1 1 478 my ($self, $space, $tuple) = @_;
197 1 50       5 croak q{Usage: $spaces->pack_tuple('space', $tuple)} unless @_ == 3;
198 1         3 return $self->space($space)->pack_tuple( $tuple );
199             }
200              
201              
202             =head2 unpack_tuple
203              
204             Unpack a tuple after getting it from the database:
205              
206             my $t = $spaces->unpack_tuple('space', \@fields);
207              
208             =cut
209              
210             sub unpack_tuple {
211 1     1 1 409 my ($self, $space, $tuple) = @_;
212 1 50       4 croak q{Usage: $spaces->unpack_tuple('space', $tuple)} unless @_ == 3;
213 1         4 return $self->space($space)->unpack_tuple( $tuple );
214             }
215              
216             package DR::Tarantool::Space;
217 10     10   84 use Carp;
  10         25  
  10         664  
218             $Carp::Internal{ (__PACKAGE__) }++;
219 10     10   11816 use JSON::XS ();
  10         85455  
  10         290  
220 10     10   89 use Digest::MD5 ();
  10         20  
  10         11139  
221              
222              
223             =head1 SPACES methods
224              
225             =head2 new
226              
227             constructor
228              
229             use DR::Tarantool::Spaces;
230             my $space = DR::Tarantool::Space->new($no, $space);
231              
232             =cut
233              
234             sub new {
235 4     4   7 my ($class, $no, $space) = @_;
236 4 100 66     139 croak 'space number must conform the regexp qr{^\d+}'
237             unless defined $no and $no =~ /^\d+$/;
238 3 50       12 croak "'fields' not defined in space hash"
239             unless 'ARRAY' eq ref $space->{fields};
240 3 50 33     20 croak "wrong 'indexes' hash"
241             if !$space->{indexes} or 'HASH' ne ref $space->{indexes};
242              
243 3         7 my $name = $space->{name};
244 3 0 33     21 croak 'wrong space name: ' . (defined($name) ? $name : 'undef')
    50          
245             unless $name and $name =~ /^[a-z_]\w*$/i;
246              
247              
248 3         11 my $fqr = qr{^(?:STR|NUM|NUM64|INT|INT64|UTF8STR|JSON|MONEY|BIGMONEY)$};
249              
250 3         5 my (@fields, %fast, $default_type);
251 3   100     12 $default_type = $space->{default_type} || 'STR';
252 3 50       19 croak "wrong 'default_type'" unless $default_type =~ $fqr;
253              
254 3         4 for (my $no = 0; $no < @{ $space->{fields} }; $no++) {
  18         42  
255 15         24 my $f = $space->{ fields }[ $no ];
256              
257 15 100       38 if (ref $f eq 'HASH') {
    50          
258 9   33     40 push @fields => {
259             name => $f->{name} || "f$no",
260             idx => $no,
261             type => $f->{type}
262             };
263             } elsif(ref $f) {
264 0         0 croak 'wrong field name or description';
265             } else {
266 6         23 push @fields => {
267             name => $f,
268             idx => $no,
269             type => $default_type,
270             }
271             }
272              
273 15         16 my $s = $fields[ -1 ];
274 15 0 33     107 croak 'unknown field type: ' .
    50          
275             (defined($s->{type}) ? $s->{type} : 'undef')
276             unless $s->{type} and $s->{type} =~ $fqr;
277              
278 15 0 33     83 croak 'wrong field name: ' .
    50          
279             (defined($s->{name}) ? $s->{name} : 'undef')
280             unless $s->{name} and $s->{name} =~ /^[a-z_]\w*$/i;
281              
282 15 50       33 croak "Duplicate field name: $s->{name}" if exists $fast{ $s->{name} };
283 15         42 $fast{ $s->{name} } = $no;
284             }
285              
286 3         18 my %indexes;
287 3 50       12 if ($space->{indexes}) {
288 3         4 for my $no (keys %{ $space->{indexes} }) {
  3         12  
289 6         12 my $l = $space->{indexes}{ $no };
290 6 50       24 croak "wrong index number: $no" unless $no =~ /^\d+$/;
291              
292 6         8 my ($name, $fields);
293              
294 6 100       21 if ('ARRAY' eq ref $l) {
    100          
295 2         4 $name = "i$no";
296 2         4 $fields = $l;
297             } elsif ('HASH' eq ref $l) {
298 1   33     3 $name = $l->{name} || "i$no";
299 1         2 $fields =
300 1 50       4 [ ref($l->{fields}) ? @{ $l->{fields} } : $l->{fields} ];
301             } else {
302 3         5 $name = "i$no";
303 3         6 $fields = [ $l ];
304             }
305              
306 6 50       24 croak "wrong index name: $name" unless $name =~ /^[a-z_]\w*$/i;
307              
308 6         12 for (@$fields) {
309 10 50       26 croak "field '$_' is presend in index but isn't in fields"
310             unless exists $fast{ $_ };
311             }
312              
313 6         34 $indexes{ $name } = {
314             no => $no,
315             name => $name,
316             fields => $fields
317             };
318              
319             }
320             }
321              
322 3         43 my $tuple_class = 'DR::Tarantool::Tuple::Instance' .
323             Digest::MD5::md5_hex( join "\0", sort keys %fast );
324              
325 3   33     42 bless {
326             fields => \@fields,
327             fast => \%fast,
328             name => $name,
329             number => $no,
330             default_type => $default_type,
331             indexes => \%indexes,
332             tuple_class => $tuple_class,
333             } => ref($class) || $class;
334              
335             }
336              
337              
338             =head2 tuple_class
339              
340             Create (or return) a class to hold tuple data.
341             The class is a descendant of L<DR::Tarantool::Tuple>. Returns a unique class
342             (package) name. If a package with such name is already exists, the method
343             doesn't recreate it.
344              
345             =cut
346              
347             sub tuple_class {
348 11     11   20 my ($self) = @_;
349 11         32 my $class = $self->{tuple_class};
350              
351              
352 10     10   232 no strict 'refs';
  10         59  
  10         27876  
353 11 100       13 return $class if ${ $class . '::CREATED' };
  11         84  
354              
355 3 50   2   246 die unless eval "package $class; use base 'DR::Tarantool::Tuple'; 1";
  2     1   20  
  2         4  
  2         1238  
  1         8  
  1         53  
  1         85  
356              
357 3         8 for my $fname (keys %{ $self->{fast} }) {
  3         19  
358 15         31 my $fnumber = $self->{fast}{$fname};
359              
360 15         930 *{ $class . '::' . $fname } = eval "sub { \$_[0]->raw($fnumber) }";
  15         109  
361             }
362              
363 3         26 ${ $class . '::CREATED' } = time;
  3         13  
364              
365 3         14 return $class;
366             }
367              
368              
369             =head2 name
370              
371             Get a space name.
372              
373             =cut
374              
375 13     13   774 sub name { $_[0]{name} }
376              
377              
378             =head2 number
379              
380             Get a space number.
381              
382             =cut
383              
384 2     2   8 sub number { $_[0]{number} }
385              
386             sub _field {
387 106     105   129 my ($self, $field) = @_;
388              
389 106 50       191 croak 'field name or number is not defined' unless defined $field;
390 109 100       293 if ($field =~ /^\d+$/) {
391 20 50       21 return $self->{fields}[ $field ] if $field < @{ $self->{fields} };
  20         74  
392 0         0 return undef;
393             }
394 85 50       187 croak "field with name '$field' is not defined in this space"
395             unless exists $self->{fast}{$field};
396 85         208 return $self->{fields}[ $self->{fast}{$field} ];
397             }
398              
399              
400             =head2 field_number
401              
402             Return field index by field name.
403              
404             =cut
405              
406             sub field_number {
407 4     4   6 my ($self, $field) = @_;
408 4 50       7 croak 'field name or number is not defined' unless defined $field;
409 4 100       22 return $self->{fast}{$field} if exists $self->{fast}{$field};
410 1         92 croak "Can't find field '$field' in this space";
411             }
412              
413              
414             =head2 tail_index
415              
416             Return index of the first element that is not described in the space.
417              
418             =cut
419              
420             sub tail_index {
421 3     3   4 my ($self) = @_;
422 3         7 return scalar @{ $self->{fields} };
  3         32  
423             }
424              
425              
426             =head2 pack_field
427              
428             Pack a field before making a database request.
429              
430             =cut
431              
432             sub pack_field {
433 52     52   70 my ($self, $field, $value) = @_;
434 52 50       104 croak q{Usage: $space->pack_field('field', $value)}
435             unless @_ == 3;
436              
437 52         93 my $f = $self->_field($field);
438              
439 52 50       126 my $type = $f ? $f->{type} : $self->{default_type};
440              
441 52 100       97 if ($type eq 'JSON') {
442 8         12 my $v = eval { JSON::XS->new->allow_nonref->utf8->encode( $value ) };
  8         86  
443 8 50       32 croak "Can't pack json: $@" if $@;
444 8         29 return $v;
445             }
446              
447 44         57 my $v = $value;
448 44 100       107 utf8::encode( $v ) if utf8::is_utf8( $v );
449 44 100 100     227 return $v if $type eq 'STR' or $type eq 'UTF8STR';
450 37 100       216 return pack "L$LE" => $v if $type eq 'NUM';
451 8 100       27 return pack "l$LE" => $v if $type eq 'INT';
452 7 50       25 return pack "Q$LE" => $v if $type eq 'NUM64';
453 7 50       17 return pack "q$LE" => $v if $type eq 'INT64';
454              
455 7 50 33     18 if ($type eq 'MONEY' or $type eq 'BIGMONEY') {
456 7         22 my ($r, $k) = split /\./, $v;
457 7         18 for ($k) {
458 7 100       15 $_ = '.00' unless defined $_;
459 7         17 s/^\.//;
460 7 100       18 $_ .= '0' if length $_ < 2;
461 7         20 $_ = substr $_, 0, 2;
462             }
463 7   100     24 $r ||= 0;
464              
465 7 100       14 if ($r < 0) {
466 2         6 $v = $r * 100 - $k;
467             } else {
468 5         13 $v = $r * 100 + $k;
469             }
470              
471 7 50       53 return pack "l$LE", $v if $type eq 'MONEY';
472 0         0 return pack "q$LE", $v;
473             }
474              
475              
476 0         0 croak 'Unknown field type:' . $type;
477             }
478              
479              
480             =head2 unpack_field
481              
482             Unpack a single field in a server response.
483              
484             =cut
485              
486             sub unpack_field {
487 27     27   43 my ($self, $field, $value) = @_;
488 27 50       81 croak q{Usage: $space->pack_field('field', $value)}
489             unless @_ == 3;
490              
491 27         54 my $f = $self->_field($field);
492              
493 27 50       72 my $type = $f ? $f->{type} : $self->{default_type};
494              
495 27         29 my $v = $value;
496 27 100       73 utf8::encode( $v ) if utf8::is_utf8( $v );
497              
498 27 100       53 if ($type eq 'JSON') {
499 8         86 $v = JSON::XS->new->allow_nonref->utf8->decode( $v );
500 8 50       29 croak "Can't unpack json: $@" if $@;
501 8         37 return $v;
502             }
503              
504 19 100       60 $v = unpack "L$LE" => $v if $type eq 'NUM';
505 19 100       42 $v = unpack "l$LE" => $v if $type eq 'INT';
506 19 50       31 $v = unpack "Q$LE" => $v if $type eq 'NUM64';
507 19 50       34 $v = unpack "q$LE" => $v if $type eq 'INT64';
508 19 100       34 utf8::decode( $v ) if $type eq 'UTF8STR';
509 19 100 66     89 if ($type eq 'MONEY' or $type eq 'BIGMONEY') {
510 4 50       18 $v = unpack "l$LE" => $v if $type eq 'MONEY';
511 4 50       9 $v = unpack "q$LE" => $v if $type eq 'BIGMONEY';
512 4         6 my $s = '';
513 4 100       11 if ($v < 0) {
514 1         3 $v = -$v;
515 1         2 $s = '-';
516             }
517 4         11 my $k = $v % 100;
518 4         8 my $r = ($v - $k) / 100;
519 4         21 $v = sprintf '%s%d.%02d', $s, $r, $k;
520             }
521 19         63 return $v;
522             }
523              
524              
525             =head2 pack_tuple
526              
527             Pack a tuple to the binary protocol format:
528              
529             =cut
530              
531             sub pack_tuple {
532 1     1   2 my ($self, $tuple) = @_;
533 1 50       3 croak 'tuple must be ARRAYREF' unless 'ARRAY' eq ref $tuple;
534 1         2 my @res;
535 1         5 for (my $i = 0; $i < @$tuple; $i++) {
536 6         15 push @res => $self->pack_field($i, $tuple->[ $i ]);
537             }
538 1         3 return \@res;
539             }
540              
541              
542             =head2 unpack_tuple
543              
544             Unpack a tuple in a server response.
545              
546             =cut
547              
548             sub unpack_tuple {
549 2     2   4 my ($self, $tuple) = @_;
550 2 50       8 croak 'tuple must be ARRAYREF' unless 'ARRAY' eq ref $tuple;
551 2         4 my @res;
552 2         8 for (my $i = 0; $i < @$tuple; $i++) {
553 8         63 push @res => $self->unpack_field($i, $tuple->[ $i ]);
554             }
555 2         12 return \@res;
556             }
557              
558              
559             sub _index {
560 16     16   25 my ($self, $index) = @_;
561 16 100       56 if ($index =~ /^\d+$/) {
562 5         9 for (values %{ $self->{indexes} }) {
  5         14  
563 17 100       45 return $_ if $_->{no} == $index;
564             }
565 0         0 croak "index $index is undefined";
566             }
567              
568 11 100       45 return $self->{indexes}{$index} if exists $self->{indexes}{$index};
569 1         82 croak "index `$index' is undefined";
570             }
571              
572              
573             =head2 index_number
574              
575             returns index number by its name.
576              
577             =cut
578              
579             sub index_number {
580 4     4   7 my ($self, $idx) = @_;
581 4 100       101 croak "index name is undefined" unless defined $idx;
582 3         7 return $self->_index( $idx )->{no};
583             }
584              
585              
586             =head2 index_name
587              
588             returns index name by its number.
589              
590             =cut
591              
592             sub index_name {
593 2     2   3 my ($self, $idx) = @_;
594 2 50       6 croak "index number is undefined" unless defined $idx;
595 2         6 return $self->_index( $idx )->{name};
596             }
597              
598              
599             sub pack_keys {
600 11     11   18 my ($self, $keys, $idx, $disable_warn) = @_;
601              
602 11         25 $idx = $self->_index($idx);
603 11         12 my $ksize = @{ $idx->{fields} };
  11         23  
604              
605 11 100       34 $keys = [[ $keys ]] unless 'ARRAY' eq ref $keys;
606 11 100       26 unless('ARRAY' eq ref $keys->[0]) {
607 4 100       8 if ($ksize == @$keys) {
608 3         8 $keys = [ $keys ];
609 3 100 66     264 carp "Ambiguous keys list (it was used as ONE key), ".
610             "Use brackets to solve the trouble."
611             if $ksize > 1 and !$disable_warn;
612             } else {
613 1         3 $keys = [ map { [ $_ ] } @$keys ];
  3         6  
614             }
615             }
616              
617 11         136 my @res;
618 11         17 for my $k (@$keys) {
619 13 100       314 croak "key must have $ksize elements" unless $ksize >= @$k;
620 10         7 my @packed;
621 10         22 for (my $i = 0; $i < @$k; $i++) {
622 14         35 my $f = $self->_field($idx->{fields}[$i]);
623 14         40 push @packed => $self->pack_field($f->{name}, $k->[$i])
624             }
625 10         26 push @res => \@packed;
626             }
627 8         30 return \@res;
628             }
629              
630             sub pack_primary_key {
631 0     0   0 my ($self, $key) = @_;
632              
633 0 0 0     0 croak 'wrong key format'
634             if 'ARRAY' eq ref $key and 'ARRAY' eq ref $key->[0];
635              
636 0         0 my $t = $self->pack_keys($key, 0, 1);
637 0         0 return $t->[0];
638             }
639              
640             sub pack_operation {
641 12     12   18 my ($self, $op) = @_;
642 12 50 33     60 croak 'wrong operation' unless 'ARRAY' eq ref $op and @$op > 1;
643              
644 12         20 my $fno = $op->[0];
645 12         13 my $opname = $op->[1];
646              
647 12         24 my $f = $self->_field($fno);
648              
649 12 100       32 if ($opname eq 'delete') {
650 1 50       4 croak 'wrong operation' unless @$op == 2;
651 1         5 return [ $f->{idx} => $opname ];
652             }
653              
654 11 100       43 if ($opname =~ /^(?:set|insert|add|and|or|xor)$/) {
655 9 50       52 croak 'wrong operation' unless @$op == 3;
656 9         39 return [ $f->{idx} => $opname, $self->pack_field($fno, $op->[2]) ];
657             }
658              
659 2 50       6 if ($opname eq 'substr') {
660 2 50       6 croak 'wrong operation11' unless @$op >= 4;
661 2 50       11 croak 'wrong offset in substr operation' unless $op->[2] =~ /^\d+$/;
662 2 50       8 croak 'wrong length in substr operation' unless $op->[3] =~ /^\d+$/;
663 2         10 return [ $f->{idx}, $opname, $op->[2], $op->[3], $op->[4] ];
664             }
665 0         0 croak "unknown operation: $opname";
666             }
667              
668             sub pack_operations {
669 2     2   3 my ($self, $ops) = @_;
670              
671 2 50 33     16 croak 'wrong operation' unless 'ARRAY' eq ref $ops and @$ops >= 1;
672 2 100       9 $ops = [ $ops ] unless 'ARRAY' eq ref $ops->[ 0 ];
673              
674 2         3 my @res;
675 2         10 push @res => $self->pack_operation( $_ ) for @$ops;
676 2         8 return \@res;
677             }
678              
679             =head1 COPYRIGHT AND LICENSE
680              
681             Copyright (C) 2011 Dmitry E. Oboukhov <unera@debian.org>
682             Copyright (C) 2011 Roman V. Nikolaev <rshadow@rambler.ru>
683              
684             This program is free software, you can redistribute it and/or
685             modify it under the terms of the Artistic License.
686              
687             =head1 VCS
688              
689             The project is placed git repo on github:
690             L<https://github.com/dr-co/dr-tarantool/>.
691              
692             =cut
693              
694             1;