Thursday, September 13, 2012

Transactions in MySQL


Definition of a transaction

A transaction is an atomic unit of database operations against the data in one or more databases. The effects of all the SQL statements in a transaction can be either all committed to the database or all rolled back.

MySQL supports several storage engines. The InnoDB is fully ACID compliant. The ACID stands for Atomicity, Consistency, Isolation and Durability. Reliable transactions must support all these four properties.

Operations within a transaction must be atomic. This means, that either all operations succeed or fail. This is all or nothing rule. The consistency property ensures that the database is in a consistent state after the transaction is finished. The data is valid and there are no half-finished records. For example there are no customers left with no payment records or there are no payment records without customers. Isolation is the requirement that other operations cannot access data that has been modified during a transaction that has not yet completed. The question of isolation occurs in case of concurrent transactions. Without isolation, the data may end up in inconsistent state. Durability is the ability of the database system to recover the committed transaction updates against any kind of system failure.

The default transaction isolation level for MySQL is repeatable read.

mysql> SELECT @@tx_isolation;
+-----------------+
| @@tx_isolation  |
+-----------------+
| REPEATABLE-READ |
+-----------------+

The current isolation level is stored in the tx_isolation server variable.

mysql> SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

mysql> SELECT @@tx_isolation;
+----------------+
| @@tx_isolation |
+----------------+
| SERIALIZABLE   |
+----------------+

We can change the isolation level with the SET TRANSACTION ISOLATION LEVEL statement.


Autocommit


MySQL also automatically commits statements that are not part of a transaction. The results of any UPDATE or INSERT statement not preceded with a START will immediately be visible to all connections.

mysql> SELECT @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            1 |
+--------------+

The autocommit variable is set by default.

mysql> SET autocommit=0;

mysql> SELECT @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            0 |
+--------------+

The autocommit can be turned off.
Now we are going to demonstrate the autocommint variable.

mysql> SELECT @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            1 |
+--------------+

CREATE TABLE Test(Num INTEGER NOT NULL) engine=InnoDB;

The autocommit is set. We create a simple Test table with InnoDB storage engine, which supports transactions.

mysql> INSERT INTO Test VALUES (1), (2), (3);

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
+-----+

We insert three rows into the column of the table. The values are immediately committed.

mysql> SET autocommit=0;

mysql> INSERT INTO Test VALUES (4), (5);

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
|   5 |
+-----+

Now we set the autocommit variable to false. We insert two values and select all data from the table. We have now 5 rows in the table.

mysql> ROLLBACK;

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
+-----+

However, the data is not permanently written to the table. With the ROLLBACK statement, we take them back.

mysql> INSERT INTO Test VALUES (4), (5);

mysql> COMMIT;

mysql> ROLLBACK;

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
|   5 |
+-----+

Now we insert value 4, 5 again. This time, the rows are committed with the COMMIT statement. Subsequent rollback statement has no effect.


Starting transactions

With autocommit enabled, each single SQL statement is wrapped automatically in its own transaction. To start our own transaction, we issue the START TRANSACTION statement. The transaction is later finished with the COMMIT or ROLLBACK statements. Multiple statements may be issued in the body of the transaction. All are either committed or rolled back as one unit.

mysql> TRUNCATE Test;
Query OK, 0 rows affected (0.02 sec)

mysql> SELECT * FROM Test;
Empty set (0.00 sec)

We will work with the same Test table. We truncate the data in the table.

mysql> START TRANSACTION;

mysql> INSERT INTO Test VALUES (1), (2);

mysql> INSERT INTO Test VALUES (3), (4);

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
+-----+

In the above code, we start a transaction and insert four rows into the table. The values are not yet committed. From the current connection the rows are visible.

$ mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 65
Server version: 5.1.41-3ubuntu12.9 (Ubuntu)

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> SELECT * FROM mydb.Test;
Empty set (0.00 sec)


