Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Delete (cruD) Using Perl and DBD::ORACLE

DZone's Guide to

Delete (cruD) Using Perl and DBD::ORACLE

If you like using Perl (and Oracle DB), see how you can use it to delete data from your tables with the help of a nifty driver.

· Database Zone
Free Resource

Learn how to move from MongoDB to Couchbase Server for consistent high performance in distributed environments at any scale.

In this post, we're going to take a look at the D in CRUDDelete.

We use the DBD::Oracle driver to delete some data in the database tables, using the connection object created in the Initial Setup section of the first post in this series.

PLEASE REVIEW ALL EXAMPLE CODE AND ONLY RUN IT IF YOU ARE SURE IT WILL NOT CAUSE ANY PROBLEMS WITH YOUR SYSTEM.

Helper Function

My helper function get_all_rows encapsulates a select statement used to verify that the deletes worked. The select functionality is covered in the R part of this series, so I won't go into the details here.

sub get_all_rows {
 my $label = $_[0];
 my $data_type = $_[1];

 # Query all rows
 my $con = DBI->connect( 'dbi:Oracle:', $connectString, '') ||
 die "Database connection not made: $DBI::errstr";
 $con->{RaiseError} = 1; # set the connection to raise errors

 my $statement = 'select id, name, age, notes from lcs_people order by id';

 if ($data_type eq "pets") {
   $statement = 'select id, name, owner, type from lcs_pets order by owner, id';
 }

 my $sth = $con->prepare($statement);
 $sth->execute;

 #Adding some space around the results to make better screenshots.
 print "\n $label: \n";
 while (my @row = $sth->fetchrow_array){
   print " @row\n";
 }
 print "\n";

 $con->disconnect;
}

Add this function to the top of your file.

Resetting the Data

To keep the examples clean and precise, I will reset the data at times.

Create a new file called reset_data.perl with the following code and run it whenever you would like to reset the data. (Notice this version adds people and pet data not included in other sections.)

use strict;
use DBI;
my $connectString=$ENV{'db_connect'};
my $con = DBI->connect( 'dbi:Oracle:', $connectString, '');
$con->{RaiseError} = 1; # set the connection to raise errors

# Delete rows
my $sth = $con->prepare("delete from lcs_pets");
$sth->execute;

# Reset Identity Coulmn
my $sth = $con->prepare("alter table lcs_pets modify id generated BY DEFAULT as identity (START WITH 8)");
$sth->execute;

# Delete rows
my $sth = $con->prepare("delete from lcs_people");
$sth->execute;

# Reset Identity Coulmn
my $sth = $con->prepare("alter table lcs_people modify id generated BY DEFAULT as identity (START WITH 8)");
$sth->execute;

# Insert default rows
my @ids = (1, 2, 3, 4, 5, 6, 7);
my @names = ("Bob", "Kim", "Cheryl", "Bob", "Stacey", "Pete", "Pat");
my @ages = (35, 27, 23, 27, 45, 23, 36);
my @notes = ("I like dogs", "I like birds", "I like horses", "I like rabbits", "I like snakes", "I like cats", "I like dogs");

my $sth = $con->prepare("INSERT INTO lcs_people(id, name, age, notes) VALUES (?, ?, ?, ?)");
my $tuples = $sth->execute_array(
 { ArrayTupleStatus => \my @tuple_status }, \@ids, \@names, \@ages, \@notes,);
if ($tuples) {
 print "Successfully inserted $tuples records\n";
} else {
 print "Insert failed\n";
}

# Insert default rows
my @ids = (1, 2, 3, 4, 5, 6, 7);
my @names = ("Duke", "Dragon", "Sneaky", "Red", "Red", "Buster", "Fido");
my @owners = (1, 2, 5, 2, 3, 1, 7);
my @types = ("dog", "bird", "snake", "bird", "horse", "dog", "cat");

my $sth = $con->prepare("INSERT INTO lcs_pets(id, name, owner, type) VALUES (?, ?, ?, ?)");
my $tuples = $sth->execute_array(
 { ArrayTupleStatus => \my @tuple_status }, \@ids, \@names, \@owners, \@types,);
if ($tuples) {
 print "Successfully inserted $tuples records\n";
} else {
 print "Insert failed\n";
}

$con->disconnect;

Boilerplate Template

The template we will be using is:

