Saturday, May 29, 2010

Referential CONSTRAINT


Constraints on the database that require relations to satisfy certain properties. Relations that satisfy all such constraints are legal relations.

Defining referential constraints

Referential integrity is imposed by adding referential constraints to table and column definitions. Once referential constraints are defined to the database manager, changes to the data within the tables and columns is checked against the defined constraint. Completion of the requested action depends on the result of the constraint checking.
Referential constraints are established with the FOREIGN KEY clause, and the REFERENCES clause in the CREATE TABLE or ALTER TABLE statements. There are effects from a referential constraint on a typed table or to a parent table that is a typed table that you should consider before creating a referential constraint.
The identification of foreign keys enforces constraints on the values within the rows of a table or between the rows of two tables. The database manager checks the constraints specified in a table definition and maintains the relationships accordingly. The goal is to maintain integrity whenever one database object references another.
For example, primary and foreign keys each have a department number column. For the EMPLOYEE table, the column name is WORKDEPT, and for the DEPARTMENT table, the name is DEPTNO. The relationship between these two tables is defined by the following constraints:
  • There is only one department number for each employee in the EMPLOYEE table, and that number exists in the DEPARTMENT table.
  • Each row in the EMPLOYEE table is related to no more than one row in the DEPARTMENT table. There is a unique relationship between the tables.
  • Each row in the EMPLOYEE table that has a non-null value for WORKDEPT is related to a row in the DEPTNO column of the DEPARTMENT table.
  • The DEPARTMENT table is the parent table, and the EMPLOYEE table is the dependent table.
The SQL statement defining the parent table, DEPARTMENT, is:
CREATE TABLE DEPARTMENT
      (DEPTNO    CHAR(3)     NOT NULL,
       DEPTNAME  VARCHAR(29) NOT NULL,
       MGRNO     CHAR(6),
       ADMRDEPT  CHAR(3)     NOT NULL,
       LOCATION  CHAR(16),
          PRIMARY KEY (DEPTNO))
   IN RESOURCE 
The SQL statement defining the dependent table, EMPLOYEE, is:
CREATE TABLE EMPLOYEE
      (EMPNO     CHAR(6)     NOT NULL PRIMARY KEY,
       FIRSTNME  VARCHAR(12) NOT NULL,
       LASTNAME  VARCHAR(15) NOT NULL,
       WORKDEPT  CHAR(3),
       PHONENO   CHAR(4),
       PHOTO     BLOB(10m)   NOT NULL,
          FOREIGN KEY DEPT (WORKDEPT)
          REFERENCES DEPARTMENT ON DELETE NO ACTION)
   IN RESOURCE 
By specifying the DEPTNO column as the primary key of the DEPARTMENT table and WORKDEPT as the foreign key of the EMPLOYEE table, you are defining a referential constraint on the WORKDEPT values. This constraint enforces referential integrity between the values of the two tables. In this case, any employees that are added to the EMPLOYEE table must have a department number that can be found in the DEPARTMENT table.
The delete rule for the referential constraint in the employee table is NO ACTION, which means that a department cannot be deleted from the DEPARTMENT table if there are any employees in that department.
Although the previous examples use the CREATE TABLE statement to add a referential constraint, the ALTER TABLE statement can also be used.
Another example: The same table definitions are used as those in the previous example. Also, the DEPARTMENT table is created before the EMPLOYEE table. Each department has a manager, and that manager is listed in the EMPLOYEE table. MGRNO of the DEPARTMENT table is actually a foreign key of the EMPLOYEE table. Because of this referential cycle, this constraint poses a slight problem. You could add a foreign key later. You could also use the CREATE SCHEMA statement to create both the EMPLOYEE and DEPARTMENT tables at the same time.

DATABASE- Hierarchical Model & Relational Model




Hierarchical Model

The hierarchical data model organizes data in a tree structure. There is a hierarchy of parent and child data segments. This structure implies that a record can have repeating information, generally in the child data segments. Data in a series of records, which have a set of field values attached to it. It collects all the instances of a specific record together as a record type. These record types are the equivalent of tables in the relational model, and with the individual records being the equivalent of rows. To create links between these record types, the hierarchical model uses Parent Child Relationships. These are a 1:N mapping between record types. This is done by using trees, like set theory used in the relational model, "borrowed" from maths. For example, an organization might store information about an employee, such as name, employee number, department, salary. The organization might also store information about an employee's children, such as name and date of birth. The employee and children data forms a hierarchy, where the employee data represents the parent segment and the children data represents the child segment. If an employee has three children, then there would be three child segments associated with one employee segment. In a hierarchical database the parent-child relationship is one to many. This restricts a child segment to having only one parent segment. Hierarchical DBMSs were popular from the late 1960s, with the introduction of IBM's Information Management System (IMS) DBMS, through the 1970s.

