Skip to content

Commit f96f54d

Browse files
committed
feat(database): add query builder date helpers
- Add whereDate(), whereYear(), whereMonth(), and whereDay() - Add OR variants for date-part WHERE clauses - Compile date-part expressions per database driver - Document supported operators, null handling, escaping, and index caveats - Add builder and live database coverage Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent 2ef1571 commit f96f54d

11 files changed

Lines changed: 806 additions & 0 deletions

File tree

‎system/Database/BaseBuilder.php‎

Lines changed: 295 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use CodeIgniter\Exceptions\InvalidArgumentException;
2020
use CodeIgniter\Traits\ConditionalTrait;
2121
use Config\Feature;
22+
use DateTimeInterface;
2223
use TypeError;
2324

2425
/**
@@ -774,6 +775,246 @@ public function orWhere($key, $value = null, ?bool $escape = null)
774775
return $this->whereHaving('QBWhere', $key, $value, 'OR ', $escape);
775776
}
776777

778+
/**
779+
* Generates a WHERE clause that compares the date portion of a field.
780+
*
781+
* @param non-empty-string $key Field name, optionally with comparison operator
782+
* @param mixed $value
783+
*
784+
* @return $this
785+
*
786+
* @throws InvalidArgumentException
787+
*/
788+
public function whereDate(string $key, $value, ?bool $escape = null): static
789+
{
790+
return $this->whereDatePart('date', $key, $value, 'AND ', $escape);
791+
}
792+
793+
/**
794+
* Generates an OR WHERE clause that compares the date portion of a field.
795+
*
796+
* @param non-empty-string $key Field name, optionally with comparison operator
797+
* @param mixed $value
798+
*
799+
* @return $this
800+
*
801+
* @throws InvalidArgumentException
802+
*/
803+
public function orWhereDate(string $key, $value, ?bool $escape = null): static
804+
{
805+
return $this->whereDatePart('date', $key, $value, 'OR ', $escape);
806+
}
807+
808+
/**
809+
* Generates a WHERE clause that compares the year portion of a field.
810+
*
811+
* @param non-empty-string $key Field name, optionally with comparison operator
812+
* @param mixed $value
813+
*
814+
* @return $this
815+
*
816+
* @throws InvalidArgumentException
817+
*/
818+
public function whereYear(string $key, $value, ?bool $escape = null): static
819+
{
820+
return $this->whereDatePart('year', $key, $value, 'AND ', $escape);
821+
}
822+
823+
/**
824+
* Generates an OR WHERE clause that compares the year portion of a field.
825+
*
826+
* @param non-empty-string $key Field name, optionally with comparison operator
827+
* @param mixed $value
828+
*
829+
* @return $this
830+
*
831+
* @throws InvalidArgumentException
832+
*/
833+
public function orWhereYear(string $key, $value, ?bool $escape = null): static
834+
{
835+
return $this->whereDatePart('year', $key, $value, 'OR ', $escape);
836+
}
837+
838+
/**
839+
* Generates a WHERE clause that compares the month portion of a field.
840+
*
841+
* @param non-empty-string $key Field name, optionally with comparison operator
842+
* @param mixed $value
843+
*
844+
* @return $this
845+
*
846+
* @throws InvalidArgumentException
847+
*/
848+
public function whereMonth(string $key, $value, ?bool $escape = null): static
849+
{
850+
return $this->whereDatePart('month', $key, $value, 'AND ', $escape);
851+
}
852+
853+
/**
854+
* Generates an OR WHERE clause that compares the month portion of a field.
855+
*
856+
* @param non-empty-string $key Field name, optionally with comparison operator
857+
* @param mixed $value
858+
*
859+
* @return $this
860+
*
861+
* @throws InvalidArgumentException
862+
*/
863+
public function orWhereMonth(string $key, $value, ?bool $escape = null): static
864+
{
865+
return $this->whereDatePart('month', $key, $value, 'OR ', $escape);
866+
}
867+
868+
/**
869+
* Generates a WHERE clause that compares the day portion of a field.
870+
*
871+
* @param non-empty-string $key Field name, optionally with comparison operator
872+
* @param mixed $value
873+
*
874+
* @return $this
875+
*
876+
* @throws InvalidArgumentException
877+
*/
878+
public function whereDay(string $key, $value, ?bool $escape = null): static
879+
{
880+
return $this->whereDatePart('day', $key, $value, 'AND ', $escape);
881+
}
882+
883+
/**
884+
* Generates an OR WHERE clause that compares the day portion of a field.
885+
*
886+
* @param non-empty-string $key Field name, optionally with comparison operator
887+
* @param mixed $value
888+
*
889+
* @return $this
890+
*
891+
* @throws InvalidArgumentException
892+
*/
893+
public function orWhereDay(string $key, $value, ?bool $escape = null): static
894+
{
895+
return $this->whereDatePart('day', $key, $value, 'OR ', $escape);
896+
}
897+
898+
/**
899+
* @used-by whereDate()
900+
* @used-by orWhereDate()
901+
* @used-by whereYear()
902+
* @used-by orWhereYear()
903+
* @used-by whereMonth()
904+
* @used-by orWhereMonth()
905+
* @used-by whereDay()
906+
* @used-by orWhereDay()
907+
*
908+
* @param 'date'|'day'|'month'|'year' $part
909+
* @param non-empty-string $key Field name, optionally with comparison operator
910+
* @param mixed $value
911+
*
912+
* @return $this
913+
*
914+
* @throws InvalidArgumentException
915+
*/
916+
private function whereDatePart(string $part, string $key, $value, string $type = 'AND ', ?bool $escape = null): static
917+
{
918+
[$key, $operator] = $this->parseDatePartKey($key);
919+
920+
if ($key === '') {
921+
throw new InvalidArgumentException(sprintf('%s() expects $key to be a non-empty string', debug_backtrace(0, 2)[1]['function']));
922+
}
923+
924+
$escape ??= $this->db->protectIdentifiers;
925+
926+
if (is_array($value) || $this->isSubquery($value)) {
927+
throw new InvalidArgumentException(sprintf('%s() does not accept array or subquery values', debug_backtrace(0, 2)[1]['function']));
928+
}
929+
930+
if ($value === null) {
931+
$nullOperator = match ($operator) {
932+
'=' => 'IS NULL',
933+
'!=', '<>' => 'IS NOT NULL',
934+
default => throw new InvalidArgumentException(sprintf('%s() supports null values only with =, !=, or <> operators', debug_backtrace(0, 2)[1]['function'])),
935+
};
936+
937+
$this->addWhereHavingCondition('QBWhere', [
938+
'condition' => '',
939+
'datePartComparison' => true,
940+
'escape' => $escape,
941+
'key' => $key,
942+
'nullComparison' => true,
943+
'nullOperator' => $nullOperator,
944+
'part' => $part,
945+
], $type);
946+
947+
return $this;
948+
}
949+
950+
$value = $this->normalizeDatePartValue($part, $value);
951+
$bind = $this->setBind($key, $value, $escape);
952+
953+
$this->addWhereHavingCondition('QBWhere', [
954+
'condition' => '',
955+
'datePartComparison' => true,
956+
'escape' => $escape,
957+
'key' => $key,
958+
'operator' => $operator,
959+
'part' => $part,
960+
'rawValue' => $value instanceof RawSql,
961+
'valueBind' => $bind,
962+
], $type);
963+
964+
return $this;
965+
}
966+
967+
/**
968+
* Extracts the comparison operator from date helper keys.
969+
*
970+
* @return array{string, string}
971+
*
972+
* @throws InvalidArgumentException
973+
*/
974+
private function parseDatePartKey(string $key): array
975+
{
976+
$key = trim($key);
977+
978+
if (
979+
preg_match('/\s+(?:IS(?:\s+NOT)?(?:\s+NULL)?|(?:NOT\s+)?(?:LIKE|IN|BETWEEN|EXISTS|REGEXP|RLIKE))(?:\s+.*|\s*\(.*\))?$/i', $key) === 1
980+
|| preg_match('/\s*<=>\s*$/', $key) === 1
981+
) {
982+
throw new InvalidArgumentException(sprintf('%s() supports only comparison operators: =, !=, <>, <, >, <=, >=', debug_backtrace(0, 3)[2]['function']));
983+
}
984+
985+
if (preg_match('/\s*(!=|<>|<=|>=|=|<|>)\s*$/', $key, $match) === 1) {
986+
return [rtrim(substr($key, 0, -strlen($match[0]))), trim($match[1])];
987+
}
988+
989+
return [$key, '='];
990+
}
991+
992+
/**
993+
* Converts DateTime values into deterministic date helper comparison values.
994+
*
995+
* @param 'date'|'day'|'month'|'year' $part
996+
* @param mixed $value
997+
*
998+
* @return mixed
999+
*/
1000+
private function normalizeDatePartValue(string $part, $value)
1001+
{
1002+
if ($value instanceof DateTimeInterface) {
1003+
return match ($part) {
1004+
'date' => $value->format('Y-m-d'),
1005+
'year' => (int) $value->format('Y'),
1006+
'month' => (int) $value->format('m'),
1007+
'day' => (int) $value->format('d'),
1008+
};
1009+
}
1010+
1011+
if (! $value instanceof RawSql && $part !== 'date' && (is_int($value) || (is_string($value) && preg_match('/^-?\d+$/', $value) === 1))) {
1012+
return (int) $value;
1013+
}
1014+
1015+
return $value;
1016+
}
1017+
7771018
/**
7781019
* Generates a WHERE clause that compares two columns.
7791020
*
@@ -3763,6 +4004,10 @@ private function compileWhereHavingCondition(array|RawSql|string $condition): Ra
37634004
return $this->compileBetweenComparison($condition);
37644005
}
37654006

4007+
if (($condition['datePartComparison'] ?? false) === true) {
4008+
return $this->compileDatePartComparison($condition);
4009+
}
4010+
37664011
if ($condition['escape'] === false) {
37674012
return $condition['condition'];
37684013
}
@@ -3854,6 +4099,56 @@ private function compileBetweenComparison(array $condition): string
38544099
return $condition['condition'] . $condition['key'] . $condition['not'] . ' BETWEEN :' . $condition['lowerBind'] . ': AND :' . $condition['upperBind'] . ':';
38554100
}
38564101

4102+
/**
4103+
* @used-by compileWhereHavingCondition()
4104+
*
4105+
* @param array{condition: string, datePartComparison: true, escape: bool, key: string, nullComparison?: true, nullOperator?: string, operator?: string, part: 'date'|'day'|'month'|'year', rawValue?: bool, valueBind?: string} $condition
4106+
*/
4107+
private function compileDatePartComparison(array $condition): string
4108+
{
4109+
if ($condition['escape']) {
4110+
$condition['key'] = $this->db->protectIdentifiers($condition['key'], false, true);
4111+
}
4112+
4113+
$expression = $this->compileDatePartExpression($condition['part'], $condition['key']);
4114+
4115+
if (($condition['nullComparison'] ?? false) === true) {
4116+
return $condition['condition']
4117+
. $expression
4118+
. ' ' . $condition['nullOperator'];
4119+
}
4120+
4121+
return $condition['condition']
4122+
. $expression
4123+
. ' ' . $condition['operator'] . ' '
4124+
. $this->compileDatePartValue($condition['part'], $condition['valueBind'], $condition['rawValue']);
4125+
}
4126+
4127+
/**
4128+
* Compiles a driver-specific SQL expression for Query Builder date helpers.
4129+
*
4130+
* @param 'date'|'day'|'month'|'year' $part
4131+
*/
4132+
protected function compileDatePartExpression(string $part, string $field): string
4133+
{
4134+
return match ($part) {
4135+
'date' => 'CAST(' . $field . ' AS DATE)',
4136+
'year' => 'EXTRACT(YEAR FROM ' . $field . ')',
4137+
'month' => 'EXTRACT(MONTH FROM ' . $field . ')',
4138+
'day' => 'EXTRACT(DAY FROM ' . $field . ')',
4139+
};
4140+
}
4141+
4142+
/**
4143+
* Compiles the value side for Query Builder date helpers.
4144+
*
4145+
* @param 'date'|'day'|'month'|'year' $part
4146+
*/
4147+
protected function compileDatePartValue(string $part, string $bind, bool $rawValue): string
4148+
{
4149+
return ':' . $bind . ':';
4150+
}
4151+
38574152
/**
38584153
* Escapes identifiers in GROUP BY statements at execution time.
38594154
*

‎system/Database/MySQLi/Builder.php‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,21 @@ protected function compileLockForUpdate(): string
7676
return parent::compileLockForUpdate();
7777
}
7878

79+
/**
80+
* Compiles a driver-specific SQL expression for Query Builder date helpers.
81+
*
82+
* @param 'date'|'day'|'month'|'year' $part
83+
*/
84+
protected function compileDatePartExpression(string $part, string $field): string
85+
{
86+
return match ($part) {
87+
'date' => 'DATE(' . $field . ')',
88+
'year' => 'YEAR(' . $field . ')',
89+
'month' => 'MONTH(' . $field . ')',
90+
'day' => 'DAY(' . $field . ')',
91+
};
92+
}
93+
7994
/**
8095
* Generates a platform-specific batch update string from the supplied data
8196
*/

