source: trunk/prototype/services/PostgreSQL.php @ 5998

Revision 5998, 10.2 KB checked in by cristiano, 12 years ago (diff)

Ticket #2640 - Problemas com eventos no módulo ExpressoCalendar?

Line 
1<?php
2
3class PostgreSQL implements Service
4{
5    private $con; //Conexão com o banco de dados
6    private $config; //Configuração
7    public  $error = false; //Armazena um erro caso ocorra
8   
9    public function find ( $uri, $justthese = false, $criteria = false ){
10                   
11        $map =  Config::get($uri['concept'], 'PostgreSQL.mapping');
12       
13        $criteria = ($criteria !== false) ? $this->parseCriteria ( $criteria , $map) : '';
14
15        $justthese = self::parseJustthese($justthese, $map);
16
17        return $this->execSql( 'SELECT '.$justthese['select'].' FROM '. (Config::get($uri['concept'],'PostgreSQL.concept')) .' '.$criteria );
18    }
19
20   public function read ( $uri, $justthese = false , $criteria = false){
21   
22      $map =  Config::get($uri['concept'], 'PostgreSQL.mapping');   
23      $justthese = self::parseJustthese($justthese, $map);
24      $criteria = ($criteria !== false) ? $this->parseCriteria ( $criteria , $map , ' WHERE '.$map['id'].' = \''.addslashes( $uri['id'] ).'\'') : ' WHERE '.$map['id'].' = \''.addslashes( $uri['id'] ).'\'';
25   
26      return $this->execSql( 'SELECT '.$justthese['select'].' FROM '. (Config::get($uri['concept'],'PostgreSQL.concept')) .$criteria , true );
27    }
28       
29    public function deleteAll ( $uri,   $justthese = false, $criteria = false ){
30            $map = Config::get($uri['concept'], 'PostgreSQL.mapping');
31            if(!self::parseCriteria ( $criteria , $map)) return false; //Validador para não apagar tabela inteira
32            return $this->execSql( 'DELETE FROM '.(Config::get($uri['concept'],'PostgreSQL.concept')).' '.self::parseCriteria ( $criteria ,$map) );
33    }
34
35    public function delete ( $uri, $justthese = false, $criteria = false ){
36            if(!isset($uri['id']) && !is_int($uri['id'])) return false; //Delete chamado apenas passando id inteiros
37            $map = Config::get($uri['concept'], 'PostgreSQL.mapping');
38            $criteria = ($criteria !== false) ? $this->parseCriteria ( $criteria , $map , ' WHERE '.$map['id'].' = \''.addslashes( $uri['id'] ).'\'') : ' WHERE '.$map['id'].' = \''.addslashes( $uri['id'] ).'\'';
39            return $this->execSql('DELETE FROM '.(Config::get($uri['concept'],'PostgreSQL.concept')).$criteria);
40    }
41
42    public function replace ( $uri,  $data, $criteria = false ){
43            $map = Config::get($uri['concept'], 'PostgreSQL.mapping');
44            return $this->execSql('UPDATE '.(Config::get($uri['concept'],'PostgreSQL.concept')).' '. self::parseUpdateData( $data ,$map).' '.self::parseCriteria($criteria , $map));
45    }
46               
47    public function update ( $uri,  $data ){
48            $map = Config::get($uri['concept'], 'PostgreSQL.mapping');
49            return $this->execSql('UPDATE '.(Config::get($uri['concept'],'PostgreSQL.concept')).' '. self::parseUpdateData( $data ,$map).' WHERE id = \''. addslashes( $uri['id']) .'\'');
50    }
51
52    public function create ( $uri,  $data ){   
53            return $this->execSql( 'INSERT INTO '.(Config::get($uri['concept'],'PostgreSQL.concept')).' '.self::parseInsertData( $data , $uri['concept'] ), true );
54    }
55
56    public function execSql( $sql, $unique = false )
57    {
58            if(!$this->con) $this->open( $this->config );
59
60            $rs = pg_query( $this->con, $sql );
61
62            if( is_bool( $rs ) )
63            {
64                if ( !$rs )
65                  $this->error = pg_last_error ( $this->con );
66
67                return( $rs );
68            }
69
70            if( pg_num_rows( $rs ) <= 0 )
71                return array();
72
73            $return = array();
74
75            while( $row = pg_fetch_assoc( $rs ) )
76                $return[] = $row;
77
78            return( $unique ? $return[0] : $return );
79    }
80
81    //@DEPRECATED
82    public function execResultSql( $sql, $unique = false ){
83            return $this->execSql( $sql, $unique );
84    }
85
86    public function begin( $uri ) {
87   
88        if(!$this->con)
89            $this->open( $this->config );
90       
91        $this->error = false;
92        pg_query($this->con, "BEGIN WORK");
93    }
94
95    public function commit($uri ) {
96   
97        if( $this->error !== false )
98        {
99            $error = $this->error;
100            $this->error = false;
101
102            throw new Exception( $error );
103        }
104
105        pg_query($this->con, "COMMIT");
106
107        return( true );
108    }
109
110    public function rollback( $uri ){
111   
112        pg_query($this->con, "ROLLBACK");
113    }
114
115    public function open  ( $config ){
116                       
117        $this->config = $config;
118       
119        $rs = '';
120        $rs .= ( isset($this->config['host']) && $this->config['host'] )  ? ' host='.$this->config['host'] : '' ;
121        $rs .= ( isset($this->config['user']) && $this->config['user'] )  ? ' user='.$this->config['user'] : '' ;
122        $rs .= ( isset($this->config['password']) && $this->config['password'] )  ? ' password='.$this->config['password'] : '' ;
123        $rs .= ( isset($this->config['dbname']) && $this->config['dbname'] )  ? ' dbname='.$this->config['dbname'] : '' ;
124        $rs .= ( isset($this->config['port']) && $this->config['port'] )  ? ' port='.$this->config['port'] : '' ;
125
126        if($this->con = pg_connect( $rs ))
127            return $this->con;
128
129        throw new Exception('It was not possible to enable the target connection!');
130        //$this->con = pg_connect('host='.$config['host'].' user='.$config['user'].' password='.$config['password'].' dbname='.$config['dbname'].'  options=\'--client_encoding=UTF8\'');
131    }
132
133    public function close(){
134
135            pg_close($this->con);
136           
137            $this->con = false;
138
139    }
140
141    public function setup(){}
142
143    public function teardown(){}
144
145    private static function parseInsertData( $data , $concept){
146         
147            $map = Config::get($concept, 'PostgreSQL.mapping');
148       
149            $ind = array();
150            $val = array();
151           
152            foreach ($data as $i => $v){
153                    if(!isset($map[$i])) continue;
154               
155                    $ind[] = $map[$i];
156                    $val[] = '\''.addslashes($v).'\'';
157            }
158           
159            return '('.implode(',', $ind).') VALUES ('.implode(',', $val).') RETURNING '.$map['id'].' as id';
160    }
161       
162    private static function parseUpdateData( $data , &$map){
163                                           
164            $d = array();
165            foreach ($data as $i => $v)
166            {
167                if(!isset($map[$i])) continue;
168               
169                $d[] = $map[$i].' = \''.addslashes ($v).'\'';
170            }
171           
172            return 'SET '.implode(',', $d);
173    }
174
175    private static function parseCriteria( $criteria  , &$map , $query = '' ){               
176       
177            if( isset($criteria["filter"]) && $criteria["filter"] !== NULL )
178            {
179                    /*
180                  * ex: array   (
181                  *               [0] 'OR',
182                  *               [1] array( 'OR', array( array( '=', 'campo', 'valor' ) ),
183                  *               [2] array( '=', 'campo' , 'valor' ),
184                  *               [3] array( 'IN', 'campo', array( '1' , '2' , '3' ) )
185                  *             )
186                  * OR
187                  *         array( '=' , 'campo' , 'valor' )
188                */
189                $query .= ($query === '') ?  'WHERE ('.self::parseFilter( $criteria['filter'] , $map).')' : ' AND ('.self::parseFilter( $criteria['filter'] , $map).')';
190            }
191            /*
192              * ex: array( 'table1' => 'table2' ,  'table1' => 'table2')
193              *         
194              */
195            if( isset($criteria["join"]) )
196            {
197                foreach ($criteria["join"] as $i => $v)
198                    $query .= ' AND '.$i.' = '.$v.' ';
199            }
200           
201            if( isset($criteria["group"]) )
202            {
203                    $query .= ' GROUP BY '.( is_array($criteria["group"]) ? implode(', ', $criteria["group"]) : $criteria["group"] ).' ';
204            }
205           
206            if( isset($criteria["order"]) )
207            {
208                    $query .= ' ORDER BY '.self::parseOrder( $criteria["order"], $map ).' ';
209            }
210            if( isset($criteria["limit"]) )
211            {
212                    $query .= ' LIMIT '. $criteria["limit"] .' ';
213            }
214            if( isset($criteria["offset"]) )
215            {
216                    $query .= ' OFFSET '. $criteria["offset"] .' ';
217            }
218           
219            return $query;
220    }
221   
222    private static function parseFilter( $filter ,&$map){
223   
224        if( !is_array( $filter ) || count($filter) <= 0) return null;
225               
226        $op = self::parseOperator( array_shift( $filter ) );
227       
228        if( is_array($filter[0]) )
229        {
230            $nested = array();
231
232            foreach( $filter as $i => $f )
233                if( $n = self::parseFilter( $f , $map))
234                    $nested[] = $n;
235
236               
237            return (count($nested) > 0 ) ? '('.implode( ' '.$op.' ', $nested ).')' : '';
238        }
239
240        if(!isset($map[$filter[0]])) return '';
241                 
242        $filter[0] = $map[$filter[0]];
243       
244        $igSuffix = $igPrefix = '';
245               
246        if( strpos( $op[0], 'i' ) === 0 )
247        {
248            $op[0] = substr( $op[0], 1 );
249            $filter[0] = 'upper("'.$filter[0].'")';
250            $igPrefix = 'upper(';
251            $igSuffix = ')';
252        }
253
254        if( is_array($filter[1]) )
255            return( $filter[0].' '.$op[0]." ($igPrefix'".implode( "'$igSuffix,$igPrefix'", array_map("addslashes" , $filter[1]) )."'$igSuffix)" );
256
257        return( $filter[0].' '.$op[0]." $igPrefix'".$op[1].addslashes( $filter[1] ).$op[2]."'$igSuffix" );
258    }
259
260    private static function parseOperator( $op ){
261   
262        switch(strtolower($op))
263        {
264            case 'and':
265            case 'or': return( $op );
266            case 'in': return array( $op );
267            case '^': return array( 'like', '%',  '' );
268            case '$': return array( 'like',  '', '%' );
269            case '*': return array( 'like', '%', '%' );
270            case 'i^': return array( 'ilike', '%',  '' );
271            case 'i$': return array( 'ilike',  '', '%' );
272            case 'i*': return array( 'ilike', '%', '%' );
273            default : return array( $op,  '',  '' );
274        }
275    }
276   
277    private static function parseJustthese($justthese , &$map)
278    {
279                 
280        if(!is_array($justthese)) //Caso seja um full select pegar todas as keys
281            $justthese = array_keys($map);
282
283        $return = array();
284
285        foreach ($justthese as &$value)
286        {
287            if(!isset($map[$value])) continue; //Escapa itens não existentes no mapa
288
289            if(is_array($map[$value]))
290                $return['deepness'][$value] = $map[$value];
291            else
292                $return['select'][] = $map[$value] .' as "'. $value. '"';
293        }
294       
295        $return['select'] = implode(', ', $return['select']);
296        return $return; 
297    }
298
299   private static function parseOrder($order , &$map)
300    {
301                 
302        if($notArray = !is_array($order)) //Caso seja um full select pegar todas as keys
303            $order = array( $order );
304
305        $return = array();
306
307        foreach ($order as &$value)
308        {
309            if(!isset($map[$value])) continue; //Escapa itens não existentes no mapa
310
311            $value = $map[$value];
312        }
313
314        return ( $notArray ?  $order[0] : implode(', ', $order) );
315    }
316}
317
318?>
Note: See TracBrowser for help on using the repository browser.