00001 <?php
00002 require_once dirname(__FILE__) . '/dbsqlbuilder.select.cls.php';
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013 class DBSqlBuilderCount extends DBSqlBuilderSelect {
00014 protected function get_sql_template() {
00015 return 'SELECT COUNT(%distinct%!fields) AS c FROM %!from%join%where';
00016 }
00017
00018 protected function get_substitutes() {
00019 $table = $this->query->get_table();
00020 $ret = array(
00021 '%!fields' => $this->get_fieldnames($this->get_field_array(), $table),
00022 '%!from' => $this->get_table_and_alias($table),
00023 '%distinct' => $this->get_feature_sql($this->params, 'distinct', 'DISTINCT '),
00024 '%where' => $this->get_where($this->query->get_wheres()),
00025 '%join' => $this->get_join($this->query->get_subqueries()),
00026 '%having' => $this->get_having($this->query->get_havings()),
00027 );
00028 return $ret;
00029 }
00030
00031
00032
00033
00034
00035
00036 protected function get_field_array() {
00037 $ret = array();
00038 $group_by = Arr::get_item($this->params, 'group_by', array());
00039 if ($group_by) {
00040 foreach($group_by as $g) {
00041 $f = $g['field'];
00042 $ret[] = $f;
00043 }
00044 }
00045 else {
00046 $ret = $this->fields;
00047 }
00048 return $ret;
00049 }
00050
00051 protected function get_fieldnames($arr_fields, IDBTable $table) {
00052 $count_fields = '*';
00053 $fieldnames = array();
00054 if (count($arr_fields) == 0) {
00055
00056 if (count($this->query->get_subqueries()) > 0) {
00057 $arr_fields = array_keys($table->get_table_keys());
00058 }
00059 }
00060
00061 foreach($arr_fields as $key => $name) {
00062 if (is_numeric($key)) {
00063 $fieldnames[] = $this->prefix_column($name, $table);
00064 }
00065 else {
00066 if (!$this->is_function($key)) {
00067 $fieldnames[] = $this->prefix_column($key, $table);
00068 }
00069 }
00070 }
00071 if (count($fieldnames) > 0) {
00072 $count_fields = implode(', ', $fieldnames);
00073 }
00074
00075 if ($count_fields == '*') {
00076 unset($this->params['distinct']);
00077 }
00078
00079 return $count_fields;
00080 }
00081 }