However, from a different connection, the Test table is empty. We launch a new instance of a mysql client program. This is a different connection to the MySQL database. From this connection, the values are not yet visible.


mysql> COMMIT;

Finally, the COMMIT statement commits the data to the table. The rows are visible from both connections.

We start another transaction. This time the data will be rolled back.

mysql> START TRANSACTION;

mysql> INSERT INTO Test VALUES (5), (6);

mysql> INSERT INTO Test VALUES (7), (8);

mysql> ROLLBACK;

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
+-----+



In the above SQL code, we start a new transaction. We insert four values into the Test table. We roll the changes back with the ROLLBACK statement. Subsequent select from the table shows that the data was not committed to the table.

Tuesday, August 28, 2012

How to find a content of a file linux

You can find content inside a file by using Linux grep command. eg : If you want to find the usage of text called "Hello". You can type as follows:

grep -r hello .

-r option means read all files under each directory, recursively
hello - means the content what you want to search
. - means the path for this scenario it means from current folder.(You can use absolute path as well eg: /home/gayan/)

Enjoy ~

Wednesday, August 1, 2012

Database Access Object Pattern using PHP


The simplest web widget to the most complex online e-commerce website have one thing in
common: they deal with data. So much of programming revolves around data access and
manipulation. With the massive proliferation of the Internet, cheaper storage devices, improved understanding of analytics, and greater expectations for information access, data is being leveraged in more interesting and unique ways. The Data Access Object Design Pattern aims to help construct objects that can work easily (transparently) with all of this data.

Programming typically can be a lot of repetition. This was especially true before more popular frameworks started being released. Most PHP programmers can count into the double digits the number of CRUD (create, read, update, delete) applications they’ve had to make. One of the major portions of repetition in the standard create/update application is the data source manipulation. For the rest of the discussion, I’m going to stop generalizing the data source and refer to it as SQL.

In the application, a SQL statement has to be written to create the entity in the database. Next, an additional SQL statement must be written in order to provide updates to any of the individual features of that entity. The repetition involved in creating these SQL statements is not only boring but also not best practice.

Code example

First create your own database and create following table

 CREATE TABLE task (  
      id INT PRIMARY KEY AUTO_INCREMENT,  
      subject VARCHAR(255),  
      description text  
 );  

Create php file called "baseDao" and put following code

 <?php  
 class baseDao  
 {  
   private $connection;  
   public function __construct() {  
     $this->connectToDb(DB_USER, DB_PASS, DB_HOST, DB_NAME);  
   }  
   public function connectToDb($user, $pass, $host, $database) {  
     $this->connection = mysql_connect($host, $user, $pass);  
     mysql_select_db($database, $this->connection);  
   }  
   public function fetch($value, $key = NULL)  
   {  
     if (is_null($key)) {  
       $key = $this->_primaryKey;  
     }  
     $sql = "SELECT * FROM {$this->_tableName} WHERE {$key} = '" . $value . "';";  
     $results = mysql_query($sql, $this->connection);  
     $rows = array();  
     while ($result = mysql_fetch_array($results)) {  
       $rows[] = $result;  
     }  
     return $rows;  
   }  
   public function update($keyedArray)  
   {  
     $sql = "UPDATE {$this->_tableName} SET ";  
     $updates = array();  
     foreach ($keyedArray as $column=>$value) {  
       $updates[] = "{$column}='" . $value . "'" ;  
     }  
     $sql .= implode(",", $updates);  
     $sql .= " where {$this->_primaryKey}='". $keyedArray[$this->_primaryKey] . "';";  
     mysql_query($sql, $this->connection);  
   }  
      public function save($keyedArray)  
   {  
     $sql = "INSERT INTO {$this->_tableName} ";  
     $updates = array();  
     foreach ($keyedArray as $column=>$value) {  
       $updates_columns[] = "{$column}";  
       $updates_values[] = "'" . $value . "'" ;  
     }  
           $sql .= "(";  
     $sql .= implode(",", $updates_columns);  
           $sql .= ")";  
           $sql .= " VALUES (";  
     $sql .= implode(",", $updates_values);  
     $sql .= ");";  
     if (!mysql_query($sql, $this->connection))  
                echo mysql_error();  
   }  
 }  

