__PACKAGE__->set_primary_key('id');
__PACKAGE__->sequence('mysequence');
+ # Somewhere in your Code
+ # add some data to a table with a hierarchical relationship
+ $schema->resultset('Person')->create ({
+ firstname => 'foo',
+ lastname => 'bar',
+ children => [
+ {
+ firstname => 'child1',
+ lastname => 'bar',
+ children => [
+ {
+ firstname => 'grandchild',
+ lastname => 'bar',
+ }
+ ],
+ },
+ {
+ firstname => 'child2',
+ lastname => 'bar',
+ },
+ ],
+ });
+
+ # select from the hierarchical relationship
+ my $rs = $schema->resultset('Person')->search({},
+ {
+ 'start_with' => { 'firstname' => 'foo', 'lastname' => 'bar' },
+ 'connect_by' => { 'parentid' => 'prior persionid'},
+ 'order_siblings_by' => 'firstname ASC',
+ };
+ );
+
+ # this will select the whole tree starting from person "foo bar", creating
+ # following query:
+ # SELECT
+ # me.persionid me.firstname, me.lastname, me.parentid
+ # FROM
+ # person me
+ # START WITH
+ # firstname = 'foo' and lastname = 'bar'
+ # CONNECT BY
+ # parentid = prior persionid
+ # ORDER SIBLINGS BY
+ # firstname ASC
+
=head1 DESCRIPTION
- This class implements autoincrements for Oracle and adds support for Oracle
- specific hierarchical queries.
+ This class implements base Oracle support. The subclass
+ L<DBIx::Class::Storage::DBI::Oracle::WhereJoins> is for C<(+)> joins in Oracle
+ versions before 9.
=head1 METHODS
use base qw/DBIx::Class::Storage::DBI/;
use mro 'c3';
+__PACKAGE__->sql_maker_class('DBIx::Class::SQLAHacks::Oracle');
+
+ sub deployment_statements {
+ my $self = shift;;
+ my ($schema, $type, $version, $dir, $sqltargs, @rest) = @_;
+
+ $sqltargs ||= {};
+ my $quote_char = $self->schema->storage->sql_maker->quote_char;
+ $sqltargs->{quote_table_names} = $quote_char ? 1 : 0;
+ $sqltargs->{quote_field_names} = $quote_char ? 1 : 0;
+
+ my $oracle_version = eval { $self->_get_dbh->get_info(18) };
+
+ $sqltargs->{producer_args}{oracle_version} = $oracle_version;
+
+ $self->next::method($schema, $type, $version, $dir, $sqltargs, @rest);
+ }
+
sub _dbh_last_insert_id {
my ($self, $dbh, $source, @columns) = @_;
my @ids = ();
sub _svp_release { 1 }
sub _svp_rollback {
- my ($self, $name) = @_;
+ my ($self, $name) = @_;
+ $self->_get_dbh->do("ROLLBACK TO SAVEPOINT $name")
+ }
+
+ =head2 relname_to_table_alias
+
+ L<DBIx::Class> uses L<DBIx::Class::Relationship> names as table aliases in
+ queries.
+
+ Unfortunately, Oracle doesn't support identifiers over 30 chars in length, so
+ the L<DBIx::Class::Relationship> name is shortened and appended with half of an
+ MD5 hash.
+
+ See L<DBIx::Class::Storage/"relname_to_table_alias">.
+
+ =cut
+
+ sub relname_to_table_alias {
+ my $self = shift;
+ my ($relname, $join_count) = @_;
+
+ my $alias = $self->next::method(@_);
+
+ return $alias if length($alias) <= 30;
+
+ # get a base64 md5 of the alias with join_count
+ require Digest::MD5;
+ my $ctx = Digest::MD5->new;
+ $ctx->add($alias);
+ my $md5 = $ctx->b64digest;
+
+ # remove alignment mark just in case
+ $md5 =~ s/=*\z//;
+
+ # truncate and prepend to truncated relname without vowels
+ (my $devoweled = $relname) =~ s/[aeiou]//g;
+ my $shortened = substr($devoweled, 0, 18);
+
+ my $new_alias =
+ $shortened . '_' . substr($md5, 0, 30 - length($shortened) - 1);
+
+ return $new_alias;
+ }
+
+ =head2 with_deferred_fk_checks
+
+ Runs a coderef between:
+
+ alter session set constraints = deferred
+ ...
+ alter session set constraints = immediate
+
+ to defer foreign key checks.
+
+ Constraints must be declared C<DEFERRABLE> for this to work.
+
+ =cut
+
+ sub with_deferred_fk_checks {
+ my ($self, $sub) = @_;
+
+ my $txn_scope_guard = $self->txn_scope_guard;
+
+ $self->_do_query('alter session set constraints = deferred');
-
++
+ my $sg = Scope::Guard->new(sub {
+ $self->_do_query('alter session set constraints = immediate');
+ });
- $self->_get_dbh->do("ROLLBACK TO SAVEPOINT $name")
+ return Context::Preserve::preserve_context(sub { $sub->() },
+ after => sub { $txn_scope_guard->commit });
}
+sub _select_args {
+ my ($self, $ident, $select, $where, $attrs) = @_;
+
+ my $connect_by_args = {};
+ if ( $attrs->{connect_by} || $attrs->{start_with} || $attrs->{order_siblings_by} ) {
+ $connect_by_args = {
+ connect_by => $attrs->{connect_by},
+ start_with => $attrs->{start_with},
+ order_siblings_by => $attrs->{order_siblings_by},
+ }
+ }
+
+ my @rv = $self->next::method($ident, $select, $where, $attrs);
+
+ return (@rv, $connect_by_args);
+}
+
+=head1 ATTRIBUTES
+
+Following additional attributes can be used in resultsets.
+
+=head2 connect_by
+
+=over 4
+
+=item Value: \%connect_by
+
+=back
+
+A hashref of conditions used to specify the relationship between parent rows
+and child rows of the hierarchy.
+
+ connect_by => { parentid => 'prior personid' }
+
+ # adds a connect by statement to the query:
+ # SELECT
+ # me.persionid me.firstname, me.lastname, me.parentid
+ # FROM
+ # person me
+ # CONNECT BY
+ # parentid = prior persionid
+
+=head2 start_with
+
+=over 4
+
+=item Value: \%condition
+
+=back
+
+A hashref of conditions which specify the root row(s) of the hierarchy.
+
+It uses the same syntax as L<DBIx::Class::ResultSet/search>
+
+ start_with => { firstname => 'Foo', lastname => 'Bar' }
+
+ # SELECT
+ # me.persionid me.firstname, me.lastname, me.parentid
+ # FROM
+ # person me
+ # START WITH
+ # firstname = 'foo' and lastname = 'bar'
+ # CONNECT BY
+ # parentid = prior persionid
+
+=head2 order_siblings_by
+
+=over 4
+
+=item Value: ($order_siblings_by | \@order_siblings_by)
+
+=back
+
+Which column(s) to order the siblings by.
+
+It uses the same syntax as L<DBIx::Class::ResultSet/order_by>
+
+ 'order_siblings_by' => 'firstname ASC'
+
+ # SELECT
+ # me.persionid me.firstname, me.lastname, me.parentid
+ # FROM
+ # person me
+ # CONNECT BY
+ # parentid = prior persionid
+ # ORDER SIBLINGS BY
+ # firstname ASC
+
=head1 AUTHOR
See L<DBIx::Class/CONTRIBUTORS>.
$dbh->do("CREATE SEQUENCE pkid1_seq START WITH 1 MAXVALUE 999999 MINVALUE 0");
$dbh->do("CREATE SEQUENCE pkid2_seq START WITH 10 MAXVALUE 999999 MINVALUE 0");
$dbh->do("CREATE SEQUENCE nonpkid_seq START WITH 20 MAXVALUE 999999 MINVALUE 0");
+
-$dbh->do("CREATE TABLE artist (artistid NUMBER(12), name VARCHAR(255), rank NUMBER(38), charfield VARCHAR2(10))");
+$dbh->do("CREATE TABLE artist (artistid NUMBER(12), parentid NUMBER(12), name VARCHAR(255), rank NUMBER(38), charfield VARCHAR2(10))");
+ $dbh->do("ALTER TABLE artist ADD (CONSTRAINT artist_pk PRIMARY KEY (artistid))");
+
$dbh->do("CREATE TABLE sequence_test (pkid1 NUMBER(12), pkid2 NUMBER(12), nonpkid NUMBER(12), name VARCHAR(255))");
- $dbh->do("CREATE TABLE cd (cdid NUMBER(12), artist NUMBER(12), title VARCHAR(255), year VARCHAR(4), single_track NUMBER(12), genreid NUMBER(12))");
- $dbh->do("CREATE TABLE track (trackid NUMBER(12), cd NUMBER(12), position NUMBER(12), title VARCHAR(255), last_updated_on DATE, last_updated_at DATE, small_dt DATE)");
+ $dbh->do("ALTER TABLE sequence_test ADD (CONSTRAINT sequence_test_constraint PRIMARY KEY (pkid1, pkid2))");
- $dbh->do("ALTER TABLE artist ADD (CONSTRAINT artist_pk PRIMARY KEY (artistid))");
+ $dbh->do("CREATE TABLE cd (cdid NUMBER(12), artist NUMBER(12), title VARCHAR(255), year VARCHAR(4), genreid NUMBER(12), single_track NUMBER(12))");
$dbh->do("ALTER TABLE cd ADD (CONSTRAINT cd_pk PRIMARY KEY (cdid))");
+
+ $dbh->do("CREATE TABLE track (trackid NUMBER(12), cd NUMBER(12) REFERENCES cd(cdid) DEFERRABLE, position NUMBER(12), title VARCHAR(255), last_updated_on DATE, last_updated_at DATE, small_dt DATE)");
+$dbh->do("ALTER TABLE track ADD (CONSTRAINT track_pk PRIMARY KEY (trackid))");
- $dbh->do("ALTER TABLE sequence_test ADD (CONSTRAINT sequence_test_constraint PRIMARY KEY (pkid1, pkid2))");
+
$dbh->do(qq{
CREATE OR REPLACE TRIGGER artist_insert_trg
BEFORE INSERT ON artist
$new = $schema->resultset('ArtistFQN')->create( { name => 'bar' } );
is( $new->artistid, 2, "Oracle Auto-PK worked with fully-qualified tablename" );
+ # test rel names over the 30 char limit
+ my $query = $schema->resultset('Artist')->search({
+ artistid => 1
+ }, {
+ prefetch => 'cds_very_very_very_long_relationship_name'
+ });
+
+ lives_and {
+ is $query->first->cds_very_very_very_long_relationship_name->first->cdid, 1
+ } 'query with rel name over 30 chars survived and worked';
+
+ # rel name over 30 char limit with user condition
+ # This requires walking the SQLA data structure.
+ {
+ local $TODO = 'user condition on rel longer than 30 chars';
+
+ $query = $schema->resultset('Artist')->search({
+ 'cds_very_very_very_long_relationship_name.title' => 'EP C'
+ }, {
+ prefetch => 'cds_very_very_very_long_relationship_name'
+ });
+
+ lives_and {
+ is $query->first->cds_very_very_very_long_relationship_name->first->cdid, 1
+ } 'query with rel name over 30 chars and user condition survived and worked';
+ }
+
# test join with row count ambiguity
-my $track = $schema->resultset('Track')->create({ trackid => 1, cd => 1,
+my $track = $schema->resultset('Track')->create({ cd => $cd->cdid,
position => 1, title => 'Track1' });
my $tjoin = $schema->resultset('Track')->search({ 'me.title' => 'Track1'},
{ join => 'cd',
is($st->pkid1, 55, "Oracle Auto-PK without trigger: First primary key set manually");
SKIP: {
- skip 'buggy BLOB support in DBD::Oracle 1.23', 8
- if $DBD::Oracle::VERSION == 1.23;
+ my %binstr = ( 'small' => join('', map { chr($_) } ( 1 .. 127 )) );
+ $binstr{'large'} = $binstr{'small'} x 1024;
- my %binstr = ( 'small' => join('', map { chr($_) } ( 1 .. 127 )) );
- $binstr{'large'} = $binstr{'small'} x 1024;
+ my $maxloblen = length $binstr{'large'};
+ note "Localizing LongReadLen to $maxloblen to avoid truncation of test data";
+ local $dbh->{'LongReadLen'} = $maxloblen;
- my $maxloblen = length $binstr{'large'};
- note "Localizing LongReadLen to $maxloblen to avoid truncation of test data";
- local $dbh->{'LongReadLen'} = $maxloblen;
+ my $rs = $schema->resultset('BindType');
+ my $id = 0;
- my $rs = $schema->resultset('BindType');
- my $id = 0;
+ if ($DBD::Oracle::VERSION eq '1.23') {
+ throws_ok { $rs->create({ id => 1, blob => $binstr{large} }) }
+ qr/broken/,
+ 'throws on blob insert with DBD::Oracle == 1.23';
- foreach my $type (qw( blob clob )) {
- foreach my $size (qw( small large )) {
- $id++;
+ skip 'buggy BLOB support in DBD::Oracle 1.23', 7;
+ }
- lives_ok { $rs->create( { 'id' => $id, $type => $binstr{$size} } ) }
- "inserted $size $type without dying";
- ok($rs->find($id)->$type eq $binstr{$size}, "verified inserted $size $type" );
- }
- }
+ foreach my $type (qw( blob clob )) {
+ foreach my $size (qw( small large )) {
+ $id++;
+
+ lives_ok { $rs->create( { 'id' => $id, $type => $binstr{$size} } ) }
+ "inserted $size $type without dying";
+
+ ok($rs->find($id)->$type eq $binstr{$size}, "verified inserted $size $type" );
+ }
+ }
}
- # test hierarchical querys
++# test hierarchical queries
+if ( $schema->storage->isa('DBIx::Class::Storage::DBI::Oracle::Generic') ) {
+ my $source = $schema->source('Artist');
+
+ $source->add_column( 'parentid' );
+
+ $source->add_relationship('children', 'DBICTest::Schema::Artist',
+ { 'foreign.parentid' => 'self.artistid' },
+ {
+ accessor => 'multi',
+ join_type => 'LEFT',
+ cascade_delete => 1,
+ cascade_copy => 1,
+ } );
+ $source->add_relationship('parent', 'DBICTest::Schema::Artist',
+ { 'foreign.artistid' => 'self.parentid' },
+ { accessor => 'single' } );
+ DBICTest::Schema::Artist->add_column( 'parentid' );
+ DBICTest::Schema::Artist->has_many(
+ children => 'DBICTest::Schema::Artist',
+ { 'foreign.parentid' => 'self.artistid' }
+ );
+ DBICTest::Schema::Artist->belongs_to(
+ parent => 'DBICTest::Schema::Artist',
+ { 'foreign.artistid' => 'self.parentid' }
+ );
+
+ $schema->resultset('Artist')->create ({
+ name => 'root',
+ cds => [],
+ children => [
+ {
+ name => 'child1',
+ children => [
+ {
+ name => 'grandchild',
+ cds => [
+ {
+ title => "grandchilds's cd" ,
+ year => '2008',
+ tracks => [
+ {
+ position => 1,
+ title => 'Track 1 grandchild',
+ }
+ ],
+ }
+ ],
+ children => [
+ {
+ name => 'greatgrandchild',
+ }
+ ],
+ }
+ ],
+ },
+ {
+ name => 'child2',
+ },
+ ],
+ });
+
+ {
+ # select the whole tree
+ my $rs = $schema->resultset('Artist')->search({},
+ {
+ 'start_with' => { 'name' => 'root' },
+ 'connect_by' => { 'parentid' => { '-prior' => \'artistid' } },
+ });
+=pod
+ SELECT
+ COUNT( * )
+ FROM
+ artist me
+ START WITH
+ name = ?
+ CONNECT BY
+ parentid = prior artistid
+
+ Parameters: 'root'
+=cut
+ is( $rs->count, 5, 'Connect By count ok' );
+ my $ok = 1;
+=pod
+ SELECT
+ me.artistid, me.name, me.rank, me.charfield, me.parentid
+ FROM
+ artist me
+ START WITH
+ name = ?
+ CONNECT BY
+ parentid = prior artistid
+
+ Parameters: 'root'
+=cut
+ foreach my $node_name (qw(root child1 grandchild greatgrandchild child2)) {
+ $ok = 0 if $rs->next->name ne $node_name;
+ }
+ ok( $ok, 'got artist tree');
+ }
+
+ {
+ # use order siblings by statement
+ my $rs = $schema->resultset('Artist')->search({},
+ {
+ 'start_with' => { 'name' => 'root' },
+ 'connect_by' => { 'parentid' => { '-prior' => \'artistid' } },
+ 'order_siblings_by' => 'name DESC',
+ });
+ my $ok = 1;
+=pod
+ SELECT
+ me.artistid, me.name, me.rank, me.charfield, me.parentid
+ FROM
+ artist me
+ START WITH
+ name = ?
+ CONNECT BY
+ parentid = prior artistid
+ ORDER SIBLINGS BY
+ name DESC
+
+ Parameters: 'root'
+=cut
+ foreach my $node_name (qw(root child2 child1 grandchild greatgrandchild)) {
+ $ok = 0 if $rs->next->name ne $node_name;
+ }
+ ok( $ok, 'Order Siblings By ok');
+ }
+
+ {
+ # get the root node
+ my $rs = $schema->resultset('Artist')->search({ parentid => undef },
+ {
+ 'start_with' => { 'name' => 'greatgrandchild' },
+ 'connect_by' => { '-prior' => [ \'parentid', \'artistid' ] } ,
+ });
+=pod
+ SELECT
+ COUNT( * )
+ FROM
+ artist me
+ WHERE
+ ( parentid IS NULL )
+ START WITH
+ name = ?
+ CONNECT BY
+ prior parentid = artistid
+
+ Parameters: 'greatgrandchild'
+=cut
+ is( $rs->count, 1, 'root node count ok' );
+=pod
+ SELECT
+ me.artistid, me.name, me.rank, me.charfield, me.parentid
+ FROM
+ artist me
+ WHERE
+ ( parentid IS NULL )
+ START WITH
+ name = ?
+ CONNECT BY
+ prior parentid = artistid
+
+ Parameters: 'greatgrandchild'
+=cut
+ ok( $rs->next->name eq 'root', 'found root node');
+ }
+
+ {
+ # combine a connect by with a join
+ my $rs = $schema->resultset('Artist')->search({'cds.title' => { 'like' => '%cd'}},
+ {
+ 'join' => 'cds',
+ 'start_with' => { 'name' => 'root' },
+ 'connect_by' => { 'parentid' => { '-prior' => \'artistid' } },
+ });
+=pod
+ SELECT
+ COUNT( * )
+ FROM
+ artist me
+ LEFT JOIN
+ cd cds ON cds.artist = me.artistid
+ WHERE
+ ( cds.title LIKE ? )
+ START WITH
+ name = ?
+ CONNECT BY
+ parentid = prior artistid
+
+ Parameters: '%cd', 'root'
+=cut
+ is( $rs->count, 1, 'Connect By with a join; count ok' );
+=pod
+ SELECT
+ me.artistid, me.name, me.rank, me.charfield, me.parentid
+ FROM
+ artist me
+ LEFT JOIN
+ cd cds ON cds.artist = me.artistid
+ WHERE
+ ( cds.title LIKE ? )
+ START WITH
+ name = ?
+ CONNECT BY
+ parentid = prior artistid
+
+ Parameters: '%cd', 'root'
+=cut
+ ok( $rs->next->name eq 'grandchild', 'Connect By with a join; result name ok')
+ }
+
+ {
+ # combine a connect by with order_by
+ my $rs = $schema->resultset('Artist')->search({},
+ {
+ 'start_with' => { 'name' => 'greatgrandchild' },
+ 'connect_by' => { '-prior' => [ \'parentid', \'artistid' ] },
+ 'order_by' => 'name ASC',
+ });
+ my $ok = 1;
+=pod
+ SELECT
+ me.artistid, me.name, me.rank, me.charfield, me.parentid
+ FROM
+ artist me
+ START WITH
+ name = ?
+ CONNECT BY
+ prior parentid = artistid
+ ORDER BY
+ name ASC
+
+ Parameters: 'greatgrandchild'
+=cut
+ foreach my $node_name (qw(child1 grandchild greatgrandchild root)) {
+ $ok = 0 if $rs->next->name ne $node_name;
+ }
+ ok( $ok, 'Connect By with a order_by; result name ok');
+ }
+
+ {
+ # limit a connect by
+ my $rs = $schema->resultset('Artist')->search({},
+ {
+ 'start_with' => { 'name' => 'greatgrandchild' },
+ 'connect_by' => { '-prior' => [ \'parentid', \'artistid' ] },
+ 'order_by' => 'name ASC',
+ 'rows' => 2,
+ 'page' => 1,
+ });
+=pod
+ SELECT
+ COUNT( * )
+ FROM
+ artist me
+ START WITH
+ name = ?
+ CONNECT BY
+ prior parentid = artistid
+
+ Parameters: 'greatgrandchild'
+=cut
+ is( $rs->count(), 2, 'Connect By; LIMIT count ok' );
+ my $ok = 1;
+=pod
+ SELECT
+ *
+ FROM
+ (
+ SELECT
+ A.*,ROWNUM r
+ FROM
+ (
+ SELECT
+ me.artistid AS col1, me.name AS col2, me.rank AS col3, me.charfield AS col4, me.parentid AS col5
+ FROM
+ artist me
+ START WITH
+ name = ?
+ CONNECT BY
+ prior parentid = artistid
+ ORDER BY
+ name ASC
+ ) A
+ WHERE
+ ROWNUM < 3
+ ) B
+ WHERE
+ r >= 1
+ Parameters: 'greatgrandchild'
+=cut
+ foreach my $node_name (qw(child1 grandchild)) {
+ $ok = 0 if $rs->next->name ne $node_name;
+ }
+ ok( $ok, 'LIMIT a Connect By query ok');
+ }
+}
+
+ done_testing;
+
# clean up our mess
END {
if($schema && ($dbh = $schema->storage->dbh)) {