A parent-child hierarchy is a hierarchy in a standard dimension that contains a parent attribute. A parent attribute describes a self-referencing relationship, or self-join, within a dimension main table. Parent-child hierarchies are constructed from a single parent attribute. Only one level is assigned to a parent-child hierarchy, because the levels present in the hierarchy are drawn from the parent-child relationships between members associated with the parent attribute. 

Relational Model

(RDBMS - relational database management system) A database based on the relational model developed by E.F. Codd. A relational database allows the definition of data structures, storage and retrieval operations and integrity constraints. In such a database the data and relations between them are organised in tables. A table is a collection of records and each record in a table contains the same fields.



Properties of Relational Tables:



  • Values Are Atomic


  • Each Row is Unique


  • Column Values Are of the Same Kind


  • The Sequence of Columns is Insignificant


  • The Sequence of Rows is Insignificant


  • Each Column Has a Unique Name

    Certain fields may be designated as keys, which means that searches for specific values of that field will use indexing to speed them up. Where fields in two different tables take values from the same set, a join operation can be performed to select related records in the two tables by matching values in those fields. Often, but not always, the fields will have the same name in both tables. For example, an "orders" table might contain (customer-ID, product-code) pairs and a "products" table might contain (product-code, price) pairs so to calculate a given customer's bill you would sum the prices of all products ordered by that customer by joining on the product-code fields of the two tables. This can be extended to joining multiple tables on multiple fields. Because these relationships are only specified at retreival time, relational databases are classed as dynamic database management system. The RELATIONAL database model is based on the Relational Algebra. 





  • ref. unixspace.com



  • INHERITANCE REVISITED


    Types of Inheritance:--
    1. Single
    2. Multi-level ( class 1 derived to class 2 and class 2 derived to class 3)
    3. Multiple ( class 3 derived from class 1 and class 2 )
    4. Hierarchy type ( class 1 derives to class 2,3,4 )
    5. Hybrid  ( deadly diamond )


    eg,

    class Derived-Class : access-specifier Base-class


    Case 1 =
    When the access specifier for a base class is public, all public members of the base become public members of the derived class, and all protected members of the base become protected members of the derived class. In all cases, the base's private elements remain private to the base and are not accessible by members of the derived class

    Case 2 =
    When the base class is inherited by using the private access specifier, all public and protected members of the base class become private members of the derived class
    When a base class' access specifier is private, public and protected members of the base become private members of the derived class. This means that they are still accessible by members of the derived class but cannot be accessed by parts of your program that are not members of either the base or derived class.
    Case 3 =
    Inheritance of Protected members of a class, they behave same as private members of the class i.e. they cant be accessed by the member functions of the class only and cannot be accessed by the non-member functions outside of the class.
    But the difference between the PRIVATE and PROTECTED members is this -- private members of the class when derived they cannot be accessed by derived class but protected members are accessed through derived class.
    Case 4 =
    When we inherit a base class as protected(access specifier). When this is done, all public and protected members of the base class become protected members of the derived class.

    Multiple inheritance ( multiple base class - single derived class )
    // Inherit multiple base classes.
    syntex == class derived: public base1, public base2

    Constructor and Destructor calls in inheritance:-
    Constructors are executed in their order of derivation. Destructors are executed in reverse order of derivation.
    Passing Parameters to Base-Class Constructors:-
    #include
    using namespace std;
      
    class base {
    protected:
      int i;
    public:
      base(int x) { i=x; cout << "Constructing base\n"; }
      ~base() { cout << "Destructing base\n"; }
    };
      
    class derived: public base {
      int j;
    public:
      // derived uses x; y is passed along to base.
      derived(int x, int y): base(y)     ===================> base class's paramter has to be passed in derived class's constructor even though it might not use it.
        { j=x; cout << "Constructing derived\n"; }
      
      ~derived() { cout << "Destructing derived\n"; }
      void show() { cout << i << " " << j << "\n"; }
    };
      
    int main()
    {
      derived ob(3, 4);
      
      ob.show(); // displays 4 3
      
      return 0;
    }

    Special Case of accessing the public member of base class derived as privately making that member private for that derived class:
    class base {
    public:
      int j; // public in base
    };
      
    // Inherit base as private.
    class derived: private base {
    public:
      
      // here is access declaration
      base::j; // make j public again   //using this syntax base::member;
      .
      .
      .
    };

    Virtual base class ( deadly diamond -- hybrid inheritance )
    // This program uses virtual base classes.
    #include
    using namespace std;
      
    class base {
    public:
      int i;
    };
      
    // derived1 inherits base as virtual.
    class derived1 : virtual public base {
    public:
      int j;
    };
      
    // derived2 inherits base as virtual.
    class derived2 : virtual public base {
    public:
      int k;
    };
      
    /* derived3 inherits both derived1 and derived2.
       This time, there is only one copy of base class. */
    class derived3 : public derived1, public derived2 {
    public:
      int sum;
    };
      
    int main()
    {
      derived3 ob;
      
      ob.i = 10; // now unambiguous
      ob.j = 20;
      ob.k = 30;
      
      // unambiguous
      ob.sum = ob.i + ob.j + ob.k;
      
      // unambiguous
      cout << ob.i << " ";
      
      cout << ob.j << " " << ob.k << " ";
      cout << ob.sum;
      
      return 0;
    }






    TYPE CASTING C/C++

    Type Casting



    Converting an expression of a given type into another type is known as type-casting

    Implicit conversion

    Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example:
    short a=2000;
    int b;
    b=a;
    Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.
    Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions. For example:
    class A {};
    class B { public: B (A a) {} };
     
    A a;
    B b=a;
    Here, a implicit conversion happened between objects of class A and class B, because B has a constructor that takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed.

    Explicit conversion

    C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c-like casting:
    short a=2000;
    int b;
    b = (int) a;    // c-like cast notation
    b = int (a);    // functional notation 
    The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors. For example, the following code is syntactically correct:
    // class type-casting
    #include 
    using namespace std;
     
    class CDummy {
        float i,j;
    };
     
    class CAddition {
            int x,y;
      public:
            CAddition (int a, int b) { x=a; y=b; }
            int result() { return x+y;}
    };
     
    int main () {
      CDummy d;
      CAddition * padd;
      padd = (CAddition*) &d;
      cout << padd->result();
      return 0;
    }
     
    The program declares a pointer to CAddition, but then it assigns to it a reference to an object of another incompatible type using explicit type-casting:
    padd = (CAddition*) &d;
    Traditional explicit type-casting allows to convert any pointer into any other pointer type, independently of the types they point to. The subsequent call to member result will produce either a run-time error or a unexpected result.
    In order to control these types of conversions between classes, we have four specific casting operators: dynamic_cast, reinterpret_cast, static_cast and const_cast. Their format is to follow the new type enclosed between angle-brackets (<>) and immediately after, the expression to be converted between parentheses.
    dynamic_cast (expression)
    reinterpret_cast (expression)
    static_cast (expression)
    const_cast (expression)

    The traditional type-casting equivalents to these expressions would be:

    (new_type) expression
    new_type (expression)

    but each one with its own special characteristics:

    dynamic_cast

    dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.
    Therefore, dynamic_cast is always successful when we cast a class to one of its base classes:
    class CBase { };
    class CDerived: public CBase { };
     
    CBase b; CBase* pb;
    CDerived d; CDerived* pd;
     
    pb = dynamic_cast(&d);     // ok: derived-to-base
    pd = dynamic_cast(&b);  // wrong: base-to-derived 
    The second conversion in this piece of code would produce a compilation error since base-to-derived conversions are not allowed with dynamic_cast unless the base class is polymorphic.
    When a class is polymorphic, dynamic_cast performs a special checking during runtime to ensure that the expression yields a valid complete object of the requested class:
    // dynamic_cast
    #include 
    #include 
    using namespace std;
     
    class CBase { virtual void dummy() {} };
    class CDerived: public CBase { int a; };
     
    int main () {
      try {
        CBase * pba = new CDerived;
        CBase * pbb = new CBase;
        CDerived * pd;
     
        pd = dynamic_cast(pba);
        if (pd==0) cout << "Null pointer on first type-cast" << endl;
     
        pd = dynamic_cast(pbb);
        if (pd==0) cout << "Null pointer on second type-cast" << endl;
     
      } catch (exception& e) {cout << "Exception: " << e.what();}
      return 0;
    }
    Null pointer on second type-cast

    Compatibility note: dynamic_cast requires the Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers support this feature as an option which is disabled by default. This must be enabled for runtime type checking using dynamic_cast to work properly.
    The code tries to perform two dynamic casts from pointer objects of type CBase* (pba and pbb) to a pointer object of type CDerived*, but only the first one is successful. Notice their respective initializations:
    CBase * pba = new CDerived;
    CBase * pbb = new CBase;
    Even though both are pointers of type CBase*, pba points to an object of type CDerived, while pbb points to an object of type CBase. Thus, when their respective type-castings are performed using dynamic_cast, pba is pointing to a full object of class CDerived, whereas pbb is pointing to an object of class CBase, which is an incomplete object of class CDerived.

    When
    dynamic_cast cannot cast a pointer because it is not a complete object of the required class -as in the second conversion in the previous example- it returns a null pointer to indicate the failure. If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type bad_cast is thrown instead.
    dynamic_cast can also cast null pointers even between pointers to unrelated classes, and can also cast pointers of any type to void pointers (void*).

    static_cast

    static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of dynamic_cast is avoided.
    class CBase {};
    class CDerived: public CBase {};
    CBase * a = new CBase;
    CDerived * b = static_cast(a);
    This would be valid, although b would point to an incomplete object of the class and could lead to runtime errors if dereferenced.
    static_cast can also be used to perform any other non-pointer conversion that could also be performed implicitly, like for example standard conversion between fundamental types:
    double d=3.14159265;
    int i = static_cast<int>(d); 
    Or any conversion between classes with explicit constructors or operator functions as described in "implicit conversions" above.

    reinterpret_cast

    reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.
    It can also cast pointers to or from integer types. The format in which this integer value represents a pointer is platform-specific. The only guarantee is that a pointer cast to an integer type large enough to fully contain it, is granted to be able to be cast back to a valid pointer.
    The conversions that can be performed by reinterpret_cast but not by static_cast have no specific uses in C++ are low-level operations, whose interpretation results in code which is generally system-specific, and thus non-portable. For example:
    class A {};
    class B {};
    A * a = new A;
    B * b = reinterpret_cast(a);
    This is valid C++ code, although it does not make much sense, since now we have a pointer that points to an object of an incompatible class, and thus dereferencing it is unsafe.

    const_cast

    This type of casting manipulates the constness of an object, either to be set or to be removed. For example, in order to pass a const argument to a function that expects a non-constant parameter:
    // const_cast
    #include 
    using namespace std;
     
    void print (char * str)
    {
      cout << str << endl;
    }
     
    int main () {
      const char * c = "sample text";
      print ( const_cast<char *> (c) );
      return 0;
    }
    sample text

    typeid

    typeid allows to check the type of an expression:
    typeid (expression)
    This operator returns a reference to a constant object of type type_info that is defined in the standard header file . This returned value can be compared with another one using operators == and != or can serve to obtain a null-terminated character sequence representing the data type or class name by using its name() member.
    // typeid
    #include 
    #include 
    using namespace std;
     
    int main () {
      int * a,b;
      a=0; b=0;
      if (typeid(a) != typeid(b))
      {
        cout << "a and b are of different types:\n";
        cout << "a is: " << typeid(a).name() << '\n';
        cout << "b is: " << typeid(b).name() << '\n';
      }
      return 0;
    }
    a and b are of different types:
    a is: int *
    b is: int  
    When typeid is applied to classes typeid uses the RTTI to keep track of the type of dynamic objects. When typeid is applied to an expression whose type is a polymorphic class, the result is the type of the most derived complete object:
    // typeid, polymorphic class
    #include 
    #include 
    #include 
    using namespace std;
     
    class CBase { virtual void f(){} };
    class CDerived : public CBase {};
     
    int main () {
      try {
        CBase* a = new CBase;
        CBase* b = new CDerived;
        cout << "a is: " << typeid(a).name() << '\n';
        cout << "b is: " << typeid(b).name() << '\n';
        cout << "*a is: " << typeid(*a).name() << '\n';
        cout << "*b is: " << typeid(*b).name() << '\n';
      } catch (exception& e) { cout << "Exception: " << e.what() << endl; }
      return 0;
    }
    a is: class CBase *
    b is: class CBase *
    *a is: class CBase
    *b is: class CDerived
    Notice how the type that typeid considers for pointers is the pointer type itself (both a and b are of type class CBase *). However, when typeid is applied to objects (like *a and *b) typeid yields their dynamic type (i.e. the type of their most derived complete object).
    If the type typeid evaluates is a pointer preceded by the dereference operator (*), and this pointer has a null value, typeid throws a bad_typeid exception.