use strict;
use DBI;
my $connectString=$ENV{'db_connect'};

sub get_all_rows {
 my $label = $_[0];
 my $data_type = $_[1];

 # Query all rows
 my $con = DBI->connect( 'dbi:Oracle:', $connectString, '') ||
 die "Database connection not made: $DBI::errstr";
 $con->{RaiseError} = 1; # set the connection to raise errors

 my $statement = 'select id, name, age, notes from lcs_people order by id';

 if ($data_type eq 'pets') {
   $statement = 'select id, name, owner, type from lcs_pets order by owner, id';
 }

 my $sth = $con->prepare($statement);
 $sth->execute;

 #Adding some space around the results to make better screenshots.
 print "\n $label: \n";
 while (my @row = $sth->fetchrow_array){
   print " @row\n";
 }
 print "\n";

 $con->disconnect;
}

my $con = DBI->connect( 'dbi:Oracle:', $connectString, '') || die "Database connection not made: $DBI::errstr";
$con->{RaiseError} = 1; # set the connection to raise errors

get_all_rows('Original Data', 'pets');

# Your code here

get_all_rows('New Data', 'pets');

For each exercise, replace the "# Your code here" line with your code.

Reset the Data

First, let's run reset_data.perl to set up our data.

Simple Delete

We will perform a simple delete that removes a single record from the lcs_people table.  These are the steps performed in the code snippet below.

  • Prepare a SQL DELETE statement, deleting the record with an id of 1.
  • Bind the id value. (See the R part of this series for an explanation of bind variables.)
  • Execute the statement.
my $sth = $con->prepare("delete from lcs_pets where id = :id");
$sth->bind_param( ":id",1);
$sth->execute;

When I run this code in my Perl session, I see:

Image title

 Original Data: 
 1 Duke 1 dog
 6 Buster 1 dog
 2 Dragon 2 bird
 4 Red 2 bird
 5 Red 3 horse
 3 Sneaky 5 snake
 7 Fido 7 cat

 New Data: 
 6 Buster 1 dog
 2 Dragon 2 bird
 4 Red 2 bird
 5 Red 3 horse
 3 Sneaky 5 snake
 7 Fido 7 cat

Extra Fun 1

Delete all the birds.

Your results should be:

Image title

 Original Data: 
 6 Buster 1 dog
 2 Dragon 2 bird
 4 Red 2 bird
 5 Red 3 horse
 3 Sneaky 5 snake
 7 Fido 7 cat


 New Data: 
 6 Buster 1 dog
 5 Red 3 horse
 3 Sneaky 5 snake
 7 Fido 7 cat

Answer:

my $sth = $con->prepare("delete from lcs_pets where type = :type");
$sth->bind_param( ":type","bird");
$sth->execute;

Reset the Data

Now is a good time to run reset_data.perl.

Boilerplate Change

Change the boilerplate get_all_rows statements to get people and pet data.

get_all_rows('Original People Data', 'people');
get_all_rows('Original Pet Data', 'pets');

# Your code here

get_all_rows('New People Data', 'people');
get_all_rows('New Pet Data', 'pets');

Deleting Records Referenced by Foreign Keys

If you are using integrity constraints in your database (of course you are, because then you let the database do some heavy lifting for you), you will sometimes need to change the way you process your changes.

In our design, we have a Foreign Key constraint in lcs_pets that ensures if a pet has an owner, that owner exists.

This is the statement that creates the constraint in the Creating the Database Objects section of the Initial Setup post.

ALTER TABLE LCS_PETS ADD CONSTRAINT FK_LCS_PETS_OWNER FOREIGN KEY ("OWNER") REFERENCES "LCS_PEOPLE" ("ID")
/

If we attempt to delete a record in lcs_people that is referenced in lcs_pets (Person has a pet,) we get an error.

my $sth = $con->prepare("delete from lcs_people where id = :id");
$sth->bind_param( ":id",1);
$sth->execute;

When I run this code in my Perl session, I see:

Image title

DBD::Oracle::st execute failed: ORA-02292: integrity constraint (BLAINE.FK_LCS_PETS_OWNER) violated - child record found (DBD ERROR: OCIStmtExecute) [for Statement "delete from lcs_people where id = :id" with ParamValues: :id=1] at delete2.perl line 41.
DBD::Oracle::st execute failed: ORA-02292: integrity constraint (BLAINE.FK_LCS_PETS_OWNER) violated - child record found (DBD ERROR: OCIStmtExecute) [for Statement "delete from lcs_people where id = :id" with ParamValues: :id=1] at delete2.perl line 41.

