0% found this document useful (0 votes)
93 views

Practical ADM

The document discusses different experiments related to database queries and implementations. It covers topics like locking protocols, creating databases using XML, queries using functions and types, structured and object types, inheritance, array and multiset types, object identity and reference types.

Uploaded by

Shaikh Ashraf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

Practical ADM

The document discusses different experiments related to database queries and implementations. It covers topics like locking protocols, creating databases using XML, queries using functions and types, structured and object types, inheritance, array and multiset types, object identity and reference types.

Uploaded by

Shaikh Ashraf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Experiment 1: Implemen ng Locking protocols.

Solu on

Two-Phase Locking (2P1)

-In this scheme, each transac on makes lock and unlock request in 2 phases 1.

1.A Growing Pluse(or An Expanding Phase or First Phase) In this phase, new locks on the desired data
sem Can be acquired but none can be released

2. A Shrinking Phave tor Second Phases In this phase, exis ng locks can be released but no new locks
can be acquired

-In the beginning, the transac on is in growing phase in which it acquire lock as per requirement.
A er comple ng the work, the transac on releases the locks and enters into shrinking phase

-The transac on cannot request for new locks a er releasing the locks

T
- Lock-
X(A);
-Read (A);
-A=A+500
-Write(A);
-Lock-
X(B)
-Read(B);
B=B+100;
-Unlock(A);
-Unlock(B);

The point in the schedule where the schedule where the transac ons acquire its final lock is called as
bock point This point in the end of growing phase. The transac ons can be ordered as per their lock
points. This sequence of transac ons is the serailizability ordering for the transac ons. This protocol
assures serializability
Experiment 3: Create database using XML a ributes and Elements.

Solu on:

<?xml version="1.0" encoding="u -8"?>

<Phoenix>

<projects>

<project name="Phoenix-InfoTech" launch-"2006-04-06">

<edi ons>

<edi on language="English">en.PhoneixGlobe.com</edi on>

<edi on language "German">de.PhoneixGlobe.com</edi on>

<edi on language="French">fr.PhoneixGlobe.com</edi on>

<edi on language= "Polish”> pl.PhoneixGlobe.com</edi on>

<edi on language="Spanish">es.PhoneixGlobe.com</edi on>

</edi ons>

</project>

<project name="Phoneix-Computers”launch=“2002-12-12">

<edi ons>

<edi on language= English">en Phoenix World.com</edi on>

<edi on language="French">fr.PhoenixWorld.com</edi on>

<edi on language= "Vietnamese">vi.Phoenix World.com</edi on>

<edi on language= "Turkish">tr.Phoenix World.com</edi on>

<edi on language= "Spanish">es.Phoenix World.com</edi on>

</edi ons>

</project>

</projects>

</Phoenix>
Experiment 4: Implement queries based on FLOWER expressions and joins using XQuery.

Solu on:

-Following is an example of a query that corresponds to a le outer join.

-Return names of all the suppliers in alphabe c order, including those that supply no parts; inside
each supplier element, list the descrip ons of all the parts it supplies, in alphabe c order.

FOR $s IN document (“s.xml”)//s_tuple

RETURN

<supplier>

$s/sname,

FOR $sp IN document(“sp.xml”)//sp_tuple

[sno=$s/sno],

$p IN document(“p.xml”)//p_tuple

[pno=$sp/pno]

RETURN $/descript SORTBY(.)

Supplier> SORTBY(sname)
Experiment 5: Implement queries based on Nested queries and sor ng of results using Query.

Solu on

-Example: The following XQuery expression sorts part of the authors by their last name and groups
book together with their first author, then sorts each author's book by publishing year.

-The query is aged from W3C XQuery Use Cases by adding the posi on func on and orderby clauses.

For $a in dis nct-Vales (doc(“bib.xml”)/book/author[1])

OrdClause by $a/last

Return <result> {$a.

For $b in doc(bib.xml”)/book

where $b/author[1]=$a

order by $b/year

return $b/ tle}

<result>

-In this example XQuery expression, the outer for clause binds $a to a sequence of authors appearing
in the XML document .The outer order by clause sorts this sequence by the authors last name.

-For each instance of $a, the inner query Mock can be evaluated.

-Such an in a ve itera ve execu on tends to be less efficient than at equivalent collec on oriented
execu on strategy, since for every binding of $a, many opera ng staps are repeated in the inner
subquery

Sor ng

There is no “sort” func on in XQuery. To sort your sequence you just create a new sequence that
contains a FLOWER loop of your item with the order statement in it.

For example if you have a list of items with tles of the elements you can use the following to sort
items by tle:

