Monday, February 7, 2011

Different Key In RDBMS

* Alternate key - An alternate key is any candidate key which is not selected to be the primary key

* Candidate key - A candidate key is a field or combination of fields that can act as a primary key field for that table to uniquely identify each record in that table.


* Compound key - compound key (also called a composite key or concatenated key) is a key that consists of 2 or more attributes.


* Primary key - a primary key is a value that can be used to identify a unique row in a table. Attributes are associated with it. Examples of primary keys are Social Security numbers (associated to a specific person) or ISBNs (associated to a specific book).
In the relational model of data, a primary key is a candidate key chosen as the main method of uniquely identifying a tuple in a relation.


* Superkey - A superkey is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. Equivalently a superkey can also be defined as a set of attributes of a relvar upon which all attributes of the relvar are functionally dependent.


* Foreign key - a foreign key (FK) is a field or group of fields in a database record that points to a key field or group of fields forming a key of another database record in some (usually different) table. Usually a foreign key in one table refers to the primary key (PK) of another table. This way references can be made to link information together and it is an essential part of database normalization

MyISAM V/S InnoDB

MyISAM

Let's start with MyISAM since it is the default engine with MySQL. MyISAM is based on the older but proven ISAM code but has been extended to be fully-featured while retaining the reliability. Data in MyISAM tables is split between three different files on the disk. One for the table format, another for the data, and lastly a third for the indexes.

The maximum number of rows supported amounts to somewhere around ~4.295E+09 and can have up to 64 indexed fields per table. Both of these limits can be greatly increased by compiling a special version of MySQL.

Text/Blob fields are able to be fully-indexed which is of great importance to search functions.

Much more technical information can be found on MySQL's MyISAM Manual Page.

InnoDB

InnoDB is relatively newer so the scene than MyISAM is so people are still weary about its use in environments than run fine under MyISAM. InnoDB is transaction-safe meaning data-integrity is maintained throughout the entire query process. InnoDB also provides row-locking, as opposed to table-locking, meaning while one query is busy updating or inserting a row, another query can update a different row at the same time. These features increase multi-user concurrency and performance.

Another great feature InnoDB boasts is the ability to use foreign-key constraints. FK constraints allows developers to ensure that inserted data referencing another table remains valid. For example, if you had an authors table and a books table and you wanted to insert a new book while referencing the author. The author would have to exist in the authors table before inserting them in the books table because a foreign key was specified in the books table. At the same time you would not be able to delete an author from the authors table if they had any entries associated with them in the books table. More on this in a later article...

Because of its row-locking feature InnoDB is said to thrive in high load environments. Its CPU efficiency is probably not matched by any other disk-based relational database engine.

Comparison

MyISAM in most cases will be faster than InnoDB for run of the mill sort of work. Selecting, updating and inserting are all very speedy under normal circumstances. It is the default engine chosen by the MySQL development team which speaks to its integrity, reliability, and performance.

InnoDB, or the OSX of the database-engine world, has emerged with some nifty features and created a niche for itself very quickly. Boasting features like row-level locking, transaction-safe queries, and relational table design are all very temping. The first two features really shine in a table that is constantly getting hammered like a logs, or search engine-type table. Since queries happen in the blink of an eye (faster actually) table-level locking(MyISAM) is sufficient in most other normal cases.

InnoDB recovers from a crash or other unexpected shutdown by replaying its logs. MyISAM must fully scan and repair or rebuild any indexes or possibly tables which had been updated but not fully flushed to disk.

Decision Matrix

Is your table is going to be inserted, deleted, and updated much much more than it is going to be selected?
InnoDB
If you need full-text search MyISAM
If you prefer/require relational database design InnoDB
Is disk-space or ram an issue? MyISAM
In Doubt? MyISAM

There is no winner.

REMEMBER! It's OK to mix table types in the same database! In fact it's recommended and frequently required. However, it is important to note that if you are having performance issues when joining the two types, try converting one to the other and see if that fixes it. This issue does not happen often but it has been reported.

New Features of PHP 5.3.0