Finally you can use the dao class as follows:


 <?php  
 //DB_USER, DB_PASS, DB_HOST, DB_NAME  
 define('DB_USER', 'root');  
 define('DB_PASS', '');  
 define('DB_HOST', 'localhost');  
 define('DB_NAME', 'blog_samples');  
 //include "baseDao.php";  
 include "taskDao.php";  
 $taskDao = new taskDao();  
 $updates=array('subject' => 'testSubjectValue', 'description' => 'testDescriptionValue');  
 $taskDao->save($updates);  
 echo "<br/>Dao pattern !<br/>";  
Good luck !

Friday, July 27, 2012

Builder design pattern using php

Software complexity is an interesting thing. The requirements for software are complex as are the functionality of a software package or product. Even the code that makes up the software is complex. The focus of the Design Pattern approach is to provide maintainability, architectural 
strength and reduced complexity. With the host of complex objects making up most software repositories, solutions involving the Builder Design Pattern have their work cut out for them.

Code example

The project contains a class that creates the complex product object. This class contains three methods to completely form it. If each of these methods is not called when creating a new product object, attributes of the class will be missing and the program will halt. These methods are setType(), setColor(), and setSize(). The initial version of this code was designed to create the object followed by the execution of each of these methods.

class Product
{
    protected $type = '';
    protected $size = '';
    protected $color = '';
    protected $price = '';

    public function setColor($color)
    {
        $this->color = $color;
    }

    public function setSize($size)
    {
        $this->size = $size;
    }

    public function setType($type)
    {
        $this->type = $type;
    }


    public function setPrice($price)
    {
        $this->price = $price;
    }

    function __toString()
    {
        $text = 'Product { ';
        $text .= ":type => " . $this->type;
        $text .= ", :size => " . $this->size;
        $text .= ", :color => " . $this->color;
        $text .= ", :price => " . $this->price;
        $text .= " }";
        return $text;
    }

}


To create a complete product object, the product configurations need to be passed individually to each of
the methods of the product class:


// our product configuration received from other functionality
$productConfigs = array(‘type’=>’shirt’, ‘size’=>’XL’, ‘color’=>’red’);
$product = new product();
$product->setType($productConfigs[‘type’]);
$product->setSize($productConfigs[‘size’]);
$product->setColor($productConfigs[‘color’]);


Having to call each one of these methods when an object is created is not best practice. Instead, an object based on the Builder Design Pattern should be used to create this product instance.


The productBuilder class is designed to accept those configuration options that are required to build
the product object. It stores both the configuration parameter and a new product instance on
instantiation. The build() method is responsible for calling each of the methods in the product class to
fully complete the product object. Finally, the getProduct() method returns the completely built
product object.




class ProductBuilder
{

    protected $product = NULL;
    protected $config = array();

    public function __construct($config){
        $this->product = new Product();
        $this->config = $config;
    }

    public function build() {
        $this->product->setType($this->config['type']);
        $this->product->setColor($this->config['color']);
        $this->product->setSize($this->config['size']);
        $this->product->setPrice($this->config['price']);
    }

    public function getProduct() {
        return $this->product;
    }
}

Note that this build() method hides the actual method calls from the code requesting the new product. If the product class changes in the future, only the build() method of the productBuilder class needs to change. This code demonstrates the creation of the product object, using the productBuilder class:


$builder = new productBuilder($productConfigs);
$builder->build();
$product = $builder->getProduct();

The Builder Design Pattern is meant to eliminate the complex creation of other objects. Using the Builder Design Pattern is not only best practice but it also reduces the chances of having to repeatedly alter pieces of code if an object’s construction and configuration methods change.

Thursday, June 14, 2012