Let $sorted-items:=

for $item in $items

onder by $item/ tle/text()

return$item

-You can also use descending with order by to reverse the order:

$item in $items
order by name($item) descending

return $item

-If you want to sort with your own order by crea ng a separate sequence and using the index-of
func on to find where this is in the sequence:

For $i in/roo*

$order:=(“b”,”a”,”c”)

Order by index-of($order,$i)

reture $i
Experiment 6: Implement queries based on func ons and types using XQuery.

Solu on:

string-length($string as xs:string) as xs:integer-returns the length of a string as the number of its


characters

-Example: string-length("Hello") return 5, since the string "Hello" is five characters long.
concat($input as xs:any AtomicType?) as xs:string-concatenates a list of strings together.

-The func on does not accept a sequence of values, just individual atomic values passed as separate
arguments.

-Example: concat("big", 'red', 'ball') returns "bigredball”

String-join($sequence as xs:string", $delimiter as string) as xs:string-combines the items in a


sequence, separa ng them with a delimiter

Example: string-joint("big", "red", "ball"),-) returns "big-red-ball"


Experiment 7: Execute queries using structured type in SQL.

Solu on:

Object structured type

In order to define a custom structure type using Oracle database one could use statements such as
these:

CREATE TYPE Person_Type AS OBJECT(

person tle VARCHAR2(10),

person tle_ name VARCHAR2(20),

person_last_name VARCHAR(20),

NOT FINAL:

-Such structure type can be then used to create a table that would also hold all colums defined in
Person_Type:

CREATE TABLE Person_Table Of Person_Type(

-Custom structure types support inheritance, which means that one can create another type that
inherits from previos.

-NOT FINAL statement must be however included in a base structure type defini on in order to allow
for crea on of any other subtypes.

CREATE TYPE Student_Type UNDER Person_Type(

Matricula on_number NUMBER(10)

-Student Type them could be used in order to create a Student_Table which will include all columns
defined in Person_Type as well.

- Primary Key and Constraints should be defined during or a er crea on of table and cannot be
defined inside structure type itself

CREATE TABLE Student_Table Of Student_Type(

Matricula on_number PRIMARY KEY,

CONSTRAINT person_ tle_not_null consraint NOT NULL (person_ tle)

Each custom structure type carlo contain other types in order to support more complex structures:
CREATE TYPE Address_Type AS OBJECT(

Address_street VARCHAR2(30),

Address_city VARCHAR2(30),

CREATE TYPE Univesity AS OBJECT(

University_name VARCHAR2(30),

University_address Address_Type
Experiment 8: Execute queries using type inheritance and table inheritance in SQL.

Solu on:

Queries using Type Inheritance

- Consider that there is following type defini on for people:

create type Person

(name varchar(20),

Address varchar(20);

-Now there may be need to store extra data in the database regarding people who are students, and
regarding people who are teachers.

- As students and teachers are under the category people, inheritance can be used to define the
student andteacher types in SQL:

create type Student

under Person

(degree varchar(20).

Department varchar(20));

create type Teacher

under Person

(salary integer,

Department varchar(20));

Queries using Table Inheritance

-The following CREATE TABLE statements define the simple table hierarchy that Figure 1 shows.
- The example in this sec on assume that the person_t, employee_t, and sales rep_t types already
exist.

CREATE TABLE person OF TYPE person_t;

CREATE TABLE employee OF TYPE employee t UNDER person;

CREATE TABLE sales rep OF TYPE sales rep_t UNDER employee,


Experiment 9: Implement queries using Array and Mul set types in SQL..

Solu on:

Queries using Array

SQL

CREATE TABLE Book

(book id CHARACTER VARYING(5) CONSTRAINT book_book_id_pk PRIMARY KEY.

book- tle CHARACTER VARYING(50).

Book_ publisher REF(Publisher),

Book_author AUTHOR_ROW_TYPE,

Book_edi on INTEGER ARRAY[10];

Oracle

CREATE TABLE Book

(book_id VARCHAR(S) PRIMARY KEY,

book tle VARCHAR(50), book publisher REF(Publisher),

book author AUTHOR_TABLE_TYPE.

Book_edi on VARRAY OF INTEGER(10)) NESTED TABLE book_author AS Book_Author_Tab;

Queries using Mul set Types

SQL

CREATE TABLE Book

(Book_id CHARACTER VARYING(5)CONSTRAINT book_book_id_pk PRIMARY KEY,

book_ tle CHARACTER VARYING(50), book publisher REF(Publisher),

book_author AUTHOR_ROW_TYPE,

book_edi on INTEGER ARRAY[10].

Book_ra ng INTEGER MULTISET);


Experiment 10: Execute queries using object iden ty and reference types in SQL

Solu on:

-In SQL it is possible to define a type Department having field name and a field head that is a
reference tothe type Person, and a table departments of type Department, as follows:

create type Department (name varchar(20),

head reflPerson) scope people).

create table departments of Department;

-Here, the reference is considered as restricted to tuples regarding the table people. The restric on
of the scope of a reference to tuples of a table is always considered as mandatory in SQL, and it
forces the references to work just similar to foreign keys .

-It is possible to skip the declara on scope people from the type declara on and rather declara on
and rather an addi on to the create table statement can be made:

create table departments of Department

(head with op ons scope people);

-The referenced table constrained to contain an a ribute which stores the iden fier of the tuple.

-This a ribute (self-referen al a ribute) can be declared by the way of adding a ref is clause to the

respec ve create table statement:

create table people of Person

ref is person id system generated;

-In this statement, person id is an a ribute name (not a keyword) and the create table statement
indicates that the database generates the iden fier automa cally for the purpose of ini alizing a
reference a ribute. there is necessity to get the iden fier of the tuple which is to be referenced.
Experiment 11: Design and Develop MongoDB Queries using basic opera ons.

Solu on:

There are some basic opera ons (CRUD) of MongoDB such as Create, Read, Update, and Delete

documents

A. Create Opera ons

-Create or insert opera on add new documents to a collec on. If the collec on does not currently
exist, insert opera ons will create the collec on. -

-MongoDB provides the following methods in insert documents into a collec on:

 odb.collec on insertOne()
 db.collec on insertMany()

-In MongoDB, insert opera ons target a single collec on. All write opera ons in MongoDB are
atomic on the level of a single document..

db users.insertOne ( <--collec on

Name: "sue". <--field: value

Age: 26, < --field: value } document

Status:"pending" <--field: value

R. Read Opera ons

-Read opera on retrieves documents from a collec on; ie, queries a collec on for documents.
MongoDB provides the following methods to read documents from a collec on: db.collec on.find()

-You can specify query filters or criteria that iden fy the documents to return.

db.users.find( <--collec on

(age: ($gt: 18}}, <--query criteria

{name: 1, address: 1 } <--projec on


).limit(5) <--cursor modifier

C. Update Opera ons

-Update opera ons modify exis ng documents in a collec on. MongoDB provides the following
methods to update documents of collec on:

db.collec on.updateOne()

db.collec on.updateMany()

db.collec on.replaceOne()

-In MongoDB, update opera ons target a single collec on. All write opera ons in MongoDB are
atomic on the level of a single document.

-You can specify criteria, or filters, that iden fy the document to update. These filters use the same
syntax as read opera ons.

dh.users.updateMany ( <--collec on

{age: {$1t: 18}}; <-- update filter

{$set:{ status :”reject”} } <--update ac on

D. Delete Opera ons

-Delete opera ons remove documents from a collec on. MongoDB provides the following methods
so delete documents of a collec on:

db.collec on deleteOne() New in version 3.2

db.collec on delete Many ()New in version 3.2

-In MongoDB, delete opera ons target a single collec on. All write opera ons in MongoDB are
atomic on the level of a single document.

You can specify criteria, or filters, that iden fy the documents to remove. These filers use the same
syntax as read opera ons

Output -
Test>use SSP

switched to db SSP

SSP> db.createCollec on("CO")

{ok: 1}

SSP >db.CO.insert(department:"CO",year:"3d", sem:”5th”} ,

……{department:"ME" ,year:"2nd ” ,sem:"4"},

..…..{department:"EJ",year"1st ”,sem"1st “})

Depreca onWarning: Collec on insen() is deprecated. Use insertOne, insertMany, or bulk Write.

acknowledged: true.

insertedIds : (‘0’: Objec d(“63781202a7d44d34edbe”)}

SSP>db.CO.find({"department":"CO"})

_id: Objec d(“6378120a2a7d44d3-4ed3 3c"),

department: ‘CO’,

year ‘3rd ’,

sem: ‘5th ’

SSP>db.CO.update("department":"ME").($set("department”:”CE”}})

Depreca onWarning:Collec on.update() is deprecated. Use updateOne,updateMany or bulkWrite.

acknowledged: true,

Inserted Id: null,

matchedCount: 0,

modifiedCount: 0,

upsertedCount: 0

}
SSP db.CO.find({"department":"CO"})

id: Object("6378120a2a764443-4ed3b3"),

department:”CO”,

year: '3rd ’ sem: ‘5th ’

SSP >db.CO.remove({"deparment":"ME"})

Depreca on Waming: Collec on.remove() is deprecated. Use deleteOne, deleteMany,


findOneAndDelete, or bulk Write.

( acknowledged: true, deletedCount: 0}

SSP >db.CO.find({"year":"2nd"})

SSP >db.CO.find({year:"2nd"})

SSP>
Experiment 12: Implement aggrega on Queries using MongoDB.

Solu on:

Aggrega on Pipeline

Collec on

db. Orders. aggregate ([

$match stage {$match: {status: "A"}}.

$group stage {$group: {+id: "$cust id", total: {Sum: "Samount"}}}

])

{
cus: id:"A123",

amount : 500, {
cus:id:"A123",
status: "A"
} amount:500,
Results {
{ cus:id:"A123",
status: "A"
cus: id:"A123", }
amount: 500,
{
amount: 250, cus:id:"A123",
status: "A"
status: "A" }
amount :250,
} {
cus:id:"A123",
status: "A"
{ }
cus: id:"B212", $match amount 500,
{
$group cus:id:"B212",
amount :200, status: "A"
}
amount :200,
status: "A"
} status: "A"
{ }
cus: id:"A123",

amount :300,

status: "D" Orders Fig.1


}
Single Purpose Aggrega on Opera ons

Collec on

Db.orders.dis nct ("cust_id")

{
cust_id:"A123",
amount 500,
status: "A"
}
{
cust id:"A123",
["A123", "B212"] amount: 250,
status: "A"
Dis n }
{
cust_id:"B212",
amount: 200,
status: "A"
}
{
cust_id:"A123",
amount: 300,
status: "D"
}
Orders

Fig-2
Experiment 13: Implements MongoDB Queries Usinf find() func on.
Solu on:
-To search all documents which have the value of "age" is 30, key/value pair can be added to the
query document:

 db.users.find({"age":30})

-If there is a string which we want to match, for example "usemame" key having value "Om", the
key/value pair us used instead:

 db.users.find({"username": "Om"})

- To retrieve all the users with 27-year age and username "Om", we can query for the following:

 db.users.find({"usemame":"Om", "age":30})

Output:-

use pc

switched to db pc

pc> db.createCollec on("cmd")

{ok: 1}

pc> db.cmd.insert({roll:"03" name: "Om" age:"19"}})

Uncaught:

SyntaxError: Unexpected token, expected"." (1:44)

1 db.cmd.insert({roll:"03",name:"Om".age:"19"}})

pc> db.cmd.insert({roll:"03" name:"Om".age:"19"})

Depreca onWarning: Collec on.insert() is deprecated. Use insertOne, insertMany, or bulk Write

acknowledged: true,

inserted ids: {"0: Objectld("63780e9ca28d48be891066")}

po>db.cmd.insert({roll:"03",name: "Om" ape:"19”}),


…..(roll:"04",name: "Sujit”, age:"18"),

…..(roll."08" name "Mangesh",age: "20")

acknowledged: true,

Inserted Ids: {‘0’: ObjectId("63780f43a28d48 c891067")}

Pc>db.cmd.find("age":"19"})

Jd: Objec d(63780e9ca28d48 e8911066"),

roll: '03’

name: "Om'.

Age: '19

id: Objec d(63780f43a28d48be891067").

roll: ‘03’

name: 'Om',

age: '19'

Pc>pc.cmd.find({"name":"Om"})

ReferenceError: pc is not defined pdb.cmd.find(("name":"Om","age":"19"})

_id: Objec d("63780f43a28d48be891067").

roll: '03",

name: 'Om'.

age: '19

Pc>C:\mongosh-1.6.0-shell mongosh-1.6.0-win32-x64\bin
Experiment 14: Implement aggrega on Queries in MongoDB through MapReduce

Solu on:
Collec on

dborders.mapReduce (

map  func on () (emit (this cust_id, this.amount).}

reduce  func on() (key, values) { return Aray.sum (values) }

Query  query: { status:"A"}

Output  out: "order totals”

{
cust id: "A123",
amount:500,
status: "A" {
{“A123”:[500,250]} results
} cust id: "A123",
{ amount:500,
status: "A" {
cust id: "A123",
} cust id: "A123",
amount:250,
{ amount:500,
status: "A"
cust id: "A123", status: "A"
}
amount:250, }
{
status: "A" {
cust id: "B212",
} cust id: "A123",
amount:200,
{ amount:250,
status: "A"
cust id: "B123", status: "A"
}
amount:200, }
{cust id: "A123",
amount:300, status: "A"
status: "D" $match } {“B212”:200}
}

You might also like