‎system/Database/OCI8/Builder.php‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,32 @@ protected function _truncate(string $table): string
147147
return 'TRUNCATE TABLE ' . $table;
148148
}
149149

150+
/**
151+
* Compiles a driver-specific SQL expression for Query Builder date helpers.
152+
*
153+
* @param 'date'|'day'|'month'|'year' $part
154+
*/
155+
protected function compileDatePartExpression(string $part, string $field): string
156+
{
157+
if ($part === 'date') {
158+
return 'TRUNC(' . $field . ')';
159+
}
160+
161+
return 'EXTRACT(' . strtoupper($part) . ' FROM ' . $field . ')';
162+
}
163+
164+
/**
165+
* Compiles the value side for Query Builder date helpers.
166+
*
167+
* @param 'date'|'day'|'month'|'year' $part
168+
*/
169+
protected function compileDatePartValue(string $part, string $bind, bool $rawValue): string
170+
{
171+
$value = parent::compileDatePartValue($part, $bind, $rawValue);
172+
173+
return $part === 'date' && ! $rawValue ? "TO_DATE({$value}, 'YYYY-MM-DD')" : $value;
174+
}
175+
150176
/**
151177
* Compiles a delete string and runs the query
152178
*

‎system/Database/SQLSRV/Builder.php‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,20 @@ protected function compileJoinTable(string $table, bool $escape): string
110110
return $this->getFullName($table);
111111
}
112112

113+
/**
114+
* Compiles a driver-specific SQL expression for Query Builder date helpers.
115+
*
116+
* @param 'date'|'day'|'month'|'year' $part
117+
*/
118+
protected function compileDatePartExpression(string $part, string $field): string
119+
{
120+
if ($part === 'date') {
121+
return 'CAST(' . $field . ' AS DATE)';
122+
}
123+
124+
return 'DATEPART(' . strtoupper($part) . ', ' . $field . ')';
125+
}
126+
113127
/**
114128
* Generates a platform-specific insert string from the supplied data
115129
*

0 commit comments

Comments
 (0)