PHP development team has just announced the availability of PHP version 5.3.0.
This release comes with major improvements as compared with the previous versions existing in PHP 5.x series.
PHP version 5.3.0 has many new features, as well as bug fixes (in this release over 140 bugs were repaired).
In the migration guide intended for the users of PHP 5.2.0 who want to upgrade to PHP 5.3.0,
there are explained the main differences between versions 5.2.0 and 5.3.0 of PHP.

Among the wide range of new features added in PHP 5.3.0, support for namespaces, Late Static Bindings, jump labels and native Closures (Lambda/Anonymous functions) was introduced. Two new magic methods are also supported in PHP 5.3.0: __callStatic and __invoke.

A garbage collection for cyclic references enabled by default and mysqlnd PHP native replacement for libmysql are optional. In the same time, now you are allowed to use dynamic access to static methods.

The code execution performance is improved. On the other hand, Windows support includes VC9 and experimental X64 binaries, as well as portability features to other compatible platforms.

Other key features of PHP 5.3.0 are:

-More consistent float rounding
-Deprecation notices are now handled via E_DEPRECATED (part of E_ALL) instead of the E_STRICT error level
-Several enhancements to enable more flexiblity in php.ini (and ini parsing in general)
-New bundled extensions: ext/phar, ext/intl, ext/fileinfo, ext/sqlite3, ext/enchant

The complete source code and Windows binaries of PHP 5.3.0 are available for free download,

Interface in PHP

Interface in PHP

PHP Interface:

PHP does not support multiple inheritance directly, to implement this we need Interface. It is much similar to Interface of Java.

In PHP, signature of the method are declared in the Interface body, and the body part of the method is implemented in derived class. Variables are declared as constant and it can not be changed in the child classes.

We use implement keyword to extend this kind of class, at the same time we can implement more than one interface and one interface can be implemented by another interface.

All methods declared in an interface must be public and the variables should be constant.

This is mandatory that we must declare the body part of the method in the derived class otherwise an error message will be generated.

Example:

interface Inter{

const a="This is constant value";

public function disp(); }

class A implements Inter{

function show(){

echo self::a."
"
;}

public function disp(){

echo "Inside the disp function";}}

$a=new A();

$a->show();

$a->disp();

?>

Output:

This is constant value
Inside the disp function

Important Port Number

The well-known ports are those from 0 through 1023. Examples include:

Basic Linux Commands

mkdir - make directoriesa

Usage

mkdir [OPTION] DIRECTORY

Options

Create the DIRECTORY(ies), if they do not already exist.

Mandatory arguments to long options are mandatory for short options too.

-m, mode=MODE set permission mode (as in chmod), not rwxrwxrwx - umask

-p, parents no error if existing, make parent directories as needed

-v, verbose print a message for each created directory

-help display this help and exit

-version output version information and exit

cd - change directories

Use cd to change directories. Type cd followed by the name of a directory to access that directory.Keep in mind that you are always in a directory and can navigate to directories hierarchically above or below.

mv- change the name of a directory

Type mv followed by the current name of a directory and the new name of the directory.

Ex: mv testdir newnamedir

pwd - print working directory

will show you the full path to the directory you are currently in. This is very handy to use, especially when performing some of the other commands on this page

rmdir - Remove an existing directory

rm -r

Removes directories and files within the directories recursively.

chown - change file owner and group

Usage

chown [OPTION] OWNER[:[GROUP]] FILE

chown [OPTION] :GROUP FILE

chown [OPTION] --reference=RFILE FILE

Options

Change the owner and/or group of each FILE to OWNER and/or GROUP. With --reference, change the owner and group of each FILE to those of RFILE.

-c, changes like verbose but report only when a change is made

-dereference affect the referent of each symbolic link, rather than the symbolic link itself

-h, no-dereference affect each symbolic link instead of any referenced file (useful only on systems that can change the ownership of a symlink)

-from=CURRENT_OWNER:CURRENT_GROUP

change the owner and/or group of each file only if its current owner and/or group match those specified here. Either may be omitted, in which case a match is not required for the omitted attribute.

-no-preserve-root do not treat `/' specially (the default)

-preserve-root fail to operate recursively on `/'

-f, -silent, -quiet suppress most error messages

-reference=RFILE use RFILE's owner and group rather than the specifying OWNER:GROUP values

-R, -recursive operate on files and directories recursively

-v, -verbose output a diagnostic for every file processed

