在这篇文章中,我们将学习如何安装并使用 postgresql 的模块,包括 chkpass, fuzzystrmatch, isn 和 hstore. 模块为数据库增加不
在这篇文章中,我们将学习如何安装并使用 postgresql 的模块,包括 chkpass, fuzzystrmatch, isn 和 hstore. 模块为数据库增加不同的功能,例如管理和监控工具、新的数据类型、操作符、函数和算法等等。我们将测试增加数据类型和算法的模块,这些模块可以让数据库具备应用的逻辑。
postgresql 被称为是“最高级的开源数据库”,过去4年我一直在 foodlets.in 上使用它,以及 cstep (center for study of science, technology and policy) 上做空间数据存储。postgresql 是一个不会让我失望的数据库。
安装模块注意: 我的运行环境是 ubuntu 10.04 和 postgresql 8.4
首先安装 postgresql-contrib 包并重启数据库服务器,然后检查 contrib 目录看是否包含一些可用模块:
1sudo apt-get install postgresql-contrib
2sudo /etc/init.d/postgresql-8.4 restart
3cd /usr/share/postgresql/8.4/contrib/
4ls
然后我们创建一个名为 module_test 的数据库:
1su postgres
2createdb module_test
然后我们将模块 chkpass, fuzzystrmatch, isn 和 hstore 应用到 module_test 数据库,执行下面命令即可:
1psql -d module_test -f chkpass.sql
2psql -d module_test -f fuzzystrmatch.sql
3psql -d module_test -f isn.sql
4psql -d module_test -f hstore.sql
接下来,我们来看看每个模块是如何使用的。
使用 chkpasschkpass 模块引入一个新的数据类型 “chkpass” 这个类型用来存储一个加密的字段,例如密码。使用方法可以从下面的 sql 里看到,存入 chkpass 字段的字符串会自动进行加密:
1create table accounts (username varchar (100), password chkpass);
2insert into accounts(username, password ) values ( 'user1' , 'pass1' );
3insert into accounts(username, password ) values ( 'user2' , 'pass2' );
然后我们可以通过下面的sql进行身份认证:
1select count (*) from accounts where username= 'user1' and password = 'pass1'
其中 = 操作符使用了 eq(column_name, text) 方法,该方法由 chkpass 模块提供用于测试是否相等。chkpass 使用 unix 的 crypt() 函数,,因此加密效果比较弱,该函数只对字符串的前8位进行加密,只要前8位相同的字符串就被认为是相等的。因此不建议在实际生产环境中使用 chkpass 模块,建议使用 pgcrypto 模块。