« QBit/Application/Model/DBManager/_Utils/Fields.pm
↑ Summary
QBit/Application/Model/DBManager/Filter/dictionary.pm »
| 1 | |||
| 2 | =encoding utf8 | ||
| 3 | |||
| 4 | =head1 Name | ||
| 5 | |||
| 6 | QBit::Application::Model::DBManager - Class for smart working with DB. | ||
| 7 | |||
| 8 | =head1 GitHub | ||
| 9 | |||
| 10 | https://github.com/QBitFramework/QBit-Application-Model-DBManager | ||
| 11 | |||
| 12 | =head1 Install | ||
| 13 | |||
| 14 | =over | ||
| 15 | |||
| 16 | =item * | ||
| 17 | |||
| 18 | cpanm QBit::Application::Model::DBManager | ||
| 19 | |||
| 20 | =item * | ||
| 21 | |||
| 22 | apt-get install libqbit-application-model-dbmanager-perl (http://perlhub.ru/) | ||
| 23 | |||
| 24 | =back | ||
| 25 | |||
| 26 | For more information. please, see code. | ||
| 27 | |||
| 28 | =head1 Package methods | ||
| 29 | |||
| 30 | =cut | ||
| 31 | |||
| 32 | package QBit::Application::Model::DBManager; | ||
| 33 | $QBit::Application::Model::DBManager::VERSION = '0.020'; | ||
| 34 | use qbit; | ||
| 35 | |||
| 36 | use base qw(QBit::Application::Model); | ||
| 37 | |||
| 38 | use QBit::Application::Model::DBManager::_Utils::Fields; | ||
| 39 | use QBit::Application::Model::DBManager::Filter; | ||
| 40 | |||
| 41 | use Parse::Eyapp; | ||
| 42 | |||
| 43 | use Exception::DBManager::Grammar; | ||
| 44 | |||
| 45 | __PACKAGE__->abstract_methods(qw(query add)); | ||
| 46 | |||
| 47 | =head2 init | ||
| 48 | |||
| 49 | Initialization model. | ||
| 50 | |||
| 51 | B<It is done:> | ||
| 52 | |||
| 53 | =over | ||
| 54 | |||
| 55 | =item | ||
| 56 | |||
| 57 | Init fields | ||
| 58 | |||
| 59 | =back | ||
| 60 | |||
| 61 | B<No arguments.> | ||
| 62 | |||
| 63 | B<Example:> | ||
| 64 | |||
| 65 | my $model = Application::Model->new(); # Application::Model based on QBit::Application::Model | ||
| 66 | |||
| 67 | # but usually this is used so | ||
| 68 | |||
| 69 | package Application; | ||
| 70 | |||
| 71 | use base qw(QBit::Application); | ||
| 72 | |||
| 73 | __Package__->set_accessors(model => {package => 'Application::Model'}); | ||
| 74 | |||
| 75 | ... | ||
| 76 | |||
| 77 | # after | ||
| 78 | |||
| 79 | my $model = $app->model; | ||
| 80 | |||
| 81 | =cut | ||
| 82 | |||
| 83 | sub init { | ||
| 84 | my ($self) = @_; | ||
| 85 | |||
| 86 | $self->SUPER::init(); | ||
| 87 | |||
| 88 | $self->init_fields(); | ||
| 89 | } | ||
| 90 | |||
| 91 | =head2 model_fields | ||
| 92 | |||
| 93 | Set model fields. Save into package stash with key __MODEL_FIELDS__ | ||
| 94 | |||
| 95 | B<Arguments:> | ||
| 96 | |||
| 97 | =over | ||
| 98 | |||
| 99 | =item * | ||
| 100 | |||
| 101 | B<%fields> - Fields (type: hash) | ||
| 102 | |||
| 103 | =back | ||
| 104 | |||
| 105 | B<Example:> | ||
| 106 | |||
| 107 | package Sellers; | ||
| 108 | |||
| 109 | use base qw(QBit::Application::Model::DBManager); | ||
| 110 | |||
| 111 | __PACKAGE__->model_accessors( | ||
| 112 | db => 'Application::Model::DB', # your DB model, see QBit::Application::Model::DB | ||
| 113 | items => 'Application::Model::Items', # your model (base from QBit::Application::Model::DBManager) | ||
| 114 | ); | ||
| 115 | |||
| 116 | __PACKAGE__->model_fields( | ||
| 117 | id => { | ||
| 118 | pk => TRUE, # primary key for this model | ||
| 119 | db => 'sellers', # this field is from the table | ||
| 120 | default => TRUE, # this field returns if fields were not requested | ||
| 121 | }, | ||
| 122 | caption => { | ||
| 123 | db => 'sellers', # this field is from the table | ||
| 124 | default => TRUE, # this field returns if fields were not requested | ||
| 125 | i18n => TRUE, # this field depends on current locale, (in DB this field i18n too) | ||
| 126 | check_rights => 'sellers_view_field__caption', | ||
| 127 | # your right for "caption", see check_rights from QBit::Application | ||
| 128 | # Try not to use this key. | ||
| 129 | }, | ||
| 130 | id_with_caption => { | ||
| 131 | depends_on => [qw(id caption)], # this field depends on "id" and "caption" | ||
| 132 | get => sub { | ||
| 133 | my $fields = shift; # object QBit::Application::Model::DBManager::_Utils::Fields | ||
| 134 | # access to model: $fields->model | ||
| 135 | |||
| 136 | my $row = shift; # hash from db: {id => 1, caption => 'Happy Milkman'} | ||
| 137 | |||
| 138 | return $row->{'id'} . ': ' . $row->{'caption'}; | ||
| 139 | } | ||
| 140 | }, | ||
| 141 | id_with_caption_db => { | ||
| 142 | db => 'sellers', | ||
| 143 | db_expr => {CONCAT => ['id', \': ', 'caption']}, # see QBit::Application::Model::DB::Query | ||
| 144 | }, | ||
| 145 | name => { | ||
| 146 | # relation "one to one". Use it if you want use join | ||
| 147 | db => 'users', # this field is from the table, but the tables are different | ||
| 148 | }, | ||
| 149 | items => { | ||
| 150 | # relation "one to one", "one to many" or "many to many" | ||
| 151 | depends_on => [qw(id)], | ||
| 152 | get => sub { | ||
| 153 | my $fields = shift; # object QBit::Application::Model::DBManager::_Utils::Fields | ||
| 154 | my $row = shift; # hash from db: {id => 1} | ||
| 155 | |||
| 156 | # $fields->{'__ITEMS__'} created in pre_process_fields | ||
| 157 | return $fields->{'__ITEMS__'}{$row->{'id'}} // []; | ||
| 158 | } | ||
| 159 | } | ||
| 160 | ); | ||
| 161 | |||
| 162 | # returns query (class: QBit::Application::Model::DB::Query) | ||
| 163 | sub query { | ||
| 164 | my ($self, %opts) = @_; | ||
| 165 | |||
| 166 | my $filter = $self->db->filter($opts{'filter'}); | ||
| 167 | |||
| 168 | unless ($self->check_rights('sellers_view_all')) { | ||
| 169 | my $cur_user = $self->cur_user(); | ||
| 170 | |||
| 171 | $filter->and({user_id => $cur_user->{'id'}}; | ||
| 172 | } | ||
| 173 | |||
| 174 | my $query = $self->db->query->select( | ||
| 175 | table => $self->db->sellers, | ||
| 176 | fields => $opts{'fields'}->get_db_fields('sellers'), # returns db expression for fields with "db" = 'sellers' | ||
| 177 | filter => $filter | ||
| 178 | ); | ||
| 179 | |||
| 180 | my $users_fields = $opts{'fields'}->get_db_fields('users'); | ||
| 181 | |||
| 182 | # join users only if needed (field "name" was requested) | ||
| 183 | $query->join( | ||
| 184 | table => $self->db->users, | ||
| 185 | fields => $users_fields, | ||
| 186 | ) if %$users_fields; | ||
| 187 | |||
| 188 | return $query; | ||
| 189 | } | ||
| 190 | |||
| 191 | # used for dictionaries | ||
| 192 | sub pre_process_fields { | ||
| 193 | my $self = shift; # model | ||
| 194 | my $fields = shift; # object QBit::Application::Model::DBManager::_Utils::Fields | ||
| 195 | my $result = shift; # data from db | ||
| 196 | |||
| 197 | if ($fields->need('items')) { | ||
| 198 | # gets items only if needed (field "items" was requested) | ||
| 199 | |||
| 200 | my $items = $self->items->get_all( | ||
| 201 | fields => [qw(id seller_id caption)], | ||
| 202 | filter => {seller_id => [map {$_->{'id'}} @$result]}, # key "id" exists because fields "items" depends on "id" | ||
| 203 | ); | ||
| 204 | |||
| 205 | # create dictionaries {<SELLER_ID> => <ITEM>} | ||
| 206 | $fields->{'__ITEMS__'} = {map {$_->{'seller_id'} => $_} @$items}; | ||
| 207 | } | ||
| 208 | } | ||
| 209 | |||
| 210 | TRUE; | ||
| 211 | |||
| 212 | # in your code | ||
| 213 | |||
| 214 | my $sellers = $app->sellers->get_all(fields => [qw(id id_with_caption_db name items)]); | ||
| 215 | |||
| 216 | #$sellers = [ | ||
| 217 | # { | ||
| 218 | # id => 1, | ||
| 219 | # id_with_caption_db => '1: Happy Milkman', | ||
| 220 | # name => 'Petr Ivanovich', | ||
| 221 | # items => [ | ||
| 222 | # { | ||
| 223 | # id => 1, | ||
| 224 | # seller_id => 1, | ||
| 225 | # caption => 'milk' | ||
| 226 | # }, | ||
| 227 | # { | ||
| 228 | # id => 2, | ||
| 229 | # seller_id => 1, | ||
| 230 | # caption => 'cheese' | ||
| 231 | # }, | ||
| 232 | # ], | ||
| 233 | # } | ||
| 234 | #] | ||
| 235 | |||
| 236 | =cut | ||
| 237 | |||
| 238 | sub model_fields { | ||
| 239 | my ($class, %fields) = @_; | ||
| 240 | |||
| 241 | package_stash($class)->{'__MODEL_FIELDS__'} = \%fields; | ||
| 242 | } | ||
| 243 | |||
| 244 | =head2 init_fields | ||
| 245 | |||
| 246 | Initialization fields. Used after calling B<model_fields> in run time a code | ||
| 247 | |||
| 248 | B<No arguments.> | ||
| 249 | |||
| 250 | B<Example:> | ||
| 251 | |||
| 252 | $model->model_fields(...); | ||
| 253 | $model->init_fields(); | ||
| 254 | |||
| 255 | =cut | ||
| 256 | |||
| 257 | sub init_fields { | ||
| 258 | my ($self) = @_; | ||
| 259 | |||
| 260 | my $class = ref($self) || $self; | ||
| 261 | |||
| 262 | my $fields = package_stash($class)->{'__MODEL_FIELDS__'}; | ||
| 263 | |||
| 264 | my $inited_fields; | ||
| 265 | |||
| 266 | package_stash($class)->{'__MODEL_FIELDS_INITIALIZED__'} = $inited_fields = | ||
| 267 | QBit::Application::Model::DBManager::_Utils::Fields->init_fields($fields); | ||
| 268 | |||
| 269 | package_stash($class)->{'__MODEL_FIELDS_SORT_ORDERS__'} = | ||
| 270 | QBit::Application::Model::DBManager::_Utils::Fields->init_field_sort($inited_fields); | ||
| 271 | } | ||
| 272 | |||
| 273 | =head2 model_filter | ||
| 274 | |||
| 275 | Set model filters. Save into package stash with key __DB_FILTER__ | ||
| 276 | |||
| 277 | B<Types:> namespace (QBit::Application::Model::DBManager::Filter) | ||
| 278 | |||
| 279 | =over | ||
| 280 | |||
| 281 | =item | ||
| 282 | |||
| 283 | boolean | ||
| 284 | |||
| 285 | =item | ||
| 286 | |||
| 287 | dictionary | ||
| 288 | |||
| 289 | =item | ||
| 290 | |||
| 291 | multistate | ||
| 292 | |||
| 293 | =item | ||
| 294 | |||
| 295 | number | ||
| 296 | |||
| 297 | =item | ||
| 298 | |||
| 299 | subfilter | ||
| 300 | |||
| 301 | =item | ||
| 302 | |||
| 303 | text | ||
| 304 | |||
| 305 | =back | ||
| 306 | |||
| 307 | B<Arguments:> | ||
| 308 | |||
| 309 | =over | ||
| 310 | |||
| 311 | =item * | ||
| 312 | |||
| 313 | B<%opts> - Options (type: hash) | ||
| 314 | |||
| 315 | =over | ||
| 316 | |||
| 317 | =item | ||
| 318 | |||
| 319 | db_accessor - name db accessor | ||
| 320 | |||
| 321 | =item | ||
| 322 | |||
| 323 | fields - filter fields | ||
| 324 | |||
| 325 | =back | ||
| 326 | |||
| 327 | =back | ||
| 328 | |||
| 329 | B<Example:> | ||
| 330 | |||
| 331 | __PACKAGE__->model_filter( | ||
| 332 | db_accessor => 'db', # your db accessor | ||
| 333 | fields => { | ||
| 334 | id => {type => 'number'}, | ||
| 335 | caption => {type => 'text'}, | ||
| 336 | active => {type => 'boolean'}, | ||
| 337 | product => { | ||
| 338 | type => 'dictionary', | ||
| 339 | values => sub { | ||
| 340 | [ | ||
| 341 | {id => 1, label => gettext('Milk')}, | ||
| 342 | {id => 2, label => gettext('Cheese')}, | ||
| 343 | ]; | ||
| 344 | }, | ||
| 345 | } | ||
| 346 | multistate => {type => 'multistate'}, | ||
| 347 | # you can filtered by field from other model | ||
| 348 | user => { | ||
| 349 | type => 'subfilter', | ||
| 350 | model_accessor => 'users', # accessor related model | ||
| 351 | field => 'user_id', # field from this model | ||
| 352 | fk_field => 'id', # field from model "users" | ||
| 353 | }, | ||
| 354 | }, | ||
| 355 | ); | ||
| 356 | |||
| 357 | # in your code | ||
| 358 | |||
| 359 | my $items = $app->model->get_all( | ||
| 360 | filter => [ | ||
| 361 | 'OR', | ||
| 362 | [ | ||
| 363 | ['id', '=', 1], | ||
| 364 | ['caption', 'LIKE', 'Nike'], | ||
| 365 | ['active', '=', 1], | ||
| 366 | ['product', '=', [1, 2]], | ||
| 367 | ['multistate', '=', 'approved and working'], | ||
| 368 | ['user', 'MATCH', ['login', '=', 'ChuckNorris']] # login is a filter in model "users" | ||
| 369 | ] | ||
| 370 | ] | ||
| 371 | ); | ||
| 372 | |||
| 373 | =cut | ||
| 374 | |||
| 375 | sub model_filter { | ||
| 376 | my ($class, %opts) = @_; | ||
| 377 | |||
| 378 | my $pkg_stash = package_stash($class); | ||
| 379 | $pkg_stash->{'__DB_FILTER__'} = $opts{'fields'} || return; | ||
| 380 | |||
| 381 | $pkg_stash->{'__DB_FILTER_DBACCESSOR__'} = $opts{'db_accessor'} || 'db'; | ||
| 382 | throw Exception::BadArguments gettext("Cannot find DB accessor %s, package %s", | ||
| 383 | $pkg_stash->{'__DB_FILTER_DBACCESSOR__'}, $class) | ||
| 384 | unless $class->can($pkg_stash->{'__DB_FILTER_DBACCESSOR__'}); | ||
| 385 | |||
| 386 | } | ||
| 387 | |||
| 388 | =head2 get_model_fields | ||
| 389 | |||
| 390 | Returns a model fields. | ||
| 391 | |||
| 392 | B<No arguments.> | ||
| 393 | |||
| 394 | B<Return value:> $model_fields (type: ref of a hash) | ||
| 395 | |||
| 396 | B<Example:> | ||
| 397 | |||
| 398 | my $model_fields = $app->model->get_model_fields(); # getter for method "model_fields" | ||
| 399 | |||
| 400 | =cut | ||
| 401 | |||
| 402 | sub get_model_fields { | ||
| 403 | my ($self) = @_; | ||
| 404 | |||
| 405 | return package_stash(ref($self))->{'__MODEL_FIELDS__'}; | ||
| 406 | } | ||
| 407 | |||
| 408 | sub get_db_filter_fields { | ||
| 409 | my ($self, %opts) = @_; | ||
| 410 | |||
| 411 | my $filter_fields = package_stash(ref($self))->{'__DB_FILTER__'}; | ||
| 412 | |||
| 413 | if (exists($opts{fields})) { | ||
| 414 | foreach my $field (@{$opts{fields}}) { | ||
| 415 | throw Exception::BadArguments gettext('Filter by unknown field "%s" in model %s', $field, ref($self)) | ||
| 416 | unless exists($filter_fields->{$field}); | ||
| 417 | } | ||
| 418 | } | ||
| 419 | my @fields = exists($opts{fields}) ? (@{delete($opts{fields})}) : (keys %$filter_fields); | ||
| 420 | |||
| 421 | foreach my $field (@fields) { | ||
| 422 | my $fdata = $filter_fields->{$field}; | ||
| 423 | |||
| 424 | throw Exception::BadArguments gettext('Missed filter type (package: "%s", filter: "%s")', ref($self), $field) | ||
| 425 | unless defined($fdata->{'type'}); | ||
| 426 | my $filter_class = 'QBit::Application::Model::DBManager::Filter::' . $fdata->{'type'}; #delete( | ||
| 427 | my $filter_fn = "$filter_class.pm"; | ||
| 428 | $filter_fn =~ s/::/\//g; | ||
| 429 | require $filter_fn or throw $!; | ||
| 430 | |||
| 431 | $self->{'__DB_FILTER__'}{$field} = $filter_class->new(%$fdata, field_name => $field, db_manager => $self); | ||
| 432 | } | ||
| 433 | |||
| 434 | my %fields = %{clone(package_stash(ref($self))->{'__DB_FILTER__'}) || {}}; | ||
| 435 | |||
| 436 | foreach my $field (@fields) { | ||
| 437 | my $save = TRUE; | ||
| 438 | |||
| 439 | $save = $self->{'__DB_FILTER__'}{$field}->pre_process($fields{$field}, $field, %opts) | ||
| 440 | if $self->{'__DB_FILTER__'}{$field}->can('pre_process'); | ||
| 441 | |||
| 442 | unless ($save) { | ||
| 443 | delete($fields{$field}); | ||
| 444 | next; | ||
| 445 | } | ||
| 446 | |||
| 447 | $fields{$field}->{'label'} = $fields{$field}->{'label'}() | ||
| 448 | if exists($fields{$field}->{'label'}) && ref($fields{$field}->{'label'}) eq 'CODE'; | ||
| 449 | |||
| 450 | $fields{$field} = | ||
| 451 | {hash_transform($fields{$field}, [qw(type label), @{$self->{'__DB_FILTER__'}{$field}->public_keys || []}])} | ||
| 452 | unless $opts{'private'}; | ||
| 453 | } | ||
| 454 | |||
| 455 | return \%fields; | ||
| 456 | } | ||
| 457 | |||
| 458 | sub get_db_filter_simple_fields { | ||
| 459 | my ($self, %opts) = @_; | ||
| 460 | |||
| 461 | $opts{'fields'} = $self->get_db_filter_fields() unless exists($opts{'fields'}); | ||
| 462 | |||
| 463 | my @res; | ||
| 464 | while (my ($name, $value) = each(%{$opts{'fields'}})) { | ||
| 465 | push(@res, {name => $name, label => $value->{'label'}}) | ||
| 466 | if $self->{'__DB_FILTER__'}{$name}->is_simple; | ||
| 467 | } | ||
| 468 | |||
| 469 | return \@res; | ||
| 470 | } | ||
| 471 | |||
| 472 | =head2 get_all | ||
| 473 | |||
| 474 | Returns model items. | ||
| 475 | |||
| 476 | B<Arguments:> | ||
| 477 | |||
| 478 | =over | ||
| 479 | |||
| 480 | =item | ||
| 481 | |||
| 482 | B<%opts> - Options (type: hash) | ||
| 483 | |||
| 484 | =over | ||
| 485 | |||
| 486 | =item | ||
| 487 | |||
| 488 | fields | ||
| 489 | |||
| 490 | returns "id" and "caption" | ||
| 491 | my $data = $app->model->get_all(fields => [qw(id caption)]); | ||
| 492 | |||
| 493 | # returns fields with key "default" | ||
| 494 | my $data = $app->model->get_all(); | ||
| 495 | |||
| 496 | # return all fields | ||
| 497 | my $data = $app->model->get_all(fields => ['*']); | ||
| 498 | |||
| 499 | =item | ||
| 500 | |||
| 501 | filter - see QBit::Application::Model::DB::Query. Unlike filters from the database, model filters can not use field names and scalars are used without reference. | ||
| 502 | |||
| 503 | # mysql: name = caption | ||
| 504 | # db: ['name', '=', 'caption'] | ||
| 505 | # model: no way | ||
| 506 | |||
| 507 | # mysql: id = 12 | ||
| 508 | # db: ['id', '=', \12] | ||
| 509 | # model: ['id', '=', 12] | ||
| 510 | |||
| 511 | my $data = $app->model->get_all(filter => {id => 1}); | ||
| 512 | |||
| 513 | =item | ||
| 514 | |||
| 515 | distinct - unique rows from table | ||
| 516 | |||
| 517 | my $data = $app->model->get_all(fields => [qw(caption)], distinct => TRUE); | ||
| 518 | |||
| 519 | =item | ||
| 520 | |||
| 521 | for_update - get lock | ||
| 522 | |||
| 523 | # get | ||
| 524 | my $data = $app->model->get_all(fields => [qw(id)], filter => ["caption", "LIKE", "milk"]}, for_update => TRUE); | ||
| 525 | |||
| 526 | # update | ||
| 527 | $app->db->table->edit($app->db->filter({id => [map {$_->{'id'}} @$data]}), {caption => 'Milk'}); | ||
| 528 | |||
| 529 | =item | ||
| 530 | |||
| 531 | order_by - set order | ||
| 532 | |||
| 533 | my $data = $app->model->get_all( | ||
| 534 | fields => [qw(caption)], | ||
| 535 | order_by => [ | ||
| 536 | 'caption', # asc | ||
| 537 | [ | ||
| 538 | 'price', # field | ||
| 539 | 1 # order: 0 - asc, 1 - desc | ||
| 540 | ] | ||
| 541 | ] | ||
| 542 | ); | ||
| 543 | |||
| 544 | =item | ||
| 545 | |||
| 546 | limit | ||
| 547 | |||
| 548 | my $data = $app->model->get_all(limit => 100); | ||
| 549 | |||
| 550 | =item | ||
| 551 | |||
| 552 | offset | ||
| 553 | |||
| 554 | my $data = $app->model->get_all(limit => 100, offset => 1000); | ||
| 555 | |||
| 556 | =item | ||
| 557 | |||
| 558 | calc_rows | ||
| 559 | |||
| 560 | my $data = $app->model->get_all(limit => 100, calc_rows => TRUE); | ||
| 561 | |||
| 562 | my $all_data = $app->model->found_rows(); # 1_000_000 | ||
| 563 | |||
| 564 | =item | ||
| 565 | |||
| 566 | all_locales | ||
| 567 | |||
| 568 | my $data = $app->model->get_all(fields => [qw(id caption)], all_locales => TRUE); | ||
| 569 | |||
| 570 | #$data = [ | ||
| 571 | # { | ||
| 572 | # id => 1, | ||
| 573 | # caption => { | ||
| 574 | # ru => 'Веселый молочник', | ||
| 575 | # en => 'Happy Milkman', | ||
| 576 | # }, | ||
| 577 | # }, | ||
| 578 | # ... | ||
| 579 | #] | ||
| 580 | |||
| 581 | =back | ||
| 582 | |||
| 583 | =back | ||
| 584 | |||
| 585 | B<Return value:> Data (type: ref of a array) | ||
| 586 | |||
| 587 | B<Example:> | ||
| 588 | |||
| 589 | my $data = $app->model->get_all( | ||
| 590 | fields => [qw(id caption)], | ||
| 591 | filter => ['OR', [ | ||
| 592 | ['id', '=', 10], | ||
| 593 | ['caption', '=', 'milk'] | ||
| 594 | ]], | ||
| 595 | limit => 100, | ||
| 596 | offset => 10_000, | ||
| 597 | order_by => ['caption'] | ||
| 598 | ); | ||
| 599 | |||
| 600 | =cut | ||
| 601 | |||
| 602 | sub get_all { | ||
| 603 | my ($self, %opts) = @_; | ||
| 604 | |||
| 605 | $self->timelog->start(gettext('%s: get_all', ref($self))); | ||
| 606 | |||
| 607 | my $fields = $self->_get_fields_obj($opts{'fields'}, $opts{'all_locales'}); | ||
| 608 | |||
| 609 | my $last_fields = $fields->get_fields(); | ||
| 610 | foreach ($fields->need_delete) { | ||
| 611 | # Hide unavailable fields | ||
| 612 | delete($last_fields->{$_}); | ||
| 613 | } | ||
| 614 | |||
| 615 | my $query = $self->query( | ||
| 616 | fields => $fields, | ||
| 617 | filter => $self->get_db_filter($opts{'filter'}), | ||
| 618 | )->all_langs($opts{'all_locales'}); | ||
| 619 | |||
| 620 | $query->distinct if $opts{'distinct'}; | ||
| 621 | $query->for_update if $opts{'for_update'}; | ||
| 622 | |||
| 623 | if ($opts{'order_by'}) { | ||
| 624 | my $all_fields = $self->_get_fields_obj([keys(%{$self->get_model_fields()})]); | ||
| 625 | |||
| 626 | my %db_fields = map {$_ => TRUE} keys(%{$all_fields->get_db_fields()}); | ||
| 627 | |||
| 628 | my @order_by = map {[ref($_) ? ($_->[0], $_->[1]) : ($_, 0)]} | ||
| 629 | grep {exists($db_fields{ref($_) ? $_->[0] : $_})} @{$opts{'order_by'}}; | ||
| 630 | |||
| 631 | $query->order_by(@order_by) if @order_by; | ||
| 632 | } | ||
| 633 | |||
| 634 | $query->limit($opts{'offset'}, $opts{'limit'}) if $opts{'limit'}; | ||
| 635 | |||
| 636 | $query->calc_rows(1) if $opts{'calc_rows'}; | ||
| 637 | |||
| 638 | my $result = $query->get_all(); | ||
| 639 | |||
| 640 | $self->{'__FOUND_ROWS__'} = $query->found_rows() if $opts{'calc_rows'}; | ||
| 641 | |||
| 642 | if (@$result) { | ||
| 643 | $self->timelog->start(gettext('Preprocess fields')); | ||
| 644 | $self->pre_process_fields($fields, $result); | ||
| 645 | $self->timelog->finish(); | ||
| 646 | |||
| 647 | $self->timelog->start(gettext('Process data')); | ||
| 648 | $result = $fields->process_data($result); | ||
| 649 | $self->timelog->finish(); | ||
| 650 | } | ||
| 651 | |||
| 652 | $self->{'__LAST_FIELDS__'} = $last_fields; | ||
| 653 | |||
| 654 | $self->timelog->finish(); | ||
| 655 | |||
| 656 | return $result; | ||
| 657 | } | ||
| 658 | |||
| 659 | =head2 found_rows | ||
| 660 | |||
| 661 | Returns count of a rows. | ||
| 662 | |||
| 663 | B<No arguments.> | ||
| 664 | |||
| 665 | B<Return value:> $found_rows (type: scalar or undef) | ||
| 666 | |||
| 667 | B<Example:> | ||
| 668 | |||
| 669 | my $data = $app->model->get_all(limit => 3, calc_rows => TRUE); | ||
| 670 | |||
| 671 | my $found_rows = $app->model->found_rows(); | ||
| 672 | |||
| 673 | =cut | ||
| 674 | |||
| 675 | sub found_rows { | ||
| 676 | my ($self) = @_; | ||
| 677 | |||
| 678 | return $self->{'__FOUND_ROWS__'}; | ||
| 679 | } | ||
| 680 | |||
| 681 | =head2 last_fields | ||
| 682 | |||
| 683 | Returns a last fields was requested. | ||
| 684 | |||
| 685 | B<No arguments.> | ||
| 686 | |||
| 687 | B<Return value:> $last_fields (type: scalar or undef) | ||
| 688 | |||
| 689 | B<Example:> | ||
| 690 | |||
| 691 | my $data = $app->model->get_all(fields => [qw(id caption)]); | ||
| 692 | |||
| 693 | my $last_fields = $app->model->last_fields(); | ||
| 694 | |||
| 695 | # $last_fields = { | ||
| 696 | # id => '', | ||
| 697 | # caption => '', | ||
| 698 | # }; | ||
| 699 | |||
| 700 | =cut | ||
| 701 | |||
| 702 | sub last_fields { | ||
| 703 | my ($self) = @_; | ||
| 704 | |||
| 705 | return $self->{'__LAST_FIELDS__'}; | ||
| 706 | } | ||
| 707 | |||
| 708 | sub get_all_with_meta { | ||
| 709 | my ($self, %opts) = @_; | ||
| 710 | |||
| 711 | my %meta_opts = map {$_ => TRUE} @{delete($opts{'meta'}) || []}; | ||
| 712 | $opts{'calc_rows'} = TRUE if $meta_opts{'found_rows'}; | ||
| 713 | |||
| 714 | my $data = $self->get_all(%opts); | ||
| 715 | |||
| 716 | my %meta; | ||
| 717 | $meta{'last_fields'} = [keys(%{$self->last_fields()})] if $meta_opts{'last_fields'}; | ||
| 718 | $meta{'found_rows'} = $self->found_rows() if $meta_opts{'found_rows'}; | ||
| 719 | |||
| 720 | return { | ||
| 721 | data => $data, | ||
| 722 | meta => \%meta, | ||
| 723 | }; | ||
| 724 | } | ||
| 725 | |||
| 726 | =head2 get | ||
| 727 | |||
| 728 | Returns row by primary key. | ||
| 729 | |||
| 730 | B<Arguments:> | ||
| 731 | |||
| 732 | =over | ||
| 733 | |||
| 734 | =item | ||
| 735 | |||
| 736 | B<$pk> - primary key (type: scalar or hash) | ||
| 737 | |||
| 738 | =item | ||
| 739 | |||
| 740 | B<%opts> - options (type: hash; see get_all) | ||
| 741 | |||
| 742 | =back | ||
| 743 | |||
| 744 | B<Return value:> Row (type: ref of a hash or undef) | ||
| 745 | |||
| 746 | B<Example:> | ||
| 747 | |||
| 748 | my $item = $app->model->get(1, fields => [qw(id caption)]); | ||
| 749 | |||
| 750 | # or | ||
| 751 | my $item = $app->model->get({id => 1}, fields => [qw(id caption)]); | ||
| 752 | |||
| 753 | =cut | ||
| 754 | |||
| 755 | sub get { | ||
| 756 | my ($self, $pk, %opts) = @_; | ||
| 757 | |||
| 758 | return undef unless defined($pk); | ||
| 759 | |||
| 760 | my $pk_fields = $self->get_pk_fields(); | ||
| 761 | |||
| 762 | $pk = {$pk_fields->[0] => $pk} if ref($pk) ne 'HASH'; | ||
| 763 | |||
| 764 | my @missed_fields = grep {!exists($pk->{$_})} @$pk_fields; | ||
| 765 | throw Exception::BadArguments gettext("Invalid primary key fields") if @missed_fields; | ||
| 766 | |||
| 767 | return $self->get_all(%opts, filter => [AND => [map {[$_ => '=' => $pk->{$_}]} @$pk_fields]])->[0]; | ||
| 768 | } | ||
| 769 | |||
| 770 | =head2 get_pk_fields | ||
| 771 | |||
| 772 | Returns primary keys. | ||
| 773 | |||
| 774 | B<No arguments.> | ||
| 775 | |||
| 776 | B<Return value:> fields (type: ref of a array) | ||
| 777 | |||
| 778 | B<Example:> | ||
| 779 | |||
| 780 | my $pk = $app->model->get_pk_fields(); # ['id'] | ||
| 781 | |||
| 782 | =cut | ||
| 783 | |||
| 784 | sub get_pk_fields { | ||
| 785 | my ($self) = @_; | ||
| 786 | |||
| 787 | my $fields = $self->get_model_fields(); | ||
| 788 | |||
| 789 | return [sort {$a cmp $b} grep {$fields->{$_}{'pk'}} keys(%$fields)]; | ||
| 790 | } | ||
| 791 | |||
| 792 | sub get_db_filter { | ||
| 793 | my ($self, $data, %opts) = @_; | ||
| 794 | |||
| 795 | return undef unless defined($data); | ||
| 796 | |||
| 797 | return ref($data) ? $self->_get_db_filter_from_data($data, %opts) : $self->_get_db_filter_from_text($data, %opts); | ||
| 798 | } | ||
| 799 | |||
| 800 | =head2 pre_process_fields | ||
| 801 | |||
| 802 | used for dictionaries. | ||
| 803 | |||
| 804 | B<No arguments.> | ||
| 805 | |||
| 806 | B<Return value:> undef | ||
| 807 | |||
| 808 | B<Example:> | ||
| 809 | |||
| 810 | # see method: model_fields | ||
| 811 | $app->model->pre_process_fields(); | ||
| 812 | |||
| 813 | =cut | ||
| 814 | |||
| 815 | sub pre_process_fields { } | ||
| 816 | |||
| 817 | sub _get_fields_obj { | ||
| 818 | my ($self, $fields, $all_locales) = @_; | ||
| 819 | |||
| 820 | my $stash = package_stash(ref($self)); | ||
| 821 | |||
| 822 | return QBit::Application::Model::DBManager::_Utils::Fields->new( | ||
| 823 | $stash->{'__MODEL_FIELDS_INITIALIZED__'}, | ||
| 824 | $stash->{'__MODEL_FIELDS_SORT_ORDERS__'}, | ||
| 825 | $fields, $self, $all_locales | ||
| 826 | ); | ||
| 827 | } | ||
| 828 | |||
| 829 | sub _db { | ||
| 830 | my ($self) = @_; | ||
| 831 | |||
| 832 | my $accessor_name = package_stash(ref($self))->{'__DB_FILTER_DBACCESSOR__'}; | ||
| 833 | |||
| 834 | return $self->$accessor_name; | ||
| 835 | } | ||
| 836 | |||
| 837 | sub _get_db_filter_from_data { | ||
| 838 | my ($self, $data, %opts) = @_; | ||
| 839 | |||
| 840 | return undef unless $data; | ||
| 841 | |||
| 842 | return [AND => [\undef]] if ref($data) && ref($data) eq 'ARRAY' && @$data == 1 && !defined($data->[0]); | ||
| 843 | |||
| 844 | return $self->_get_db_filter_from_data([AND => [map {[$_ => '=' => $data->{$_}]} keys(%$data)]], %opts) | ||
| 845 | if ref($data) eq 'HASH'; | ||
| 846 | |||
| 847 | if (ref($data) eq 'ARRAY' && @$data == 2 && ref($data->[1]) eq 'ARRAY') { | ||
| 848 | throw Exception::BadArguments gettext('Unknow operation "%s"', uc($data->[0])) | ||
| 849 | unless in_array(uc($data->[0]), [qw(OR AND)]); | ||
| 850 | |||
| 851 | return ($opts{'type'} || '') eq 'text' | ||
| 852 | ? '(' | ||
| 853 | . join(' ' . uc($data->[0]) . ' ', map {$self->_get_db_filter_from_data($_, %opts)} @{$data->[1]}) . ')' | ||
| 854 | : $self->_db() | ||
| 855 | ->filter([uc($data->[0]) => [map {$self->_get_db_filter_from_data($_, %opts)->expression()} @{$data->[1]}]]); | ||
| 856 | } elsif (ref($data) eq 'ARRAY' && @$data == 3) { | ||
| 857 | my $field = $data->[0]; | ||
| 858 | $opts{'model_fields'}{$field} ||= $self->get_db_filter_fields(private => TRUE, fields => [$field])->{$field}; | ||
| 859 | my $model_fields = $opts{'model_fields'}; | ||
| 860 | |||
| 861 | throw Exception::BadArguments gettext('Unknown field "%s"', $field) | ||
| 862 | unless defined($model_fields->{$field}); | ||
| 863 | |||
| 864 | $self->{'__DB_FILTER__'}{$field}->check($data, $model_fields->{$field}) | ||
| 865 | if $self->{'__DB_FILTER__'}{$field}->can('check'); | ||
| 866 | |||
| 867 | return ($opts{'type'} || '') eq 'text' | ||
| 868 | ? $self->{'__DB_FILTER__'}{$field}->as_text($data, $model_fields->{$field}, %opts) | ||
| 869 | : return $self->_db()->filter( | ||
| 870 | $model_fields->{$field}{'db_filter'} | ||
| 871 | ? $model_fields->{$field}{'db_filter'}($self, $data, $model_fields->{$field}, %opts) | ||
| 872 | : $self->{'__DB_FILTER__'}{$field}->as_filter($data, $model_fields->{$field}, %opts) | ||
| 873 | ); | ||
| 874 | |||
| 875 | } else { | ||
| 876 | throw Exception::BadArguments gettext('Bad filter data'); | ||
| 877 | } | ||
| 878 | } | ||
| 879 | |||
| 880 | sub _get_db_filter_from_text { | ||
| 881 | my ($self, $data, %opts) = @_; | ||
| 882 | |||
| 883 | my $pkg_stash = package_stash(ref($self)); | ||
| 884 | my $db_accessor = $pkg_stash->{'__DB_FILTER_DBACCESSOR__'}; | ||
| 885 | my $model_fields = $opts{'model_fields'} ||= $self->get_db_filter_fields(private => TRUE); | ||
| 886 | |||
| 887 | my $grammar = <<EOF; | ||
| 888 | %{ | ||
| 889 | use qbit; | ||
| 890 | no warnings 'redefine'; | ||
| 891 | %} | ||
| 892 | |||
| 893 | %whites = /([ \\t\\r\\n]*)/ | ||
| 894 | EOF | ||
| 895 | |||
| 896 | my %tokens = %{$self->_grammar_tokens(%opts, model_fields => $model_fields)}; | ||
| 897 | $tokens{$_} = QBit::Application::Model::DBManager::Filter::tokens($_) foreach qw(AND OR); | ||
| 898 | |||
| 899 | $grammar .= "\n%token $_ = {\n $tokens{$_}->{'re'};\n}\n" | ||
| 900 | foreach sort {$tokens{$b}->{'priority'} <=> $tokens{$a}->{'priority'}} keys(%tokens); | ||
| 901 | |||
| 902 | $grammar .= <<EOF; | ||
| 903 | |||
| 904 | %left OR | ||
| 905 | %left AND | ||
| 906 | |||
| 907 | %tree | ||
| 908 | #%strict | ||
| 909 | |||
| 910 | %% | ||
| 911 | start: expr { \$_[1] } | ||
| 912 | ; | ||
| 913 | EOF | ||
| 914 | |||
| 915 | my @expr = %{$self->_grammar_expr(%opts, model_fields => $model_fields)}; | ||
| 916 | $grammar .= "\n$expr[0]: $expr[1]"; | ||
| 917 | |||
| 918 | my $nonterminals = $self->_grammar_nonterminals(%opts, model_fields => $model_fields); | ||
| 919 | $grammar .= "\n\n$_: $nonterminals->{$_}" foreach keys(%$nonterminals); | ||
| 920 | |||
| 921 | $grammar .= "\n%%"; | ||
| 922 | |||
| 923 | my $grammar_class_name = ref($self) . '::Grammar'; | ||
| 924 | |||
| 925 | my $p = Parse::Eyapp->new_grammar( | ||
| 926 | input => $grammar, | ||
| 927 | classname => $grammar_class_name, | ||
| 928 | ); | ||
| 929 | throw $p->Warnings if $p->Warnings; | ||
| 930 | |||
| 931 | my $parser = $grammar_class_name->new(); | ||
| 932 | $parser->{'__DB__'} = $self->$db_accessor; | ||
| 933 | $parser->{'__MODEL__'} = $self; | ||
| 934 | $parser->input(\$data); | ||
| 935 | |||
| 936 | my $filter = $parser->YYParse( | ||
| 937 | yyerror => sub { | ||
| 938 | my $token = $_[0]->YYCurval(); | ||
| 939 | |||
| 940 | my $text = gettext( | ||
| 941 | 'Syntax error near "%s". Expected one of these tokens: %s', | ||
| 942 | $token ? $token : gettext('end of input'), | ||
| 943 | join(', ', $_[0]->YYExpect()) | ||
| 944 | ); | ||
| 945 | throw Exception::DBManager::Grammar $text; | ||
| 946 | } | ||
| 947 | ); | ||
| 948 | |||
| 949 | return $filter if ($opts{'type'} || '') eq 'json_data'; | ||
| 950 | |||
| 951 | return $self->_get_db_filter_from_data( | ||
| 952 | $filter, %opts, | ||
| 953 | model_fields => $model_fields, | ||
| 954 | db_accessor => $db_accessor | ||
| 955 | ); | ||
| 956 | } | ||
| 957 | |||
| 958 | sub _grammar_tokens { | ||
| 959 | my ($self, %opts) = @_; | ||
| 960 | |||
| 961 | my %tokens; | ||
| 962 | |||
| 963 | foreach my $field_name (keys(%{$opts{'model_fields'}})) { | ||
| 964 | $tokens{uc($field_name)} = { | ||
| 965 | re => "/\\G(" . uc($field_name) . ")/igc and return (" . uc($field_name) . " => \$1)", | ||
| 966 | priority => length($field_name) | ||
| 967 | }; | ||
| 968 | |||
| 969 | foreach my $token (@{$self->{'__DB_FILTER__'}{$field_name}->need_tokens || []}) { | ||
| 970 | $tokens{$token} = QBit::Application::Model::DBManager::Filter::tokens($token); | ||
| 971 | } | ||
| 972 | |||
| 973 | push_hs(%tokens, | ||
| 974 | $self->{'__DB_FILTER__'}{$field_name}->tokens($field_name, $opts{'model_fields'}->{$field_name}, %opts)) | ||
| 975 | if $self->{'__DB_FILTER__'}{$field_name}->can('tokens'); | ||
| 976 | } | ||
| 977 | |||
| 978 | return \%tokens; | ||
| 979 | } | ||
| 980 | |||
| 981 | sub _grammar_nonterminals { | ||
| 982 | my ($self, %opts) = @_; | ||
| 983 | |||
| 984 | my %nonterminals; | ||
| 985 | |||
| 986 | foreach my $field_name (keys(%{$opts{'model_fields'}})) { | ||
| 987 | push_hs(%nonterminals, | ||
| 988 | $self->{'__DB_FILTER__'}{$field_name} | ||
| 989 | ->nonterminals($field_name, $opts{'model_fields'}->{$field_name}, %opts)) | ||
| 990 | if $self->{'__DB_FILTER__'}{$field_name}->can('nonterminals'); | ||
| 991 | } | ||
| 992 | |||
| 993 | return \%nonterminals; | ||
| 994 | } | ||
| 995 | |||
| 996 | sub _grammar_expr { | ||
| 997 | my ($self, %opts) = @_; | ||
| 998 | |||
| 999 | $opts{'gns'} ||= ''; | ||
| 1000 | |||
| 1001 | my $res = | ||
| 1002 | "$opts{'gns'}expr AND $opts{'gns'}expr { QBit::Application::Model::DBManager::Filter::__merge_expr(\$_[1], \$_[3], 'AND') } | ||
| 1003 | | $opts{'gns'}expr OR $opts{'gns'}expr { QBit::Application::Model::DBManager::Filter::__merge_expr(\$_[1], \$_[3], 'OR') } | ||
| 1004 | | '(' $opts{'gns'}expr ')' { \$_[2] }\n"; | ||
| 1005 | |||
| 1006 | foreach my $field_name (keys(%{$opts{'model_fields'}})) { | ||
| 1007 | $res .= " | " . $_ . "\n" | ||
| 1008 | foreach | ||
| 1009 | @{$self->{'__DB_FILTER__'}{$field_name}->expressions($field_name, $opts{'model_fields'}->{$field_name}, %opts) | ||
| 1010 | || []}; | ||
| 1011 | } | ||
| 1012 | |||
| 1013 | $res .= " ;"; | ||
| 1014 | |||
| 1015 | return {"$opts{'gns'}expr" => $res}; | ||
| 1016 | } | ||
| 1017 | |||
| 1018 | TRUE; |