用户
 找回密码
 入住 CI 中国社区
搜索
查看: 3036|回复: 0
收起左侧

[核心代码 Core] CodeIgniter2.1 数据库添加支持postgres包含RETURNING查询的取值

[复制链接]
发表于 2013-3-2 18:55:12 | 显示全部楼层 |阅读模式
本帖最后由 mark35 于 2013-3-2 19:01 编辑

postgreSQL支持 INSERT|UPDATE|DELETE查询时返回指定栏目值,比如

  1. INSERT INTO user (id, name) VALUES (DEFAULT, 'new user') RETURNING id;
  2. INSERT INTO user (id, name) VALUES (DEFAULT, 'new user') RETURNING *;
复制代码
对以上任意一条SQL查询的结果对象进行取值就可以获得需要的值,

  1. $last_inset_id = $this->db->query($sql)->row()->id;
  2. or
  3. $res = $this->db->query($sql)->row_array();
  4. $last_insert_id = $res ? $res['id'] ? 0;
复制代码
但CI2默认数据库驱动如果判断是写入的语句那么返回的是bool值而不是db结果集对象。修改如下:
system/databaseDB_driver.php
添加函数

  1.     // --------------------------------------------------------------------
  2.    
  3.     /**
  4.      * Determines if a query is a "write" type with returning colums values (postgres)
  5.      * @author    [email]waiting@xiaozhong.biz[/email]
  6.      *
  7.      * @access    public
  8.      * @param    string    An SQL query string
  9.      * @return    boolean
  10.      */
  11.     function is_write_return_type($sql)
  12.     {
  13.         if ( ! preg_match('/^\s*"?(INSERT|UPDATE|DELETE)\s+?/i', $sql))
  14.         {
  15.             return FALSE;
  16.         }
  17.         return (bool) preg_match('/\sRETURNING\b.+?/i', $sql);
  18.     }
复制代码
然后此文件中约351行处代码找到

  1.         if ($this->is_write_type($sql) === TRUE)
  2.         {
  3.             // If caching is enabled we'll auto-cleanup any
  4.             // existing files related to this particular URI
  5.             if ($this->cache_on == TRUE AND $this->cache_autodel == TRUE AND $this->_cache_init())
  6.             {
  7.                 $this->CACHE->delete();
  8.             }
  9.             return TRUE;
  10.         }
复制代码
修改为

  1.         if ($this->is_write_type($sql) === TRUE)
  2.         {
  3.             // If caching is enabled we'll auto-cleanup any
  4.             // existing files related to this particular URI
  5.             if ($this->cache_on == TRUE AND $this->cache_autodel == TRUE AND $this->_cache_init())
  6.             {
  7.                 $this->CACHE->delete();
  8.             }

  9.             // waiting ADD
  10.             if ( ! $this->is_write_return_type($sql))
  11.             {
  12.                 return TRUE;
  13.             } // ADD END
  14.         }

复制代码
注:通过 RETURNING PK 方式返回值这才是正确的、严谨的获得 last insert id的方法。CI定义的 $this-db->insert_id() 方法是根据垃圾mysql的方式处理得来的


首发 http://xiaozhong.biz/thread-312-1-1.html

本版积分规则