package DTA::Schema::Result::FormulaComplex;

use strict;
use warnings;

use base qw/DBIx::Class::Core/;
 
__PACKAGE__->table_class('DBIx::Class::ResultSource::View');
 
__PACKAGE__->load_components("InflateColumn::DateTime");
__PACKAGE__->table("formula");

__PACKAGE__->add_columns(
  id      => { data_type => 'integer' },
  book    => { data_type => 'integer' },
  page    => { data_type => 'integer' },
  no      => { data_type => 'integer' },
  tex     => { data_type => 'text' },
  'time'  => { data_type => 'timestamp' },
  account => { data_type => 'integer' },
  cnt     => { data_type => 'integer' },
);
__PACKAGE__->set_primary_key("id");
 
# do not attempt to deploy() this view
__PACKAGE__->result_source_instance->is_virtual(1);

=head2 book

Type: belongs_to

Related object: L<DTA::Schema::Result::Book>

=cut

__PACKAGE__->belongs_to(
  "book",
  "DTA::Schema::Result::Book",
  { id_book => "book" },
  { 
    is_deferrable => 1,
    join_type     => "LEFT",
    on_delete     => "CASCADE",
    on_update     => "CASCADE",
  },
);

__PACKAGE__->result_source_instance->view_definition(q[
    SELECT f.id, f.book, f.page, f.no, f.time, f.tex, f.account, fs.cnt
      FROM (
        SELECT book, page, no, max(time) AS time, count(*) AS cnt
          FROM formula
         GROUP BY book, page, no
      ) AS fs
    NATURAL JOIN formula f
]);

1;
