88use Illuminate \Database \Eloquent \Concerns \HasAttributes ;
99use Illuminate \Support \Facades \DB ;
1010use Illuminate \Support \Str ;
11+ use Tinderbox \ClickhouseBuilder \Query \Enums \Operator ;
12+ use Tinderbox \ClickhouseBuilder \Query \TwoElementsLogicExpression ;
1113
1214class BaseModel
1315{
@@ -29,6 +31,13 @@ class BaseModel
2931 */
3032 protected $ tableForInserts ;
3133
34+ /**
35+ * Use this field for OPTIMIZE TABLE OR ALTER TABLE (also DELETE) queries
36+ *
37+ * @var string
38+ */
39+ protected $ tableSources ;
40+
3241 /**
3342 * Indicates if the model exists.
3443 *
@@ -56,6 +65,15 @@ public function getTableForInserts()
5665 return $ this ->tableForInserts ?? $ this ->getTable ();
5766 }
5867
68+ /**
69+ * Use this field for OPTIMIZE TABLE OR ALTER TABLE (also DELETE) queries
70+ * @return string
71+ */
72+ public function getTableSources ()
73+ {
74+ return $ this ->tableSources ?? $ this ->getTable ();
75+ }
76+
5977 /**
6078 * @return Client
6179 */
@@ -268,15 +286,54 @@ public function __set($key, $value)
268286 * Optimize table. Using for ReplacingMergeTree, etc.
269287 * @source https://clickhouse.tech/docs/ru/sql-reference/statements/optimize/
270288 * @param bool $final
289+ * @param string|null $partition
271290 * @return \ClickHouseDB\Statement
272291 */
273- public static function optimize ($ final = false )
292+ public static function optimize ($ final = false , $ partition = null )
274293 {
275- $ sql = "OPTIMIZE TABLE " . (new static )->getTable ();
294+ $ sql = "OPTIMIZE TABLE " . (new static )->getTableSources ();
295+ if ($ partition ) {
296+ $ sql .= " PARTITION $ partition " ;
297+ }
276298 if ($ final ) {
277299 $ sql .= " FINAL " ;
278300 }
279301 return static ::getClient ()->write ($ sql );
280302 }
281303
304+ /**
305+ * @param TwoElementsLogicExpression|string|Closure $column
306+ * @param string|null $operator
307+ * @param int|float|string|null $value
308+ * @param string $concatOperator Operator::AND for example
309+ * @return Builder
310+ */
311+ public static function where ($ column , $ operator = null , $ value = null , string $ concatOperator = Operator::AND )
312+ {
313+ $ static = new static ;
314+ $ builder = (new Builder )->select (['* ' ])
315+ ->from ($ static ->getTable ())
316+ ->setSourcesTable ($ static ->getTableSources ());
317+ if (is_null ($ value )) {
318+ // Fix func_num_args() in where clause in BaseBuilder
319+ $ builder ->where ($ column , $ operator );
320+ } else {
321+ $ builder ->where ($ column , $ operator , $ value , $ concatOperator );
322+ }
323+ return $ builder ;
324+ }
325+
326+ /**
327+ * @param string $expression
328+ * @return Builder
329+ */
330+ public static function whereRaw (string $ expression )
331+ {
332+ $ static = new static ;
333+ return (new Builder )->select (['* ' ])
334+ ->from ($ static ->getTable ())
335+ ->setSourcesTable ($ static ->getTableSources ())
336+ ->whereRaw ($ expression );
337+ }
338+
282339}
0 commit comments