1 / 3
Caption Text
2 / 3
Caption Two
3 / 3
Caption Three margin testing

Wednesday, October 21, 2009

MySQL and UTF-8

MySQL and UTF-8 [Web Application Component Toolkit]

Good support from 4.1

utf-8 is utf8 in MySQL.

A collation defines the sort order for the data, it may be case sensitive or not

To find out your current setup:

SHOW VARIABLES LIKE 'character_set_database';  SHOW VARIABLES LIKE 'character_set_client'; 

To see available character sets and collations on your database:

SHOW CHARACTER SET;  SHOW COLLATION LIKE 'utf8%'; 

Character set and collation can be set per server, database, table, connection;

Server (/etc/my.cnf):

[mysqld]  ...
default-character-set=utf8
default-collation=utf8_general_ci

Database:

(CREATE | ALTER) DATABASE ... DEFAULT CHARACTER SET utf8 

Table:

(CREATE | ALTER) TABLE ... DEFAULT CHARACTER SET utf8 

Connection:

SET NAMES 'utf8'; 

A PHP mysql connection (not totally confirmed, but see tests below) defaults to a latin1 connection, so, your first query after connection should be:

mysql_query("SET NAMES 'utf8'"); 

In php versions 5.2 and later, use

mysql_set_charset('utf8',$conn);  

The CONVERT() function can convert between charsets, eg:

INSERT INTO utf8table (utf8column)  SELECT CONVERT(latin1field USING utf8) FROM latin1table;  

As mentioned in charsets, field widths may need to be increased to deal with multi-byte characters.

Code to generate a mass change of collations:

<?php   // this script will output the queries need to change all fields/tables to a different collation // it is HIGHLY suggested you take a MySQL dump prior to running any of the generated // this code is provided as is and without any warranty   die("Make a backup of your MySQL database then remove this line");   set_time_limit(0);   // collation you want to change: $convert_from = 'latin1_swedish_ci';   // collation you want to change it to: $convert_to   = 'utf8_general_ci';   // character set of new collation: $character_set= 'utf8';   $show_alter_table = true; $show_alter_field = true;   // DB login information $username = 'user'; $password = 'pass'; $database = 'table'; $host     = 'localhost';   mysql_connect($host, $username, $password); mysql_select_db($database);   $rs_tables = mysql_query(" SHOW TABLES ") or die(mysql_error());   print '<pre>'; while ($row_tables = mysql_fetch_row($rs_tables)) {     $table = mysql_real_escape_string($row_tables[0]);          // Alter table collation     // ALTER TABLE `account` DEFAULT CHARACTER SET utf8     if ($show_alter_table) {         echo("ALTER TABLE `$table` DEFAULT CHARACTER SET $character_set;\r\n");     }       $rs = mysql_query(" SHOW FULL FIELDS FROM `$table` ") or die(mysql_error());     while ($row=mysql_fetch_assoc($rs)) {                  if ($row['Collation']!=$convert_from)             continue;           // Is the field allowed to be null?         if ($row['Null']=='YES') {             $nullable = ' NULL ';         } else {             $nullable = ' NOT NULL';         }           // Does the field default to null, a string, or nothing?         if ($row['Default']==NULL) {             $default = " DEFAULT NULL";         } else if ($row['Default']!='') {             $default = " DEFAULT '".mysql_real_escape_string($row['Default'])."'";         } else {             $default = '';         }           // Alter field collation:         // ALTER TABLE `account` CHANGE `email` `email` VARCHAR( 50 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL         if ($show_alter_field) {             $field = mysql_real_escape_string($row['Field']);             echo "ALTER TABLE `$table` CHANGE `$field` `$field` $row[Type] CHARACTER SET $character_set COLLATE $convert_to $nullable $default; \r\n";         }     } }   ?>

MySQL tables, columns and connections with UTF-8

