### Complete Example: Fresh Laravel Application Setup Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/ServiceProvider.md A step-by-step guide to setting up the PHP ClickHouse Laravel package in a new Laravel application, including installation, environment variable configuration, model creation, and basic usage. ```php // In a fresh Laravel application: // 1. Install package // composer require glushkovds/phpclickhouse-laravel // 2. Set .env CLICKHOUSE_HOST=localhost CLICKHOUSE_PORT=8123 CLICKHOUSE_DATABASE=default // 3. Service provider auto-registers (package discovery) // 4. Create model // app/Models/Clickhouse/Event.php class Event extends BaseModel { protected $table = 'events'; } // 5. Use model $event = Event::create(['name' => 'signup']); // Service provider has: // - Registered 'clickhouse' driver // - Set up Connection instance // - Configured event dispatcher // - Merged configurations ``` -------------------------------- ### Example Usage of Cluster Manager Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/types.md Shows how to get the cluster manager from a connection and access the active node's connection host. ```php $cluster = $connection->getCluster(); $activeHost = $cluster->getActiveNode()->getConnectHost(); ``` -------------------------------- ### Install phpClickHouse-Laravel Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/README.md Install the package using Composer. ```bash composer require glushkovds/phpclickhouse-laravel ``` -------------------------------- ### Complete MergeTree Table Migration Example Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Migration.md A full example demonstrating the creation of a 'user_events' MergeTree table with various column types, default values, and ordering. Includes necessary imports. ```php columns([ $table->uInt64('id'), $table->datetime('created_at', 3) ->default(new Expression('now64(3)')), $table->string('user_id'), $table->string('event_name'), $table->string('event_data')->nullable(), ]); $table->orderBy('created_at'); }); } public function down() { static::write('DROP TABLE user_events'); } }; ``` -------------------------------- ### ClickHouse Cluster Migration Example Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/README.md Example of a migration for a ClickHouse table in a cluster environment. Migrations run on all nodes. ```php getClient(); $statement = $client->select('SELECT COUNT(*) as cnt FROM my_table'); // Via query builder $rows = $connection->query() ->select(['*']) ->from('my_table') ->where('status', 'active') ->getRows(); // Direct query execution $connection->statement( 'INSERT INTO my_table (id, name) VALUES (?, ?)', [1, 'John'] ); ``` -------------------------------- ### Cluster Mode Configuration Example Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Connection.md Example of a ClickHouse cluster configuration for Laravel's `config/database.php` file. Defines multiple hosts for high availability. ```php 'clickhouse' => [ 'driver' => 'clickhouse', 'cluster' => [ ['host' => 'clickhouse01', 'port' => 8123], ['host' => 'clickhouse02', 'port' => 8123], ], 'database' => env('CLICKHOUSE_DATABASE', 'default'), 'username' => env('CLICKHOUSE_USERNAME', 'default'), 'password' => env('CLICKHOUSE_PASSWORD', ''), 'timeout_connect' => (int)env('CLICKHOUSE_TIMEOUT_CONNECT', 2), 'timeout_query' => (int)env('CLICKHOUSE_TIMEOUT_QUERY', 2), 'https' => (bool)env('CLICKHOUSE_HTTPS', false), 'retries' => (int)env('CLICKHOUSE_RETRIES', 0), 'settings' => [ 'max_partitions_per_insert_block' => 300, ], 'fix_default_query_builder' => true, ], ``` -------------------------------- ### SQL Generation Example Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/README.md Demonstrates generating ClickHouse-specific SQL from a fluent builder query, including GROUP BY and SETTINGS. ```php // Generated from: MyTable::select(['id', new RawColumn('COUNT(*)', 'cnt')]) ->where('status', 'active') ->groupBy('status') ->settings(['max_threads' => 2]) ->getRows(); // Produces: SELECT `id`, COUNT(*) AS `cnt` FROM `my_table` WHERE `status` = :0 GROUP BY `status` SETTINGS max_threads=2 ``` -------------------------------- ### Complete Event Example Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Events.md Demonstrates registering multiple event listeners and creating a model, showing the flow of 'creating', 'created', and 'saved' events. ```php class MyTable extends BaseModel { protected $table = 'my_table'; } // Register listeners MyTable::listen('creating', function ($model) { // Validate data if (empty($model->name)) { Log::warning('Attempt to create model without name'); return false; } // Sanitize $model->name = trim($model->name); return true; }); MyTable::listen('created', function ($model) { // Log creation Log::info('Model created', [ 'id' => $model->id, 'name' => $model->name, ]); }); // Create model $result = MyTable::create(['name' => 'John']); // 'creating' event fires, listener returns true // Model is inserted // 'created' event fires, listener logs the event // 'saved' event fires ``` -------------------------------- ### Example Usage of ClickHouse Client Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/types.md Demonstrates how to obtain the ClickHouse client instance from a Laravel connection and execute a simple SELECT query. ```php $client = DB::connection('clickhouse')->getClient(); $statement = $client->select('SELECT * FROM my_table'); ``` -------------------------------- ### Create ClickHouse Table with Raw SQL Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Migration.md Example of creating a ClickHouse table using the `write` method for raw SQL execution. ```php class CreateMyTable extends Migration { public function up() { static::write(' CREATE TABLE my_table ( id UInt32, created_at DateTime, name String ) ENGINE = MergeTree() ORDER BY (id) '); } public function down() { static::write('DROP TABLE my_table'); } } ``` -------------------------------- ### Configuration Override Precedence Example Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/ServiceProvider.md Demonstrates how configuration values are merged, with user-defined settings in `config/database.php` taking precedence over environment variables and package defaults. ```php // config/clickhouse.php 'host' => env('CLICKHOUSE_HOST', 'localhost') // .env CLICKHOUSE_HOST=custom.example.com // config/database.php 'clickhouse' => [ 'host' => 'override.example.com', ] // Final: 'override.example.com' (database.php takes precedence) ``` -------------------------------- ### Create ReplicatedMergeTree Table with Raw SQL Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Migration.md Example of creating a replicated table using raw SQL, specifying the engine and replication paths. ```php class CreateReplicatedTable extends Migration { protected $connection = 'clickhouse'; public function up() { static::write(' CREATE TABLE my_table ( id UInt32, name String ) ENGINE = ReplicatedMergeTree( "/clickhouse/tables/default.my_table", "{replica}" ) ORDER BY (id) '); } public function down() { static::write('DROP TABLE my_table'); } } ``` -------------------------------- ### Switching ClickHouse Cluster Nodes Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/README.md Demonstrates how to get the current node host and switch to the next available node in a ClickHouse cluster. ```php $row = new MyTable(); echo $row->getThisClient()->getConnectHost(); // will print 'clickhouse01' $row->resolveConnection()->getCluster()->slideNode(); echo $row->getThisClient()->getConnectHost(); // will print 'clickhouse02' ``` -------------------------------- ### Example Usage of LaravelStatement Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/types.md Demonstrates how to execute a select query and access its results as both associative arrays and objects, as well as getting the total row count. ```php $statement = MyTable::select(['id', 'name'])->get(); // Get as arrays foreach ($statement->rows() as $row) { echo $row['name']; } // Get as objects foreach ($statement->all() as $obj) { echo $obj->name; } echo $statement->count(); // Total rows ``` -------------------------------- ### get() Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md Executes a SELECT query and returns the result as a Statement object. ```APIDOC ## get() ### Description Execute a SELECT query and return a Statement. ### Parameters #### Parameters - **bindings** (array) - Optional - Query parameter bindings (e.g., `['id' => 1]`). ### Returns `Statement` — Statement object from ClickHouseDB\Client. ### Example ```php $statement = MyTable::select(['id', 'name']) ->where('status', 'active') ->get(); echo $statement->count(); // Number of rows ``` ``` -------------------------------- ### Dispatch 'creating' event with halt Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Events.md Internal use example showing how to dispatch the 'creating' event. If halt is true, the event dispatching stops if any listener returns false. ```php // In BaseModel::save() if ($this->fireModelEvent('creating') === false) { return false; } ``` -------------------------------- ### Integrate Schema Builder with ClickHouse Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Grammars.md Demonstrates how to get the SchemaBuilder instance from a ClickHouse database connection to interact with tables. ```php $connection = DB::connection('clickhouse'); $builder = $connection->getSchemaBuilder(); // Uses SchemaGrammar internally if ($builder->hasTable('my_table')) { // Table exists } ``` -------------------------------- ### Define Table Schema with createMergeTree Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Migration.md Example of defining a table's schema, including columns and ordering, using the `createMergeTree` method. ```php class CreateMyTable extends Migration { public function up() { static::createMergeTree('my_table', function (MergeTree $table) { $table->columns([ $table->uInt32('id'), $table->datetime('created_at', 3)->default(new Expression('now64(3)')), $table->string('name'), $table->int32('age'), ]); $table->orderBy('id'); }); } public function down() { static::write('DROP TABLE my_table'); } } ``` -------------------------------- ### Create ReplicatedMergeTree Table with createMergeTree Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Migration.md Example of creating a replicated table using `createMergeTree`. The engine is automatically set to `ReplicatedMergeTree` in cluster mode. ```php class CreateReplicatedTable extends Migration { public function up() { static::createMergeTree('my_table', function (MergeTree $table) { $table->columns([ $table->uInt32('id'), $table->string('name'), ]) ->orderBy('id'); // Engine is automatically set to ReplicatedMergeTree in cluster mode }); } public function down() { static::write('DROP TABLE my_table'); } } ``` -------------------------------- ### Query Data from ClickHouse Model Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/README.md Example of selecting specific fields, applying filters, grouping, setting query parameters, and retrieving rows. ```php $rows = MyTable::select(['field_one', new RawColumn('sum(field_two)', 'field_two_sum')]) ->where('created_at', '>', '2020-09-14 12:47:29') ->groupBy('field_one') ->settings(['max_threads' => 3]) ->getRows(); ``` -------------------------------- ### Get Query Builder Instance from Connection Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/types.md Retrieves the query builder instance for constructing ClickHouse queries. ```php public function query(): Builder ``` -------------------------------- ### Dispatch 'created' and 'saved' events without halt Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Events.md Internal use example demonstrating how to dispatch 'created' and 'saved' events. With halt set to false, all listeners will be executed. ```php // In BaseModel::create() $model->fireModelEvent('created', false); $model->fireModelEvent('saved', false); ``` -------------------------------- ### Explicit Cluster Access and Manual Failover Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Cluster.md Demonstrates how to explicitly access the Cluster object from a database connection to get the active node's host and perform manual failover using `slideNode()` when an error condition occurs. ```php use Illuminate\Support\Facades\DB; $connection = DB::connection('clickhouse'); $cluster = $connection->getCluster(); // Get current host $currentHost = $cluster->getActiveNode()->getConnectHost(); echo "Connected to: $currentHost"; // Manual failover if ($someErrorCondition) { $cluster->slideNode(); $newHost = $cluster->getActiveNode()->getConnectHost(); echo "Switched to: $newHost"; } ``` -------------------------------- ### Cluster Database Configuration Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/configuration.md Configure a ClickHouse cluster connection in `config/database.php` by providing an array of node configurations. This setup is for distributed ClickHouse deployments. ```php 'connections' => [ 'clickhouse' => [ 'driver' => 'clickhouse', 'cluster' => [ ['host' => 'clickhouse01', 'port' => 8123], ['host' => 'clickhouse02', 'port' => 8123], ['host' => 'clickhouse03', 'port' => 8123], ], 'database' => env('CLICKHOUSE_DATABASE', 'default'), 'username' => env('CLICKHOUSE_USERNAME', 'default'), 'password' => env('CLICKHOUSE_PASSWORD', ''), 'timeout_connect' => (int) env('CLICKHOUSE_TIMEOUT_CONNECT', 2), 'timeout_query' => (int) env('CLICKHOUSE_TIMEOUT_QUERY', 2), 'https' => (bool) env('CLICKHOUSE_HTTPS', false), 'retries' => (int) env('CLICKHOUSE_RETRIES', 0), 'settings' => [ 'max_partitions_per_insert_block' => (int) env('CLICKHOUSE_MAX_PARTITIONS_PER_INSERT_BLOCK', 300), ], 'fix_default_query_builder' => (bool) env('CLICKHOUSE_FIX_DEFAULT_QUERY_BUILDER', true), ], ], ``` -------------------------------- ### Single Node Database Configuration Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/configuration.md Define a single ClickHouse connection in `config/database.php` using environment variables for configuration. This setup is for connecting to a standalone ClickHouse instance. ```php 'connections' => [ 'clickhouse' => [ 'driver' => 'clickhouse', 'host' => env('CLICKHOUSE_HOST', 'localhost'), 'port' => (int) env('CLICKHOUSE_PORT', 8123), 'database' => env('CLICKHOUSE_DATABASE', 'default'), 'username' => env('CLICKHOUSE_USERNAME', 'default'), 'password' => env('CLICKHOUSE_PASSWORD', ''), 'timeout_connect' => (int) env('CLICKHOUSE_TIMEOUT_CONNECT', 2), 'timeout_query' => (int) env('CLICKHOUSE_TIMEOUT_QUERY', 2), 'https' => (bool) env('CLICKHOUSE_HTTPS', false), 'retries' => (int) env('CLICKHOUSE_RETRIES', 0), 'settings' => [ 'max_partitions_per_insert_block' => (int) env('CLICKHOUSE_MAX_PARTITIONS_PER_INSERT_BLOCK', 300), ], 'fix_default_query_builder' => (bool) env('CLICKHOUSE_FIX_DEFAULT_QUERY_BUILDER', true), ], ], ``` -------------------------------- ### ClickhouseServiceProvider Boot Method Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/INDEX.md Boots the service provider. ```php boot(): void ``` -------------------------------- ### Register ClickHouse Service Provider Manually Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/ServiceProvider.md Demonstrates how to manually register the ClickhouseServiceProvider in Lumen or custom Laravel setups where package auto-discovery is disabled. This is typically done in the `bootstrap/app.php` file. ```php $app->register(\\PhpClickHouse\\ClickhouseServiceProvider::class); ``` -------------------------------- ### Update Query Builder Usage Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/docs/known_issues.md Change your code from using ->get() to ->get()->rows() to adapt to the breaking changes introduced by the query builder fix. This changes the return type from a Collection to an array. ```php $rows = DB::table('my-table') ... ->get() // Statement ->rows(); // array ``` -------------------------------- ### avg() Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md Gets the average value of a specified column. ```APIDOC ## avg() ### Description Gets the average value of a specified column. ### Method `avg($column): mixed` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **$column** (mixed) - Required - The column to calculate the average from. ### Request Example ```php $average = MyTable::avg('age'); ``` ### Response #### Success Response (200) - **mixed** - The average value. #### Response Example None provided in source. ``` -------------------------------- ### max() Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md Gets the maximum value of a specified column. ```APIDOC ## max() ### Description Gets the maximum value of a specified column. ### Method `max($column): mixed` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **$column** (mixed) - Required - The column to find the maximum value from. ### Request Example ```php $maxAge = MyTable::max('age'); ``` ### Response #### Success Response (200) - **mixed** - The maximum value found in the column. #### Response Example None provided in source. ``` -------------------------------- ### min() Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md Gets the minimum value of a specified column. ```APIDOC ## min() ### Description Gets the minimum value of a specified column. ### Method `min($column): mixed` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **$column** (mixed) - Required - The column to find the minimum value from. ### Request Example ```php $minAge = MyTable::min('age'); ``` ### Response #### Success Response (200) - **mixed** - The minimum value found in the column. #### Response Example None provided in source. ``` -------------------------------- ### Create a Query Builder Instance Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Connection.md Instantiate the query builder using the query method. This allows for fluent construction of ClickHouse queries. ```php public function query(): Builder ``` ```php $builder = DB::connection('clickhouse')->query(); $rows = $builder->select(['*'])->from('my_table')->getRows(); ``` -------------------------------- ### count() Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md Gets the count of rows. This is also listed as a query execution method. ```APIDOC ## count() ### Description Gets the count of rows. This is also listed as a query execution method. ### Method `count(): int` ### Parameters None ### Request Example None provided in source. ### Response #### Success Response (200) - **int** - The number of rows. #### Response Example None provided in source. ``` -------------------------------- ### Get Statement Row Count Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/types.md Retrieve the total number of rows returned by the query. ```php public function count(): int ``` -------------------------------- ### Initialize Cluster with Node Configurations Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Cluster.md Instantiate the Cluster class with an array of node configuration details. The constructor attempts to connect to each node and sets the first available one as active. It caches clients for reuse and throws a TransportException if no nodes are available. ```php $nodeConfigs = [ ['host' => 'clickhouse01', 'port' => 8123, 'database' => 'default', 'username' => 'default', 'password' => ''], ['host' => 'clickhouse02', 'port' => 8123, 'database' => 'default', 'username' => 'default', 'password' => ''], ]; $cluster = new Cluster($nodeConfigs); ``` -------------------------------- ### sum() Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md Gets the sum of values in a specified column. Returns 0 if no rows are found. ```APIDOC ## sum() ### Description Gets the sum of values in a specified column. Returns 0 if no rows are found. ### Method `sum($column): mixed` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **$column** (mixed) - Required - The column to sum values from. ### Request Example ```php $total = MyTable::sum('amount'); ``` ### Response #### Success Response (200) - **mixed** - The sum of values, or 0 if no rows. #### Response Example None provided in source. ``` -------------------------------- ### Get Table Name Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/BaseModel.md Retrieve the default table name associated with the model instance. ```php $model = new MyTable(); echo $model->getTable(); // Outputs: my_table ``` -------------------------------- ### getEventDispatcher() Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Events.md Get the event dispatcher instance. Returns the configured dispatcher or null if none is set. ```APIDOC ### getEventDispatcher() Get the event dispatcher instance. ```php public static function getEventDispatcher(): ?Dispatcher ``` **Returns:** `Dispatcher|null` — The dispatcher, or null if not set. **Example:** ```php $dispatcher = MyTable::getEventDispatcher(); if ($dispatcher) { // Dispatcher is configured } ``` ``` -------------------------------- ### Create a Migration using Raw SQL Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/README.md Use the Migration class to define table creation and deletion using raw SQL statements. ```php 'Jane', 'value' => 100]); // Fires 'creating' and 'created' events ``` -------------------------------- ### Get Active Node from Cluster Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/types.md Retrieves the currently active ClickHouse client node from the cluster manager. ```php public function getActiveNode(): Client ``` -------------------------------- ### Configure Multiple ClickHouse Connections Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/README.md Demonstrates setting up and using multiple ClickHouse database connections within Laravel's configuration. ```php // Define in config/database.php 'connections' => [ 'clickhouse' => [...], 'clickhouse_analytics' => [ 'driver' => 'clickhouse', 'host' => 'analytics.example.com', ... ], ] // Use in models class MyTable extends BaseModel { protected $connection = 'clickhouse'; } class AnalyticsTable extends BaseModel { protected $connection = 'clickhouse_analytics'; } ``` -------------------------------- ### Get ClickHouse Client Instance from Connection Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/types.md Retrieves the low-level ClickHouse client instance from the Laravel database connection. ```php public function getClient(): Client ``` -------------------------------- ### Client database Method Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/INDEX.md Selects the database to use for subsequent operations. ```php database(string $name): self ``` -------------------------------- ### Run Migrations in Pretend Mode Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Migration.md Use the `--pretend` flag to see the SQL output for migrations without executing them. This is useful for dry-runs. ```bash php artisan migrate --pretend ``` -------------------------------- ### Get SELECT Query Results as Array Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/types.md Executes a SELECT query using the query builder and returns the results as an array. ```php public function getRows(array $bindings = []): array ``` -------------------------------- ### Configure Cluster Mode Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/README.md Set up cluster configuration in `config/database.php` for multi-node deployments. ```php // Configure in config/database.php 'cluster' => [ ['host' => 'node1', 'port' => 8123], ['host' => 'node2', 'port' => 8123], ] // Use transparently $rows = MyTable::select(['*'])->getRows(); // Manual failover $connection->getCluster()->slideNode(); ``` -------------------------------- ### Get Maximum Value of a Column Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md The `max` method retrieves the maximum value from a specified column for the rows matching the query. ```php $maxAge = MyTable::max('age'); ``` -------------------------------- ### Instance Model Methods Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/types.md Provides instance methods for interacting with ClickHouse models, such as filling attributes, saving, and retrieving table information. ```php public function fill(array $attributes): self public function save(array $options = []): bool public function getTable(): string public function getTableForInserts(): string public function getTableSources(): string public function getAttribute(string $key): mixed public function setAttribute(string $key, $value): self ``` -------------------------------- ### Constructor Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md Initializes a new instance of the Builder class. It can optionally accept a ClickHouse client instance and a connection name. ```APIDOC ## Constructor ### Description Initializes a new instance of the Builder class. It can optionally accept a ClickHouse client instance and a connection name. ### Parameters #### Parameters - **client** (ClickHouseDB\Client) - Optional - ClickHouse client instance. Auto-resolved if null. - **connection** (string) - Optional - Database connection name (e.g., 'clickhouse'). ### Example ```php $builder = new Builder(null, 'clickhouse'); ``` ``` -------------------------------- ### Configure Buffer Table Inserts Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/README.md Sets up a model to use a buffer table for inserts while optimizing or deleting from a primary table. ```php class Events extends BaseModel { protected $table = 'events_buffer'; // Read from buffer protected $tableForInserts = 'events_buffer'; // Insert to buffer protected $tableSources = 'events'; // Optimize/delete from actual table } ``` -------------------------------- ### Get Statement Rows as Objects Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/types.md Retrieve query results as an array of stdClass objects. Each row is converted into an object for Laravel-style access. ```php public function all(): array ``` -------------------------------- ### Prepare Query Parameters Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Grammars.md Prepares a SQL query string with placeholder parameters for safe execution with ClickHouse. This is useful for preventing SQL injection. ```php use PhpClickHouseLaravel\QueryGrammar; $sql = 'SELECT * FROM users WHERE id = ? AND status = ?'; $prepared = QueryGrammar::prepareParameters($sql); // Prepared: 'SELECT * FROM users WHERE id = :0 AND status = :1' $bindings = [123, 'active']; $rows = DB::connection('clickhouse')->select($prepared, $bindings); ``` -------------------------------- ### Client select Method Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/INDEX.md Executes a SELECT query with optional parameters. ```php select(string $sql, array $params = []): Statement ``` -------------------------------- ### Get Statement Rows as Associative Arrays Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/types.md Retrieve query results as an array of associative arrays. Each row is represented as a key-value map. ```php public function rows(): array ``` -------------------------------- ### Create Connection with Client Factory Method Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Connection.md Factory method to create a new connection instance using a provided configuration array. Ensure the config array contains all necessary database connection details. ```php $config = [ 'database' => 'default', 'host' => 'localhost', 'port' => 8123, 'username' => 'default', 'password' => '', 'timeout_connect' => 2, 'timeout_query' => 2, 'https' => false, 'retries' => 0, ]; $connection = Connection::createWithClient($config); ``` -------------------------------- ### Get Average Value of a Column Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md The `avg` method calculates the average value of a specified column. The `average` method is an alias for `avg`. ```php $average = MyTable::avg('age'); ``` -------------------------------- ### getSettings() Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md Retrieves the current settings array configured via the `settings()` method. ```APIDOC ## getSettings() ### Description Retrieves the current settings array configured via the `settings()` method. ### Method `getSettings(): array` ### Parameters None ### Request Example ```php $settings = $builder->getSettings(); ``` ### Response #### Success Response (200) - **array** - Settings configured via `settings()`. #### Response Example None provided in source. ``` -------------------------------- ### Get Row Count Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md The `count` method retrieves the number of rows matching the query. It is also listed as a query execution method. ```php MyTable::count(); ``` -------------------------------- ### Switch to Next Available Node (Round-Robin) Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Cluster.md Manually switch the active connection to the next available node in a round-robin fashion. The method tests connectivity, skips unavailable nodes, and wraps around to the first node after the last one. It returns immediately if the cluster has only one node. ```php $cluster = $connection->getCluster(); echo $cluster->getActiveNode()->getConnectHost(); // clickhouse01 $cluster->slideNode(); echo $cluster->getActiveNode()->getConnectHost(); // clickhouse02 $cluster->slideNode(); echo $cluster->getActiveNode()->getConnectHost(); // clickhouse01 (wrapped) ``` -------------------------------- ### Get the event dispatcher instance Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Events.md Retrieve the current event dispatcher instance. This is useful to check if a dispatcher is configured before attempting to use it. ```php $dispatcher = MyTable::getEventDispatcher(); if ($dispatcher) { // Dispatcher is configured } ``` -------------------------------- ### Prepare Query Parameters Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Grammars.md A static method that converts internal parameter placeholders ('#@?') to numbered parameters (':0', ':1', etc.) in a SQL query string. This is used internally before queries are sent to the ClickHouse client. ```php public static function prepareParameters(string $sql): string { // ... implementation details ... // Replaces '#@?' with ':0', ':1', etc. } ``` ```php $sql = 'SELECT * FROM table WHERE id = #@? AND name = #@?'; $prepared = QueryGrammar::prepareParameters($sql); ``` -------------------------------- ### Configure Buffer Engine for Inserts Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/README.md Specify a different table for insert operations using `$tableForInserts` while continuing to select from the primary table. ```php where('age', '>', 25) ->getRows(); ``` ``` -------------------------------- ### Dynamic Attribute Access (Get) Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/BaseModel.md Access model attributes dynamically using magic __get method. This is equivalent to calling getAttribute('key'). ```php $model->name; // Returns $model->getAttribute('name') ``` -------------------------------- ### Client Common Methods Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/types.md The Client class provides low-level query execution, originating from the smi2/phpClickHouse library. ```APIDOC ## Client Common Methods ### Description The `Client` class provides low-level query execution. It is an instance of `ClickHouseDB\Client` and is sourced from the `smi2/phpClickHouse` library. ### Methods #### select() Execute a SELECT query. ```php public function select(string $sql, array $params = []): Statement ``` #### insert() Insert rows as indexed arrays. ```php public function insert(string $table, array $rows, array $columns): Statement ``` #### insertAssocBulk() Insert rows as associative arrays. ```php public function insertAssocBulk(string $table, array $rows): Statement ``` #### write() Execute a write statement (INSERT, ALTER, CREATE, etc.). ```php public function write(string $sql, array $params = []): Statement ``` #### database() Set the active database. ```php public function database(string $name): self ``` #### ping() Test connectivity to server. ```php public function ping(bool $throwException = false): bool ``` ### Usage ```php $client = DB::connection('clickhouse')->getClient(); $statement = $client->select('SELECT * FROM my_table'); ``` ``` -------------------------------- ### settings() Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md Configures query-level SETTINGS for a SELECT statement. ```APIDOC ## settings() ### Description Configures query-level SETTINGS for a SELECT statement. ### Method `settings(array $settings): self` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **$settings** (array) - Required - ClickHouse settings (e.g., `['max_threads' => 3]`). ### Request Example ```php MyTable::select(['*']) ->settings(['max_threads' => 3, 'read_overflow_mode' => 'throw']) ->getRows(); ``` ### Response #### Success Response (200) - **self** - For method chaining. #### Response Example None provided in source. ``` -------------------------------- ### Get Minimum Value of a Column Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md Use the `min` method to find the minimum value within a specified column across the matching rows. ```php $minAge = MyTable::min('age'); ``` -------------------------------- ### Project File Structure Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/MANIFEST.md Overview of the directory structure for the phpclickhouse-laravel project, indicating the purpose of each markdown file. ```bash output/ ├── README.md Main overview and quick start ├── INDEX.md Complete API index and symbol reference ├── MANIFEST.md This file ├── configuration.md Configuration options and environment setup ├── types.md Type definitions and interfaces ├── errors.md Exception reference and error handling └── api-reference/ ├── BaseModel.md Model class documentation ├── Builder.md Query builder documentation ├── Connection.md Connection driver documentation ├── Migration.md Schema migrations documentation ├── Cluster.md Cluster management documentation ├── Expressions.md Data type expressions documentation ├── Grammars.md SQL grammar classes documentation ├── Events.md Event dispatching documentation └── ServiceProvider.md Service provider documentation ``` -------------------------------- ### Get Table Name for Inserts Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/BaseModel.md Retrieve the table name specifically used for insert operations. This may differ from the default table name. ```php $model = new MyTable(); echo $model->getTableForInserts(); // my_table or my_table_buffer if set ``` -------------------------------- ### Execute SELECT and Get Statement Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md Executes a SELECT query and returns a Statement object. Useful for accessing detailed query results and metadata. ```php $statement = MyTable::select(['id', 'name']) ->where('status', 'active') ->get(); echo $statement->count(); // Number of rows ``` -------------------------------- ### Retrieve Query Settings Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md Use the `getSettings` method to retrieve the current settings array configured via the `settings()` method. This is useful for inspecting or logging current query configurations. ```php $settings = $builder->getSettings(); ``` -------------------------------- ### Get Cluster Instance Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Connection.md Retrieves the Cluster instance managing node connections. This can be used to interact with cluster-specific functionalities like switching nodes. ```php $connection = DB::connection('clickhouse'); $cluster = $connection->getCluster(); // Switch to next available node $cluster->slideNode(); ``` -------------------------------- ### Execute SELECT Query with Bindings Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/types.md Executes a SELECT query using the query builder, returning a Statement object. ```php public function get(array $bindings = []): Statement ``` -------------------------------- ### Configure ClickHouse Cluster Connection Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/README.md Set up a ClickHouse cluster connection in your database configuration. Reads and writes use the first available node. ```php 'clickhouse' => [ 'driver' => 'clickhouse', 'cluster' => [ [ 'host' => 'clickhouse01', 'port' => 8123, ], [ 'host' => 'clickhouse02', 'port' => 8123, ], ], 'database' => env('CLICKHOUSE_DATABASE','default'), 'username' => env('CLICKHOUSE_USERNAME','default'), 'password' => env('CLICKHOUSE_PASSWORD',''), 'timeout_connect' => env('CLICKHOUSE_TIMEOUT_CONNECT',2), 'timeout_query' => env('CLICKHOUSE_TIMEOUT_QUERY',2), 'https' => (bool)env('CLICKHOUSE_HTTPS', null), 'retries' => env('CLICKHOUSE_RETRIES', 0), 'settings' => [ // optional 'max_partitions_per_insert_block' => 300, ], 'fix_default_query_builder' => true, ], ``` -------------------------------- ### Get Table Name for Sources Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/BaseModel.md Retrieve the table name used for operations like OPTIMIZE, DELETE, or UPDATE. Defaults to the base table name. ```php $model = new MyTable(); echo $model->getTableSources(); // my_table ``` -------------------------------- ### Create Migration for Second ClickHouse Instance Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/README.md Define a migration for a ClickHouse table on a specific connection. Ensure the connection property is set. ```php count(); ``` -------------------------------- ### create() Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/BaseModel.md Saves a new model instance to the database with the provided attributes. This method fires 'creating' and 'created' events. ```APIDOC ## create() ### Description Save a new model instance to the database. ### Method `public static function create(array $attributes = [])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **$attributes** (array) - Optional - Attributes to insert. ### Returns `static|bool` — Saved instance or `false` if `creating` event returns false. ### Throws `Exception` — If model already exists (ClickHouse does not allow updates). ### Example ```php $model = MyTable::create(['name' => 'Jane', 'value' => 100]); // Fires 'creating' and 'created' events ``` ``` -------------------------------- ### Get Active ClickHouse Client Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Cluster.md Retrieve the currently active ClickHouseDB\Client instance from the cluster. This is useful for inspecting the connection details of the active node, such as its host. ```php $cluster = $connection->getCluster(); $client = $cluster->getActiveNode(); $host = $client->getConnectHost(); ``` -------------------------------- ### Connection::createWithClient Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Connection.md Factory method to create a new connection instance with a pre-configured ClickHouse client. It accepts an array of database configuration options. ```APIDOC ## static Connection::createWithClient(array $config) ### Description Factory method to create a connection with ClickHouse client. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **`$config`** (array) - Required - Database configuration array. See Configuration section below. ### Request Example ```php $config = [ 'database' => 'default', 'host' => 'localhost', 'port' => 8123, 'username' => 'default', 'password' => '', 'timeout_connect' => 2, 'timeout_query' => 2, 'https' => false, 'retries' => 0, ]; $connection = Connection::createWithClient($config); ``` ### Response #### Success Response (200) * **`Connection`** - New connection instance. #### Response Example ```json { "example": "Connection instance" } ``` ``` -------------------------------- ### Get Sum of Values in a Column Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md Use the `sum` method to calculate the total sum of values in a specified column. It returns 0 if no rows match the query. ```php $total = MyTable::sum('amount'); ``` -------------------------------- ### Execute SELECT and Get Rows Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md Executes a SELECT query and returns the results as an array of associative arrays (rows). Suitable for iterating through smaller result sets. ```php $rows = MyTable::select(['name', 'age']) ->where('age', '>', 25) ->getRows(); foreach ($rows as $row) { echo $row['name']; } ``` -------------------------------- ### Cluster Management Operations Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Connection.md Manage cluster connections by getting the cluster instance, accessing the active node, and sliding to the next available node for subsequent queries. ```php $connection = DB::connection('clickhouse'); $cluster = $connection->getCluster(); // Get current active node host $host = $cluster->getActiveNode()->getConnectHost(); // Switch to next available node $cluster->slideNode(); // Subsequent queries use the new node ``` -------------------------------- ### Basic Model Operations Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/README.md Perform create, query, bulk insert, update, and delete operations using the model. ```php // Create $model = MyTable::create(['name' => 'John', 'age' => 30]); // Query $rows = MyTable::select(['name', 'age']) ->where('age', '>', 25) ->getRows(); // Bulk insert MyTable::insertAssoc([ ['name' => 'Jane', 'age' => 25], ['name' => 'Bob', 'age' => 35], ]); // Update MyTable::where('id', 1)->update(['status' => 'active']); // Delete MyTable::where('status', 'inactive')->delete(); ``` -------------------------------- ### Execute Statement and Get Affected Rows Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Connection.md Use affectingStatement to execute a statement and retrieve the number of affected rows. For ClickHouse, this typically returns 1 on success. ```php public function affectingStatement($query, $bindings = []): int ``` ```php $affected = DB::connection('clickhouse')->affectingStatement( 'ALTER TABLE my_table DELETE WHERE id = ?', [1] ); ``` -------------------------------- ### Configure Query Settings Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Builder.md The `settings` method allows you to configure query-level SETTINGS for SELECT statements. It accepts an array of ClickHouse settings. This method is useful for fine-tuning query execution. ```php MyTable::select(['*']) ->settings(['max_threads' => 3, 'read_overflow_mode' => 'throw']) ->getRows(); ``` -------------------------------- ### File Organization Structure Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/INDEX.md Displays the directory structure of the src and config folders. ```text src/ ├── BaseModel.php (421 lines) ├── Builder.php (236 lines) ├── Connection.php (122 lines) ├── Migration.php (53 lines) ├── Cluster.php (95 lines) ├── Grammar.php (24 lines) ├── QueryGrammar.php (42 lines) ├── SchemaGrammar.php (151 lines) ├── SchemaBuilder.php (18 lines) ├── LaravelStatement.php (28 lines) ├── RawColumn.php (25 lines) ├── CurlerRollingWithRetries.php (44 lines) ├── WithClient.php (28 lines) ├── BuilderMethodsFromLaravel.php (253 lines) ├── ClickhouseServiceProvider.php (57 lines) ├── Concerns/ │ └── HasEvents.php (95 lines) ├── Exceptions/ │ └── QueryException.php (14 lines) └── Expressions/ ├── InsertArray.php (62 lines) └── Map.php (37 lines) config/ └── clickhouse.php (21 lines) ``` -------------------------------- ### Create and Configure ClickHouse Client (Internal) Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/api-reference/Cluster.md A protected factory method used internally to create and configure a ClickHouseDB\Client instance based on provided node configuration. It applies various settings like database name, timeouts, server settings, and retry handlers. ```php $config = [ 'host' => 'clickhouse01', 'port' => 8123, 'database' => 'default', 'username' => 'default', 'password' => '', 'timeout_query' => 2, 'timeout_connect' => 2, 'settings' => ['max_partitions_per_insert_block' => 300], 'retries' => 2, ]; $client = Cluster::createClient($config); ``` -------------------------------- ### Data Flow Diagram Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/README.md Illustrates the data flow from user code through the BaseModel, Builder, Grammar, and Connection to the ClickHouse Server. ```text User Code ↓ BaseModel::create() / select() / where() ↓ Builder (extends BaseBuilder from ClickhouseBuilder) ↓ Grammar (compiles to SQL) ↓ Connection (runs query) ↓ Cluster (manages nodes) ↓ Client (ClickHouseDB\Client) ↓ HTTP → ClickHouse Server ``` -------------------------------- ### QueryGrammar Methods Source: https://github.com/glushkovds/phpclickhouse-laravel/blob/master/_autodocs/INDEX.md Methods for compiling SQL queries and preparing parameters. ```APIDOC ## QueryGrammar Methods ### Description Methods for compiling SQL queries and preparing parameters. ### Methods - `parameter($value): string` - `static prepareParameters(string $sql): string` ```