wanglizhong
2025-05-05 9b8a7157bb9c401de973a4107f74ff3e723ec156
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
<?php
/**
 * Database Table abstract
 * 
 * @todo pretty join support
 */
class LtDbTableDataGateway
{
    public $configHandle;
    public $dbh;
    /**
     * The created field name
     * 
     * @var string 
     */
    public $createdColumn;
 
    /**
     * The modified field name
     * 
     * @var string 
     */
    public $modifiedColumn;
 
    /**
     * The table name
     * 
     * @var string 
     */
    public $tableName;
 
    /**
     * The fields array
     * 
     * @var array 
     */
    protected $fields;
 
    /**
     * The primary key
     * 
     * @var string 
     */
    protected $primaryKey;
    protected $servers;
 
    /**
     * Build table's field list
     * 
     * @return array 
     */
    protected function buildFieldList()
    {
        if (!empty($this->fields))
        {
            return true;
        }
        $servers = $this->configHandle->get('db.servers');
        $group = $this->dbh->group;
        $node = $this->dbh->node;
        $role = $this->dbh->role;
        $table = $this->tableName;
        $host = key($servers[$group][$node][$role]);
        $key = md5($group . $node . $role . $table . $host . $table);
        if (!$value = $this->configHandle->get($key))
        {
            $sql = $this->dbh->sqlAdapter->showFields($this->tableName);
            $rs = $this->dbh->query($sql);
            $this->fields = $this->dbh->sqlAdapter->getFields($rs);
            foreach($this->fields as $field)
            {
                if ($field['primary'] == 1)
                {
                    $this->primaryKey = $field['name'];
                    break;
                }
            }
 
            $value['fields'] = $this->fields;
            $value['primaryKey'] = $this->primaryKey;
            $this->configHandle->addConfig(array($key => $value));
        }
        else
        {
            $this->fields = $value['fields'];
            $this->primaryKey = $value['primaryKey'];
        }
    }
 
    /**
     * A shortcut to SELECT COUNT(*) FROM table WHERE condition
     * 
     * @param array $args 
     * @return integer 
     * @example count(array('expression' => 'id < :id', 'value' => array('id' => 10)));
     */
    public function count($args = null)
    {
        $selectTemplate = 'SELECT COUNT(*) AS total FROM %s%s';
        $where = isset($args['where']['expression']) ? ' WHERE ' . $args['where']['expression'] : '';
        $bind = isset($args['where']['value']) ? $args['where']['value'] : array();
        $join = isset($args['join']) ? ' ' . $args['join'] : '';
        $sql = sprintf($selectTemplate, $this->tableName, $join . $where);
        $queryResult = $this->dbh->query($sql, $bind);
        return $queryResult[0]['total'];
    }
 
    /**
     * Delete a row by primary key
     * 
     * @param string $primaryKeyId 
     * @return string 
     * @example delete(10);
     */
    public function delete($primaryKeyId)
    {
        $this->buildFieldList();
        $where['expression'] = $this->primaryKey . '=:' . $this->primaryKey;
        $where['value'][$this->primaryKey] = $primaryKeyId;
        return $this->deleteRows($where);
    }
 
    /**
     * Delete many rows from table
     * Please use this method carefully!
     * 
     * @param array $args 
     * @return integer 
     * @example deleteRows(array('expression' => "id > :id", 'value' => array('id' => 2)));
     */
    public function deleteRows($args = null)
    {
        $deleteTemplate = 'DELETE FROM %s%s';
        $where = isset($args['expression']) ? ' WHERE ' . $args['expression'] : '';
        $bind = isset($args['value']) ? $args['value'] : array();
        $sql = sprintf($deleteTemplate, $this->tableName, $where);
        return $this->dbh->query($sql, $bind);
    }
 
    /**
     * Fetch one row from table by primary key
     * 
     * @param string $primaryKeyId 
     * @param array $args 
     * @param boolean $useSlave 
     * @return array 
     * @example fetch(10)
     */
    public function fetch($primaryKeyId, $args = null, $useSlave = true)
    {
        $this->buildFieldList();
        $fetchRowsArgs['where']['expression'] = $this->tableName . '.' . $this->primaryKey . '=:' . $this->primaryKey;
        $fetchRowsArgs['where']['value'][$this->primaryKey] = $primaryKeyId;
        $fetchRowsArgs['fields'] = isset($args['fields']) ? $args['fields'] : null;
        $fetchRowsArgs['join'] = isset($args['join']) ? $args['join'] : null;
        $fetchResult = $this->fetchRows($fetchRowsArgs, $useSlave);
        return $fetchResult ? $fetchResult[0] : $fetchResult;
    }
 