What happens when you INSERT a UTF-8 string into a MySQL database using PHP's MySQL extension? Well that depends on what string you use. If you use something like "Iñtërnâtiônàlizætiøn" then doing just about anything in MySQL will be data-safe (but, of course, the collation will be incorrect). If you have characters that don't encode the same in UTF-8 and latin1 (e.g. text in Chinese, Russian, ...) then the behaviour depends on both the table definition and the encoding of the connection to the database.


Table or column charset

latin1 (MySQL default) utf8
default connection mysql_pconnect() data is binary-safe but not encoded properly* data is binary-safe but not encoded properly*
using SET NAMES 'utf8'; data destroyed; string is converted to "????" works fine!

* It seems that MySQL will look at the data as being a series of bytes all within the latin1 codepage. If you use the same code to read and write the data then it will round-trip fine (but MySQL's collation will obviously be wrong). If you use tools with a knowledge of the data types used by MySQL, like phpMyAdmin or even mysql_dump, then the wrong encoding is obvious.

(this test was performed with PHP versions 4.4.2 and 5.1.2 and MySQL 5.0.20; PHP source for test)

Further Reading

How to Enable Remote Access To MySQL Database Server

How Do I Enable Remote Access To MySQL Database Server?

By default, MySQL database server remote access disabled for security reasons. However, some time you need to provide the remote access to database server from home or from web server.

MySQL Remote Access

You need type the following commands which will allow remote connections:

Step # 1: Login over ssh if server is outside your IDC

First, login over ssh to remote MySQL database server

Step # 2: Enable networking

Once connected you need edit the mysql configuration file my.cfg using text editor such as vi.

  • If you are using Debian Linux file is located at /etc/mysql/my.cnf location
  • If you are using Red Hat Linux/Fedora/Centos Linux file is located at /etc/my.cnf location
  • If you are using FreeBSD you need to create a file /var/db/mysql/my.cnf

# vi /etc/my.cnf

Step # 3: Once file opened, locate line that read as follows

[mysqld] 

Make sure line skip-networking is commented (or remove line) and add following line

bind-address=YOUR-SERVER-IP

For example, if your MySQL server IP is 65.55.55.2 then entire block should be look like as follows:
[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/English
bind-address = 65.55.55.2
# skip-networking
....
..
....
Where,

  • bind-address : IP address to bind to.
  • skip-networking : Don't listen for TCP/IP connections at all. All interaction with mysqld must be made via Unix sockets. This option is highly recommended for systems where only local requests are allowed. Since you need to allow remote connection this line should removed from file or put it in comment state.

Step# 4 Save and Close the file

Restart your mysql service to take change in effect:# /etc/init.d/mysql restart

Step # 5 Grant access to remote IP address

# mysql -u root -p mysqlGrant access to new database
If you want to add new database called foo for user bar and remote IP 202.54.10.20 then you need to type following commands at mysql> prompt:mysql> CREATE DATABASE foo;
mysql> GRANT ALL ON foo.* TO bar@'202.54.10.20' IDENTIFIED BY 'PASSWORD';

How Do I Grant access to existing database?

Let us assume that you are always making connection from remote IP called 202.54.10.20 for database called webdb for user webadmin, To grant access to this IP address type the following command At mysql> prompt for existing database:mysql> update db set Host='202.54.10.20' where Db='webdb';
mysql> update user set Host='202.54.10.20' where user='webadmin';

Step # 5: Logout of MySQL

Type exit command to logout mysql:mysql> exit

Step # 6: Open port 3306

You need to open port 3306 using iptables or BSD pf firewall.

A sample iptables rule to open Linux iptables firewall

/sbin/iptables -A INPUT -i eth0 -p tcp --destination-port 3306 -j ACCEPT

OR only allow remote connection from your web server located at 10.5.1.3:

/sbin/iptables -A INPUT -i eth0 -s 10.5.1.3 -p tcp --destination-port 3306 -j ACCEPT

OR only allow remote connection from your lan subnet 192.168.1.0/24:

/sbin/iptables -A INPUT -i eth0 -s 192.168.1.0/24 -p tcp --destination-port 3306 -j ACCEPT

A sample FreeBSD / OpenBSD pf rule ( /etc/pf.conf)

pass in on $ext_if proto tcp from any to any port 3306

OR allow only access from your web server located at 10.5.1.3:

pass in on $ext_if proto tcp from 10.5.1.3 to any port 3306  flags S/SA synproxy state

Step # 7: Test it

From remote system or your desktop type the command:
$ mysql -u webadmin –h 65.55.55.2 –p
Where,

  • -u webadmin: webadmin is MySQL username
  • -h IP or hostname: 65.55.55.2 is MySQL server IP address or hostname (FQDN)
  • -p : Prompt for password

You can also use telnet to connect to port 3306 for testing purpose:$ telnet 65.55.55.2 3306

MySQL Connector for OpenOffice.org 1.0

MySQL Connector for OpenOffice.org 1.0 - OpenOffice.org Wiki

(Note: I tried UnixODBC first but found utf-8 problem. Then I selected this way, so far so good. HL)

MySQL Connector for OpenOffice.org is a MySQL driver for OpenOffice.org. It can be used to connect from OpenOffice.org 3.1 to a MySQL server 5.1 or newer.

Before MySQL Connector for OpenOffice.org became available you'd have to use MySQL Connector/J (JDBC) or MySQL Connector for ODBC to connect to a MySQL server.

Therefore the driver is also referred to as a native driver in the context of OpenOffice.org. The term native driver clashes with the MySQL definition of a native driver: MySQL Connector for OpenOffice.org does not implement the MySQL Client Server protocol. Technically speaking the MySQL Connector for OpenOffice.org is implemented as a proxy on top of the MySQL Connector/C++.

The driver is delivered as an OpenOffice.org extension.

Advantages

Using MySQL Connector for OpenOffice.org has the following advantages:

  • Easy installation through the OpenOffice.org Extension Manager.
  • Seamless integration into OpenOffice.org.
  • Work on multiple MySQL schemata (databases) simultaneously
  • Connect to MySQL servers using named pipes (Windows) or Sockets (Unix)
  • No need to go through an additional Connector installation routine (ODBC/JDBC)
  • No need to configure or register an additional Connector (ODBC)
  • No need to install or configure a driver manager (ODBC)
  • No need for a Java Runtime Environment (JDBC)

Status

The MySQL Connector for OpenOffice.org is released in version 1.0, in production quality.

Tuesday, October 20, 2009

在Ubuntu下为MySQL添加ODBC驱动

在Ubuntu下为MySQL添加ODBC驱动_本本西祠2007
2009年04月15日 星期三 下午 06:06

学过Web开发的人应该都知道ODBC,这个微软自创的数据库连接方法使得在Windows下让程序连接数据库非常容易,比如Java的ODBC连 接MSSQL、Access等等。如果要开发一个跨平台跨数据库的程序,ODBC连接数据库就是一个不错的选择,只是在Linux并不像在Windows 下一样创建ODBC连接那么容易。这篇文章就是准备讲如何在Ubuntu下为MySQL添加ODBC驱动,使得在Ubuntu下也能使用ODBC连接数据 库。

让Ubuntu也可以创建ODBC连接是依靠一个开源项目叫做iODBC实现的,这个iODBC就是为了让Unix体系的系统也能使用ODBC连接,iODBC就是ODBC的开源实现。经过测试在Ubuntu 8.04和Ubuntu 8.10下均可正常工作。

首先要有MySQL,如果还未安装,一句话安装命令:

$sudo apt-get install mysql-client mysql-server

安装iODBC的驱动管理器(GTK编写的前端界面):

$sudo apt-get install iodbc

安装MySQL的ODCB连接器:

$sudo apt-get install libmydobc

启动iODBC:

$sudo iodbcadm-gtk

iODBC DSA

看 到这个界面应该感到很熟悉了吧,几乎和Windows下的ODBC连接设置界面一模一样。要给通过ODBC连接MySQL,就要加载MySQL的ODBC 驱动,单击"ODBC Drivers"标签卡,之后单击"Add a driver"按钮,在"ODBC Driver Add/Setup"对话框中依次设置如下内容:

Description of the driver:MySQL(可以随意起一个名字)
Driver file name:/usr/lib/odbc/libmyodbc.so
Setup file name:/usr/lib/odbc/libodbcmyS.so

如下图所示:

ODBC Driver Add/Setup

设 置完毕后单击"OK"按钮,即可加载MySQL的ODBC驱动,接下来就可以创建针对MySQL的ODBC连接了,单击"User DSN"或"System DSN"标签卡来单击"Add"按钮创建ODCB连接,在"Choose an ODBC Driver"对话框中可以看到刚刚添加的MySQL的ODBC驱动,选择之兵单击"Finish"按钮,将会弹出"Setup of DSN Unknown"对话框,需要设置的有"数据源名"(Data Source Name,DSN)和一些参数。数据源名通常由用户自行定义(比如"mysqldb"),参数对于MySQL的标准而言通常需要设定以下参数:

server
database
user
password

如下图所示来设置连接参数:

Setup of DSN Unknown

更多参数具体可以参考MySQL官方的连接参数资料。 设置完成之后单击『OK』按钮之后单击『Test』按钮,询问用户名和密码的对话框弹出之后输入MySQL的用户名和密码,返回"The connection DSN wastested successfully,and can be used at this time"即是设置成功。

现在就可以在Ubuntu下使用各种语言通过ODCB来连接MySQL了。

Monday, October 19, 2009

Why Microsoft can't afford Windows 7 to fail

BBC NEWS | Business | Why Microsoft can't afford Windows 7 to fail

By Tim Weber
Business editor, BBC News website

Windows 7 screenshot
Will Windows 7 allow users to forget Vista?

On Thursday, Microsoft launches Windows 7, the latest version of its operating system. Its success or failure will determine the future of the world's biggest software company.

When talking about Microsoft, it is useful to remind yourself of the sheer scale of its reach. Windows powers about 90% of the world's computers; by the company's own reckoning more than one billion people use it.

Windows also powers Microsoft. During its last financial year, a $58.4bn (£35.7bn) turnover generated an operating profit of $20.3bn (net profit: $14.6bn). Windows accounted for well over half of that.

For years, critics have claimed that Microsoft's virtual monopoly is about to end.

They say it will be brought down by a resurgent Apple, insurgent open-source rival Linux or a revolution in how we use computers, when the actual computing moves from desktop machines to the "cloud" where software runs on remote servers.

Windows without a Vista

In reality, Microsoft has been its own worst enemy. Ruthless behaviour towards rivals earned it the attention of regulators such as the European Commission and the US Department of Justice.

Windows 7 screenshot
Windows 7 is much easier to install than its predecessor

More importantly, three years ago Microsoft botched the release of Vista, the operating system that preceded Windows 7.

Vista - a bloated, difficult to install operating system - left many early users with suddenly unusable hardware and software. The disaster badly undermined Microsoft's credibility with consumers and software developers.

Today, Vista is still outshone by its eight-year-old predecessor Windows XP. One (particularly low) estimate from web metrics firm Net Applications suggests Vista has a mere 18.6% share of the market. Others put it at just over 35%, which is still a poor figure.

Among companies, "Vista is the worst-adopted operating system", according to Annette Jump, research director at Gartner, a technology research firm.

The president of Microsoft International, Jean-Philippe Courtois, opts for understatement: "We don't feel great about Vista adoption."

Windows reloaded

Windows 7 is Microsoft's one and maybe only chance to redeem itself. "We have learned a lot from what went wrong with Vista," is a mantra repeated by every Microsoft executive.

The preparations for Windows 7 have been a remarkable step up from the days of dealing with Vista
Alex Gruzen, Dell

For starters, Windows 7 is on time, arriving less than three years after the launch of Vista, which was two years overdue.

Early users report it to be fast, reliable, secure and easy to use on the move.

Most importantly, Microsoft went out of its way to avoid a repeat of its biggest Vista mistake, when it failed to prepare its partners for the new system.

Windows 7 loves Windows 95

Windows 7 screenshot
"Peek" helps users find their way around a crowded taskbar

"The Windows ecosystem is the broadest in the world, and we have to take care of that," says Mr Courtois.

Microsoft's partners have noticed the change in tack. "The preparations for Windows 7 have been a remarkable step up from the days of dealing with Vista," says Alex Gruzen, the man in charge of consumer products at the computer giant Dell.

"In the past, Microsoft looked at its operating system in isolation, and gave it to [manufacturers] to do whatever they wanted," he says. "Now they collaborate, help to figure out which third-party vendors are slowing down the system, help them improve their code."

We expect a tangible Windows 7 bounce [in PC sales]
Richard Huddy, AMD

Microsoft, promises Mr Courtois, has "worked very hard with Windows 7 to achieve applications compatibility." When it rolled out the first service pack for Vista, there were a mere 2,700 applications certified to work with the system.

At launch, Windows 7 boasts 8,500 certified apps.

And if you want to use old software on your computer, Microsoft has built in a "compatibility tool" that allows you to run applications that were built for operating systems as old as Windows 95.

Windows 7 also has a smaller "footprint" than Vista. It needs less computing power so older PCs run it quite happily. "Our PCs have gained another two years lifetime," says Chris Page, who deployed Windows 7 on nearly 700 computers in schools run by Warwickshire County Council.

Just one five-year-old laptop refused to run the new operating system, he reports.

The best or worst of times?

But is this the right time to launch an operating system? Parts of the world may be out of recession, but investment remains low and consumers are facing the prospect of rising unemployment.

The timing, however, might actually be Microsoft's biggest asset.

Windows 7 taskbar peek
The new Taskbar preview is popular with users

"Technology has always been leading economies out of recession," says George Colony, boss of tech research firm Forrester.

Despite the downturn, IT investment is growing three times faster than most economies, reports tech industry analyst IDC. Even among consumers there are still pockets of growth, especially small netbooks with their low-power processors, which cannot run Vista but deliver zippy performance under Windows 7.

The launch of the new operating system will produce "a tangible Windows 7 bounce", says Richard Huddy of chipmaker AMD.

"Along with that, we're also seeing evidence on a global scale that the recession is starting to lessen."

"The fact that Win 7 is more efficient than Windows Vista means that it's viable for lower-cost PCs, so I think we can safely say we're increasingly optimistic."

The bottom line

At Dell, Alex Gruzen sounds bullish too. Many companies have kept old computers running for at least a year longer than they would normally do. Now "there is some optimism that the refresh cycle will begin over the next year; Windows 7 certainly helps, it provides a good catalyst for it."

Windows XP logo
April 2014: the deadline for Windows XP

A changed digital world is also driving change. Consumers and corporate computer users are becoming more mobile and Windows XP simply was not built for that.

Forcing the issue, Microsoft has said it will stop supporting Windows XP in April 2014. And even if there is an extension, by then most makers of third-party software for XP will have phased out their support, says Steve Kleynhans, vice-president of research at Gartner, "which will increase the pressure to upgrade" to Windows 7.

Also, organisations testing Windows 7, such as the UK accounting firm Baker Tilly and the City of Miami, report sharply lower support and energy costs, and higher productivity, according to Stella Chernyak, the product manager for Windows 7 Enterprise.

Gartner's Steve Kleiynhans also counsels companies against the traditional wait for "Service Pack 1", because these days Microsoft rolls out upgrades and updates continuously. The service pack will be a mere catch-up for those who have failed to install them.

The bottom line for Mr Courtois: "We expect business to adopt Windows 7 much faster" than previous operating systems.

Watching rivals

Windows 7 explorer screenshot
Microsoft has tidied up Windows Explorer

At Gartner, Annette Jump is more cautious: "We don't expect that Windows 7 will drive PC shipments," although companies "really will have to" upgrade to Windows 7, because otherwise "the support costs for older PCs will be piling up".

Microsoft's timing has been helped by the fact that one of its arch rivals, Google, won't launch its lightweight operating system Chrome OS before the middle of next year, which will be plenty of time to establish Windows 7 firmly in the netbook market.

Also useful is the misstep of its other nemesis, Apple, which uncharacteristically botched its new operating system Snow Leopard, not anywhere near as badly as Vista, but enough to give Microsoft a clear run for its Windows 7 launch.

Windows' last hurrah?

"I really have to go back to Windows 95 to remember people being so excited about a new operating system," says Mr Courtois, a 25-year veteran of Microsoft.

"Windows 7 is everything that Vista promised to be and more," enthuses AMD's Richard Huddy. Dell's Alex Gruzen calls the software "outstanding."

This may be hyperbole. Gartner analyst Annette Jump, for one, calls Windows 7 "a polishing release of Windows Vista".

But most reviews have been positive, even enthusiastic. "The fact it's an operating system I see nobody complaining about [suggests] you have something that's really good and solid," argues Mr Huddy.

That alone will not banish the fundamental threats to Microsoft's business model, though.

Over the next few years there will be "a big shift to [operating system] neutral applications like browser-based apps, Java, Silverlight, Flash, .Net", says Mr Kleynhans at Gartner.

"That will limit the dominance, the factors that drive people to have Windows."

Should Microsoft rest on its Windows 7 laurels, it might end up being its most, but also its last, successful operating system.

Laptop for every pupil in Uruguay

BBC NEWS | Technology | Laptop for every pupil in Uruguay

By Verónica Psetizki
Montevideo, Uruguay

child with XO laptop
362,000 pupils in Uruguay now have the distinctive laptops.

Uruguay has joined the small number of nations providing a laptop for every child attending state primary school.

President Tabaré Vázquez presented the final XO model laptops to pupils at a school in Montevideo on 13 October.

Over the last two years 362,000 pupils and 18,000 teachers have been involved in the scheme.

The "Plan Ceibal" (Education Connect) project has allowed many families access to the world of computers and the internet for the first time.

Uruguay is part of the One Laptop Per Child scheme, an organisation set up by internet pioneer Nicholas Negroponte. His original vision was to provide laptops at $100 (£61) but they proved more expensive.

The Uruguay programme has cost the state $260 (£159) per child, including maintenance costs, equipment repairs, training for the teachers and internet connection.

The total figure represents less than 5% of the country's education budget.

Around 70% of the XO model laptops handed out by the government were given to children who did not have computers at home.

"This is not simply the handing out of laptops or an education programme. It is a programme which seeks to reduce the gap between the digital world and the world of knowledge," explained Miguel Brechner, director of the Technological Laboratory of Uruguay and in charge of Plan Ceibal.

In a similar project, every child in the tiny South Pacific nation of Niue has an OLPC laptop. In 2008, Portugal committed to giving Intel Classmate laptops to every six-10 year old in the country.

"A revolution"

In the run up to Uruguay's general election on 25 October, the project is being promoted as an achievement of the Tabaré Vázquez government.

"It's been a revolution, which has helped us enormously, but it hasn't been easy," explained Lourdes Bardino, head teacher of School 173 in Las Piedras.

Ms Bardino said that some teachers were originally opposed to the introduction of the XO laptops.

"We have a lady who's been teaching for 30 years and when they gave us the computers and the training, she asked for leave because she didn't want to have anything to do with the programme. Later she changed her mind and now computers have changed the way she teaches."

All the teachers have been given training, but the extent to which they use the laptops in the classroom is up to them.

Research carried out recently by the State Education authorities revealed that some teachers have chosen not to include computer-related work in their lesson plans.

Costs and criticisms

The laptops have an open source Linux operating system with a user interface called Sugar. It has attracted some criticism from detractors for not being mainstream.

However Mr Brechner believes that children should learn computer skills regardless of the software available. Blind children were being taught on a Microsoft Windows operating system, he said.

The annual cost of maintaining the programme, including an information portal for pupils and teachers, will be US$21 (£13) per child.

The future

Its a culture shock scenario - many countries are simply too scared to put it into practice
Miguell Brechner, head of Plan Ceibal

Now that all the schoolchildren have their computers, the authorities say that they will endeavour keep the schools connected, particularly those in rural areas, where many still do not have internet access.

There are plans to extend the scheme to secondary schools and pre-school children next year.

Organisers of the Plan Ceibal have set up a consultancy in order to advise other countries wishing to replicate the Uruguayan experience.

Mr Brechner said that Rwanda, Haiti, El Salvador, Paraguay, some provinces in Argentina and Colombia have been in touch although they have not yet decided to contract their services.

"We would help them with tenders, planning, evaluation, which software to use, how to spread the word, training, all the "know how" we have developed. We don't have a manual. It´s a culture shock scenario - many countries are simply too scared to put it into practice."

NoSQL: Distributed and Scalable Non-Relational Database Systems

NoSQL: Distributed and Scalable Non-Relational Database Systems | Linux Magazine

Non-SQL oriented distributed databases are all the rage in some circles. They're designed to scale from day 1 and offer reliability in the face of failures.

There's an interesting shift happening in the world of Web-scale data stores. A whole new breed of scalable data stores is gaining popularity very quickly. The traditional LAMP stack is starting to look like a thing of the past. For a few years now, memcached has often appeared right next to MySQL, and now the whole "data tier" is being shaken up.

While some might see it as a move away from MySQL and PostgreSQL, the traditional open source relational data stores, it's actually a higher-level change. Much of this is change is the result of a few revelations:

  1. a relational database isn't always the model or system for every piece of data
  2. relational databases are tricky to scale (especially if you start with a single monolithic configuration–they aren't distributed by design)
  3. normalization often hurts performance
  4. in many applications, primary key look-ups are all you need

The new data stores vary quite a bit in their specific features, but in general they draw from a similar set of high-level characteristics. Not all of them meet all of these, of course, but just looking at the list gives you a sense of what they're trying to accomplish.

  1. de-normalized, often schema-free, document storage
  2. key/value based, supporting lookups by key
  3. horizontal scaling
  4. built in replication
  5. HTTP/REST or easy to program APIs
  6. support for MapReduce style programming
  7. Eventually Consistent

And I could probably list another half a dozen qualities that many of them share too. But to me, the first two are the biggest departure form the traditional RDBMS. Of course, you can stick with MySQL and go non-relational. That's basically what FriendFeed did, using MySQL as the back-end to distributed key/value store.

The movement to these distributed schema-free data stores has begun to use the name NoSQL. Rather than spending a lot of time on the philosophy behind NoSQL storage systems, I'd rather highlight a few that have caught my eye for one reason or another and spend a bit of time talking about makes each stand out.

Redis

I'm not going to say too much about Redis, since I recently covered it in Redis: Lightweight key/value Store That Goes the Extra Mile. I'll just recap by saying that it's a lightweight in-memory key/value store that handles strings, sets, and lists and has an excellent core of features for manipulating those stored data types. Redis also has built-in replication support and the ability to periodically persist the data on disk so that can survive a reboot without major data loss. Redis is still one of the newer kids on the block but version 1.0 was released a few days after I last wrote about it–Murphy's Law, huh?

Redis is interesting to me because of the simplicity of its API and the fact that it takes the traditional key/value store up a notch by adding those specific data structures and provides fast atomic operations on them.

Tokyo Cabinet

Coming straight from Japan, Tokyo Cabinet is a fast and mature disk-based key/value store that feels a lot like BerkeleyDB re-written for the Web era. It is usually paired with Tokyo Tyrant, the network server that turns Tokyo Cabinet into a network service that speaks HTTP and the memcached protocol, as well as its own binary protocol.

Like the other modern DBM implementations, Tokyo Cabinet offers B-Tree, Hash, and fixed-size array-like record storage options. It stands out for me because, when used with Tokyo Tyrant, you have a modern network protocol and interface on top a stable low-level database infrastructure that lets you choose the right data structure to use. It is also relatively mature technology that's in use as part of some very high-volume Web sites.

Apache CouchDB

To quote the Apache CouchDB home page:

Apache CouchDB is a document-oriented database that can be queried and indexed in a MapReduce fashion using JavaScript. CouchDB also offers incremental replication with bi-directional conflict detection and resolution.

CouchDB provides a RESTful JSON API than can be accessed from any environment that allows HTTP requests. There are myriad third-party client libraries that make this even easier from your programming language of choice. CouchDB's built in Web administration console speaks directly to the database using HTTP requests issued from your browser.

CouchDB is written in Erlang, a robust functional programming language ideal for building concurrent distributed systems. Erlang allows for a flexible design that is easily scalable and readily extensible.

In other words, CouchDB is very buzzword compliant!

Seriously, though, CouchDB was one of the first document oriented databases really designed for the Web and to scale with the Web. The fact that it's now under the unbrella of the Apache Software Foundation speaks to the quality of the code and the relative maturity of the project.

CouchDB appeals to me because it has always seemed to be the most futuristic of the non-relational data stores I've looked at. It's written in a language designed for large, concurrent, and reliable network systems. But it also gives you the ability to tap into Map/Reduce style processing using server-side JavaScript. It sounds a little crazy (or did when it first began), but it actually works quite well. The API is simple and well thought out, which provides a very low barrier to entry too. It's also easy to have a CouchDB instance on your desktop or laptop that you can develop with and then sync to a CouchDB server in "the cloud" or in your company's data center.

CouchDB also implements a very useful versioning scheme that makes it possible to build collaborative systems without having to re-invent yet another wheel.

Riak

The newest data store on my radar, Riak bills itself as a "document oriented web database" that "combines a decentralized key-value store, a flexible map/reduce engine, and a friendly HTTP/JSON query interface to provide a database ideally suited for Web applications." It uses the eventual consistency model in an effort to maximize availability in times of network or server outages. In fact, one of the most interesting features of Riak is that you can easily control the parameters that define how available your system is in the face of problems.

Those parameters come from Eric Brewer's CAP theorem (a good read) which says that the three ingredients we should care about are varying degrees of Consistency, Availability, and Partition Tolerance. Riak, unlike other systems, doesn't force you into a specific set of CAP values. Instead, it allows you to decide on a per-request basis how stringent you'd like to be.

This control comes thanks to three variables: N, R, and W. In a distributed system, N is the number of replicas in the system. So if you write a new key/value pair with N set to 4, then 4 nodes will be expected receive a copy of it (eventually). This value is set on a per-bucket basis.

The R and W values are set on a per-request basis and control the number of nodes that the client must receive a response from to complete a successful read or write operation, R fo read and W for write. This provides very granular control over how clients can react to failed nodes in a cluster.

For good high-level overview, see this presentation from the recent NoSQL Conference in New York City.

Others

There are a surprising number of NoSQL systems available today. The ones I've noted so far have caught my eye in one way or another and each uses a different approach to providing an alternative to centralized relational database systems. There are a few others that I'm hoping to experiment with as time allows.

  • MongoDB is a VC-backed distributed schema-free database with a very impressive feature set (including additional indexes), commercial support, and mosty hands-off operation.
  • Project Voldemort is a fairly mature system that's in heavy use at LinkedIn and comes with automatic replication and partitioning.
  • MemcacheDB combines the proven BerkeleyDB storage system with a network server that speaks the memcached network protocol so you can create memcahed-like nodes that hold more data than would fit in a traditional RAM-based memcached nodes and be assured that the data is not lost after a reboot. In some respects this is similar to the Tokyo Cabinet and Tokyo Tyrant combination.

Have you dipped your toe in the NoSQL waters yet? How did it go?

Jeremy Zawodny is a software engineer at Craigslist where he works on MySQL, Search, and various back-end infrastructure. He's also the co-author of "High Performance MySQL" and blogs at http://jeremy.zawodny.com/blog/

Featured Post

Windows和Ubuntu双系统完全独立的安装方法

http://www.ubuntuhome.com/windows-and-ubuntu-install.html  | Ubuntu Home Posted by Snow on 2012/06/25 安装Windows和Ubuntu双系统时,很多人喜欢先安装windows,然...