Codeigniter - Model-View-Controller



CodeIgniter is based on the Model-View-Controller development pattern. MVC is a software approach that separates application logic from presentation. In practice, it permits your web pages to contain minimal scripting since the presentation is separate from the PHP scripting.

  • The Model represents your data structures. Typically your model classes will contain functions that help you retrieve, insert, and update information in your database.
  • The View is the information that is being presented to a user. A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of "page".
  • The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page.

CodeIgniter has a fairly loose approach to MVC since Models are not required. If you don't need the added separation, or find that maintaining models requires more complexity than you want, you can ignore them and build your application minimally using Controllers and Views. CodeIgniter also enables you to incorporate your own existing scripts, or even develop core libraries for the system, enabling you to work in a way that makes the most sense to you.

Wednesday, June 13, 2012

Codeigniter Installation Instructions


CodeIgniter is installed in four steps:
  1. Unzip the package. (http://codeigniter.com/downloads/)
  2. Upload the CodeIgniter folders and files to your server. Normally the index.php file will be at your root.
  3. Open the application/config/config.php file with a text editor and set your base URL. If you intend to use encryption or sessions, set your encryption key.
  4. If you intend to use a database, open the application/config/database.php file with a text editor and set your database settings.
If you wish to increase security by hiding the location of your CodeIgniter files you can rename the system and application folders to something more private. If you do rename them, you must open your main index.php file and set the $system_folder and $application_folder variables at the top of the file with the new name you've chosen.
For the best security, both the system and any application folders should be placed above web root so that they are not directly accessible via a browser. By default, .htaccess files are included in each folder to help prevent direct access, but it is best to remove them from public access entirely in case the web server configuration changes or doesn't abide by the .htaccess.
After moving them, open your main index.php file and set the $system_folder and $application_folder variables, preferably with a full path, e.g. '/www/MyUser/system'.
One additional measure to take in production environments is to disable PHP error reporting and any other development-only functionality. In CodeIgniter, this can be done by setting the ENVIRONMENT constant, which is more fully described on the security page.
That's it!

Getting started CodeIgniter

CodeIgniter is an Application Development Framework - a toolkit - for people who build web sites using PHP. Its goal is to enable you to develop projects much faster than you could if you were writing code from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries. CodeIgniter lets you creatively focus on your project by minimizing the amount of code needed for a given task.

CodeIgniter is right for you if:
  • You want a framework with a small footprint.
  • You need exceptional performance.
  • You need broad compatibility with standard hosting accounts that run a variety of PHP versions and configurations.
  • You want a framework that requires nearly zero configuration.
  • You want a framework that does not require you to use the command line.
  • You want a framework that does not require you to adhere to restrictive coding rules.
  • You do not want to be forced to learn a templating language (although a template parser is optionally available if you desire one).
  • You eschew complexity, favoring simple solutions.
  • You need clear, thorough documentation.


Tuesday, June 12, 2012

Can't start portgresql in F15, F16

First please login as follows in your terminal :


# su - postgres

Then type

$ pg_ctl init

---------------------------------

After execute above command try to start the server as normal way :

systemctl start postgresql.service or /etc/init.d/postgresql start

If you want to start the server from start-up please type as following in your terminal:

chkconfig postgresql on

Friday, May 11, 2012

Adapter pattern using php

Programming would be simple, but boring. Programmers would continue to build applications on top of the same technologies that they did years ago. They would never need to introduce different databases, implement new best practices, or consume different APIs. But these things do change. Luckily, programmers have the Adapter Design Pattern to help update legacy systems with new code and functionality.

The solution is to build another object, using the Adapter Design Pattern. This Adapter object works as an intermediary between the original application and the new functionality. The Adapter Design Pattern defines a new interface for an existing object to match what the new object requires.

Code Example

In the original code base of the project, an object exists that handles all of the error messages and codes called errorObject. The original programmers didn’t think their code would ever generate any errors, so they designed the system to output the errorObject’s error information directly to the console.

In this example, a 404:Not Found error is being generated. You are going to assume that the error message content and code may change, but the text will always stay in the same format.

 class ErrorObject  
 {  
   private $error;  
   public function __construct($error){  
     $this->error = $error;  
   }  
   public function getError(){  
     return $this->error;  
   }  
 }  


 class LogToConsole  
 {  
   private $errorObject;  
   public function __construct($errorObject){  
     $this->errorObject = $errorObject;  
   }  
   public function write() {  
     fwrite(STDERR, $this->errorObject->getError() . "\n");  
   }  
 }  

Here is the testing...

 include "ErrorObject.php";  
 include "LogToConsole.php";  
 /** create the new 404 error object **/  
 $error = new ErrorObject("404:Not Found");  
 /** write the error to the console **/  
 $log = new LogToConsole($error);  
 $log->write();  
How about new requirement comes that error need to output to csv format, with the code and description.
Lets look at how we going to do that with Adapter pattern.
 class LogToCsvAdapter extends ErrorObject  
 {  
   private $errorNumber, $errorText;  
   public function __construct($error)  
   {  
     parent::__construct($error);  
     $parts = explode(':', $this->getError());  
     $this->errorNumber = $parts[0];  
     $this->errorText = $parts[1];  
   }  
   public function getErrorNumber()  
   {  
     return $this->errorNumber;  
   }  
   public function getErrorText()  
   {  
     return $this->errorText;  
   }  
 }  






Here is the testing...
 include "ErrorObject.php";  
 include "LogToCsv.php";  
 include "LogToCsvAdapter.php";  
 /** create the new 404 error object adapted for csv **/  
 $error = new LogToCsvAdapter("404:Not Found");  
 /** write the error to the csv file **/  
 $log = new logToCSV($error);  
 $log-&gt;write();  




Good luck...

Wednesday, May 9, 2012

How to delete .svn files for linux

Recursively delete .svn directories


This is a simple example of a unix command, which recursively deletes subversion .svn folders. Subversion is a well-spread open-source revision control application. Every copy of source code received from subversion repository has .svn folders, which store metadata. However, if you want to use or distribute source code, these .svn folder are often not necessary.     

We use find command to find all .svn folders beginning from current directory.


eg: type : find . -type d -name .svn

It is possible to pass these directories directly to rm command, using grave accent quotes (key to left of '1')

eg: type : rm -rf `find . -type d -name .svn`

above command will remove every .svn folder beginning from current directory.

You may do not like to type each and every time so you can create shell script for that.


1) Create a file called  /usr/bin/csvn 
2) Input following codes:

#!/bin/sh
echo "recursively removing .svn folders from"
pwd
rm -rf `find . -type d -name .svn`

You may save this script to /usr/bin/csvn (or other binary folder included in path) and use later to get 'clean' project source without typing lengthy commands.

For example

$ svn checkout svn://server.com/svn/project
A    project/index.php
A    project/sourceA/a.php
A    project/sourceA/a1.php
A    project/sourceA/a2.php
A    project/sourceB/b.php
A    project/sourceB/module/lib.php
A    project/sourceC/c.php
Checked out revision 15.
$ cd project
$ csvn
recursively removing .svn folders from
/Users/anyexample/Source/project

~Good luck~

Thursday, March 29, 2012

Mercurial for first time

This is simply version control system.

Basic usage:

1). How to clone from repo?


hg clone http://www.selenic.com/repo/hello my-hello


If everything went gladly, You will see new folder in your current directory called `my-hello` . This is the directory that you have checkout from the repository.

2). How to see  revision information?

Go to your checkout folder. (my-hello). And type


hg parents



Wednesday, March 14, 2012

Libraries installation for symfony development using yum

yum install php-pdo.i686
yum install php-xml
yum install php-mbstring.i686
yum list php-pear
yum install php-pecl-apc
yum install php-process