Before deleting the person you have to handle the pet (watch out for claws and teeth).

There are a few options here, depending on your database design:

  • If: pets are not required to have an owner and you only want to delete the person, not the pets.  Then: you can update the pets and set their owner to null.
  • If: pets are required to have an owner.  Then: you can delete the pets for the owner.

In either of the above scenarios, you can update the pets and set their owner to another person.

Bob is moving out of our area and his new apartment doesn't allow pets, so he's giving them to Kim.  Let's use that last option here.

  • Prepare a SQL UPDATE statement, changing owner to 2 (Kim) for the records with an owner of 1 (Bob).  Updating is covered in the U part of this series.
  • Bind the new and old owner values.
  • Execute the statement.
  • Prepare a SQL DELETE statement, deleting records with an id of 1 (Bob).
  • Bind the id value.
  • Execute the statement.
my $sth = $con->prepare("update lcs_pets set owner = :newOwner where owner = :oldOwner");
$sth->bind_param(":newOwner",2);
$sth->bind_param(":oldOwner",1);
$sth->execute;

my $sth = $con->prepare("delete from lcs_people where id = :id");
$sth->bind_param(":id",1);
$sth->execute;

When I run this code in my Perl session, I see:

Image title

Original People Data: 
 1 Bob 35 I like dogs
 2 Kim 27 I like birds
 3 Cheryl 23 I like horses
 4 Bob 27 I like rabbits
 5 Stacey 45 I like snakes
 6 Pete 23 I like cats
 7 Pat 36 I like dogs

Original Pet Data: 
 1 Duke 1 dog
 6 Buster 1 dog
 2 Dragon 2 bird
 4 Red 2 bird
 5 Red 3 horse
 3 Sneaky 5 snake
 7 Fido 7 cat

New People Data: 
 2 Kim 27 I like birds
 3 Cheryl 23 I like horses
 4 Bob 27 I like rabbits
 5 Stacey 45 I like snakes
 6 Pete 23 I like cats
 7 Pat 36 I like dogs

New Pet Data: 
 1 Duke 2 dog
 2 Dragon 2 bird
 4 Red 2 bird
 6 Buster 2 dog
 5 Red 3 horse
 3 Sneaky 5 snake
 7 Fido 7 cat

When you change data it's a good idea to verify the number of affected rows.  This is covered in the R part of this series.

Extra Fun 2

Due to a zoning change, snakes are no longer allowed in our area.  Stacey has decided to move and take Sneaky with her.

Let's fix our data.

Your results should be:

Image title

Original People Data: 
 2 Kim 27 I like birds
 3 Cheryl 23 I like horses
 4 Bob 27 I like rabbits
 5 Stacey 45 I like snakes
 6 Pete 23 I like cats
 7 Pat 36 I like dogs

Original Pet Data: 
 1 Duke 2 dog
 2 Dragon 2 bird
 4 Red 2 bird
 6 Buster 2 dog
 5 Red 3 horse
 3 Sneaky 5 snake
 7 Fido 7 cat

New People Data: 
 2 Kim 27 I like birds
 3 Cheryl 23 I like horses
 4 Bob 27 I like rabbits
 6 Pete 23 I like cats
 7 Pat 36 I like dogs

New Pet Data: 
 1 Duke 2 dog
 2 Dragon 2 bird
 4 Red 2 bird
 6 Buster 2 dog
 5 Red 3 horse
 7 Fido 7 cat

Answer:

my $sth = $con->prepare("delete from lcs_pets where owner = :owner");
$sth->bind_param(":owner",5);
$sth->execute;

my $sth = $con->prepare("delete from lcs_people where id = :id");
$sth->bind_param(":id",5);
$sth->execute;

Some Other Things You Could Try

  • Change the database constraints to delete or Null the child record on delete (a cascading delete). Delete a person and let the database handle the children.
  • Remove the people who don't have any pets.

Series Sections

Want to deliver a whole new level of customer experience? Learn how to make your move from MongoDB to Couchbase Server.

Topics:
oracle ,crud ,perl ,delete ,database

Published at DZone with permission of Blaine Carter. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}