The following options modify how a hierarchy is traversed when the -R option is also specified. If more than one is specified, only the final one takes effect.

-H if a command line argument is a symbolic link to a directory, traverse it

-L traverse every symbolic link to a directory encountered

-P do not traverse any symbolic links (default)

chmod - change file access permissions

Usage

chmod [-r] permissions filenames

r Change the permission on files that are in the subdirectories of the directory that you are currently in. permission Specifies the rights that are being granted. Below is the different rights that you can grant in an alpha numeric format.filenames File or directory that you are associating the rights with Permissions

u - User who owns the file.

g - Group that owns the file.

o - Other.

a - All.

r - Read the file.

w - Write or edit the file.

x - Execute or run the file as a program.

Numeric Permissions:

CHMOD can also to attributed by using Numeric Permissions:

400 read by owner

040 read by group

004 read by anybody (other)

200 write by owner

020 write by group

002 write by anybody

100 execute by owner

010 execute by group

001 execute by anybody

ls - Short listing of directory contents

-a list hidden files

-d list the name of the current directory

-F show directories with a trailing '/'

executable files with a trailing '*'

-g show group ownership of file in long listing

-i print the inode number of each file

-l long listing giving details about files and directories

-R list all subdirectories encountered

-t sort by time modified instead of name

cp - Copy files

cp myfile yourfile

Copy the files "myfile" to the file "yourfile" in the current working directory. This command will create the file "yourfile" if it doesn't exist. It will normally overwrite it without warning if it exists.

cp -i myfile yourfile

With the "-i" option, if the file "yourfile" exists, you will be prompted before it is overwritten.

cp -i /data/myfile

Copy the file "/data/myfile" to the current working directory and name it "myfile". Prompt before overwriting the file.

cp -dpr srcdir destdir

Copy all files from the directory "srcdir" to the directory "destdir" preserving links (-poption), file attributes (-p option), and copy recursively (-r option). With these options, a directory and all it contents can be copied to another dir

ln - Creates a symbolic link to a file.

ln -s test symlink

Creates a symbolic link named symlink that points to the file test Typing "ls -i test symlink" will show the two files are different with different inodes. Typing "ls -l test symlink" will show that symlink points to the file test.

locate - A fast database driven file locator.

slocate -u

This command builds the slocate database. It will take several minutes to complete this command.This command must be used before searching for files, however cron runs this command periodically on most systems.locate whereis Lists all files whose names contain the string "whereis". directory.

more - Allows file contents or piped output to be sent to the screen one page at a time

less - Opposite of the more command

cat - Sends file contents to standard output. This is a way to list the contents of short files to the screen. It works well with piping.

whereis - Report all known instances of a command

wc - Print byte, word, and line counts

bg

bg jobs Places the current job (or, by using the alternative form, the specified jobs) in the background, suspending its execution so that a new user prompt appears immediately. Use the jobs command to discover the identities of background jobs.

cal month year - Prints a calendar for the specified month of the specified year.

cat files - Prints the contents of the specified files.

clear - Clears the terminal screen.

cmp file1 file2 - Compares two files, reporting all discrepancies. Similar to the diff command, though the output format differs.

diff file1 file2 - Compares two files, reporting all discrepancies. Similar to the cmp command, though the output format differs.

dmesg - Prints the messages resulting from the most recent system boot.

fg

fg jobs - Brings the current job (or the specified jobs) to the foreground.

file files - Determines and prints a description of the type of each specified file.

find path -name pattern -print

Searches the specified path for files with names matching the specified pattern (usually enclosed in single quotes) and prints their names. The find command has many other arguments and functions; see the online documentation.

finger users - Prints descriptions of the specified users.

free - Displays the amount of used and free system memory.

ftp hostname

Opens an FTP connection to the specified host, allowing files to be transferred. The FTP program provides subcommands for accomplishing file transfers; see the online documentation.

head files - Prints the first several lines of each specified file.

ispell files - Checks the spelling of the contents of the specified files.

kill process_ids

kill - signal process_ids

kill -l

Kills the specified processes, sends the specified processes the specified signal (given as a number or name), or prints a list of available signals.

killall program

killall - signal program

Kills all processes that are instances of the specified program or sends the specified signal to all processes that are instances of the specified program.