    /**
     * Fetch many rows from table
     * 
     * @param array $args 
     * @param boolean $useSlave 
     * @return array 
     * @example fetchRows(array('where' => array('expression' => "id > :id", 'value' => array('id' => 2))));
     */
    public function fetchRows($args = null, $useSlave = true)
    {
        $this->buildFieldList();
        $selectTemplate = 'SELECT %s FROM %s%s';
        $fields = isset($args['fields']) ? $args['fields'] : '*';
        $where = isset($args['where']['expression']) ? ' WHERE ' . $args['where']['expression'] : '';
        $bind = isset($args['where']['value']) ? $args['where']['value'] : array();
        $join = isset($args['join']) ? ' ' . $args['join'] : '';
        $orderby = isset($args['orderby']) ? ' ORDER BY ' . $args['orderby'] : '';
        $groupby = isset($args['groupby']) ? ' GROUP BY ' . $args['groupby'] : '';
        $sql = sprintf($selectTemplate, $fields, $this->tableName, $join . $where . $groupby . $orderby);
        if (isset($args['limit']))
        {
            $offset = isset($args['offset']) ? $args['offset'] : 0;
            $sql = $sql . ' ' . $this->dbh->sqlAdapter->limit($args['limit'], $offset);
        }
        return $this->dbh->query($sql, $bind);
    }
 
    /**
     * Insert one row into table, then return the inserted row's pk
     * 
     * @param array $args 
     * @return string 
     * @example insert(array('name' => 'lily', 'age' => '12'));
     */
    public function insert($args = null)
    {
        $this->buildFieldList();
        $insertTemplate = 'INSERT INTO %s (%s) VALUES (%s)';
        $fields = array();
        $placeHolders = array();
        foreach($args as $field => $value)
        {
            if (isset($this->fields[$field]))
            {
                $fields[] = $field;
                $placeholders[] = ":$field";
                $values[$field] = $value;
            }
        }
        if (isset($this->fields[$this->createdColumn]) && !isset($args[$this->createdColumn]))
        {
            $fields[] = $this->createdColumn;
            $placeholders[] = ':' . $this->createdColumn;
            $values[$this->createdColumn] = time();
        }
        if (isset($this->fields[$this->modifiedColumn]) && !isset($args[$this->modifiedColumn]))
        {
            $fields[] = $this->modifiedColumn;
            $placeholders[] = ':' . $this->modifiedColumn;
            $values[$this->modifiedColumn] = time();
        }
        $sql = sprintf($insertTemplate, $this->tableName, implode(",", $fields), implode(",", $placeholders));
        $bind = $values;
        $queryResult = $this->dbh->query($sql, $bind);
        return isset($args[$this->primaryKey]) ? $args[$this->primaryKey] : $queryResult;
    }
 
    /**
     * Update one row  by primary key
     * 
     * @param string $primaryKeyId 
     * @param array $args 
     * @return integer 
     * @example update(1, array('name' => 'lily', 'age' => '18'));
     */
    public function update($primaryKeyId, $args = null)
    {
        $this->buildFieldList();
        $where['expression'] = $this->primaryKey . '=:' . $this->primaryKey;
        $where['value'][$this->primaryKey] = $primaryKeyId;
        return $this->updateRows($where, $args);
    }
 
    /**
     * Update manay rows
     * Please use this method carefully!
     * 
     * @param array $where 
     * @param array $args 
     * @return integer 
     * @example updateRows(array('expression' => "id > :id", 'value' => array('id' => 2)), array('name' => 'kiwi', 'age' => '1'));
     */
    public function updateRows($where, $args = null)
    {
        $this->buildFieldList();
        $updateTemplate = 'UPDATE %s SET %s%s';
        $fields = array();
        $bindParameters = array();
        $placeholderStyle = isset($where['value']) && array_key_exists(0, $where['value']) ? 'questionMark' : 'named';
        foreach($args as $field => $value)
        {
            if (isset($this->fields[$field]))
            {
                if ($args[$field] instanceof DbExpression)
                {
                    $fields[] = "$field=" . $args[$field]->__toString();
                }
                else
                {
                    if ('named' == $placeholderStyle)
                    {
                        $fields[] = "$field=:$field";
                        $bindParameters[$field] = $args[$field];
                    }
                    else
                    {
                        $fields[] = "$field=?";
                        $bindParameters[] = $args[$field];
                    }
                }
            }
        }
        if (isset($this->fields[$this->modifiedColumn]) && !isset($args[$this->modifiedColumn]))
        {
            if ('named' == $placeholderStyle)
            {
                $fields[] = $this->modifiedColumn . '=:' . $this->modifiedColumn;
                $bindParameters[$this->modifiedColumn] = time();
            }
            else
            {
                $fields[] = $this->modifiedColumn . '=?';
                $bindParameters[] = time();
            }
        }
        $whereCause = isset($where['expression']) ? ' WHERE ' . $where['expression'] : '';
        $bind = isset($where['value']) ? array_merge($bindParameters, $where['value']) : $bindParameters;
        $sql = sprintf($updateTemplate, $this->tableName, implode(",", $fields), $whereCause);
        return $this->dbh->query($sql, $bind);
    }
}