mail - Launches a simple mail client that permits sending and receiving email messages.

man title

man section title - Prints the specified man page.

ping host - Sends an echo request via TCP/IP to the specified host. A response confirms that the host is operational.

reboot - Reboots the system (requires root privileges).

shutdown minutes

shutdown -r minutes

Shuts down the system after the specified number of minutes elapses (requires root privileges). The -r option causes the system to be rebooted once it has shut down.

sleep time - Causes the command interpreter to pause for the specified number of seconds.

sort files - Sorts the specified files. The command has many useful arguments; see the online documentation.

split file - Splits a file into several smaller files. The command has many arguments; see the online documentation

sync - Completes all pending input/output operations (requires root privileges).

telnet host - Opens a login session on the specified host.

top - Prints a display of system processes that's continually updated until the user presses the q key.

traceroute host - Uses echo requests to determine and print a network path to the host.

uptime - Prints the system uptime.

w - Prints the current system users.

wall - Prints a message to each user except those who've disabled message reception. Type Ctrl-D to end the message.

Polymorphism in PHP

While thinking about a programming language deficiency, I rediscovered polymorphism. Overloading a function allows a function call to behave differently when passed variables of different type. I was trying to devise a method of simulating function overloading, because PHP does not support it. I considered implementing a function with an if-else statement ladder that tests the type of the actual argument and executes statements that correspond to the argument̢۪s type. This technique may ultimately result in a monolithic function or a function implementation that is too knowledgeable of multiple class hierarchies. Rethinking a problem that I was hoping to solve with function overloading allowed me to accept the lack of this language feature and think of other techniques.

There are two problems that arise from the if-else statement ladder approach. The implementation of such a function would require the function to have knowledge of every data type to be used with it. This problem can be extended to knowing class hierarchies, if subclassing is involved. This means that an introduction of a new data type to be processed by the function would require the function to be modified, which creates the possibility that the modification will break other existing code that relies on the function. The second problem is having the function̢۪s maintainer think about how the function should operate on the different data types that can be passed to it. This responsibility is better placed on the people who maintain the different data types.

One solution that deals with the problems in the if-else statement ladder is polymorphism. Polymorphism allows a set of heterogeneous elements to be treated identically. It is achieved through inheritance. In PHP, interface inheritance and implementation inheritance can be written explicitly through the use of interfaces and class extensions, respectively. Interfaces specify a class interface without providing an implementation. Classes from different class hierarchies can implement an interface, and in this way, it can be seen as different from abstract classes. When a class is defined to implement an interface, the language enforces a rule that the class implements all features of the interface. A method that operates on an interface will accept an object of any class that implements the interface, and it will function correctly.

Here is a toy example of interface inheritance, polymorphism, and PHP type hinting:

color = $color;
}

public function getColor()
{
return $this->color;
}
}

class Rectangle extends Shape implements HasArea
{
private $w;
private $h;

public function __construct( $color, $w, $h )
{
parent::__construct($color);
$this->w = $w;
$this->h = $h;
}

public function area()
{
return ($this->w * $this->h);
}

public function areaUnit()
{

if( $this->area() > 1 )
return "square meters";
else
return "square meter";
}
}

class Territory implements HasArea
{
private $name;

public function __construct( $name )
{
$this->name = $name;
/* not used in this example... */
}

public function area()
{
return 5;
}

public function areaUnit()
{
return "cities";
}
}

function outputArea( HasArea $ha )
{
echo "The area is: "
. " {$ha->area()} {$ha->areaUnit()}\n";
}

$HAs = array(
new Rectangle("red",2,3),
new Territory( "somename" )
);

foreach( $HAs as $HA )
{
outputArea( $HA );
}
?>

Type hints help the PHP interpreter enforce the restriction that outputArea() operates only on objects of data types that implement the HasArea interface. Rectangle and Territory are from unrelated class hierarchies. outputArea() can operate on these classes, since these classes implement the HasArea interface.

The explored method accomplishes only some of the features offered by function overloading. In the above example, outputArea() was restricted to one argument. In some programming languages, a function can be overloaded on the number of arguments along with the types of those arguments and the order that those types appear in the argument list. This method, however, was useful in a problem I considered solving with function overloading.