Skip to content

Conversation

@Benjaminhu
Copy link

In Laravel, database connections are defined in config/database.php under the connections key.

IMPORTANT
It would be better to rely on the configuration defined here and use those settings directly. Each connection also defines the database to use, and in the case of PostgreSQL, there are additional schema-specific settings available, such as schema and search_path (more info: laravel/ideas#918).

Because of this, the following query is unnecessary: SELECT datname FROM pg_database

Example:

'connections' => [
    'pgsql' => [
        'database' => env('DB_DATABASE', 'forge'),

        'schema' => 'public',

        /**
         * Undocumented feature, more info: https://github.com/laravel/ideas/issues/918
         */
        'search_path' => [
            /**
             * VERY IMPORTANT THIS POSITION - DO NOT EDIT
             * @see \Illuminate\Database\Schema\PostgresBuilder::parseSchemaAndTable() - $schema = $this->getSchemas()[0];
             * First item: must contain the `migrations` table!
             */
            'public',

            'other_schema1',
            'other_schema2',
        ],
    ],

    'log_connection' => [
        // ...
    ],
],

In the current implementation, what the code calls "schemas" are essentially databases, see: #318

Since Laravel supports defining multiple connections (e.g., log_connection), hardcoding the connection name can result in different behavior than what is passed via the CLI.
This is why I use $connectionName to pass the correct one dynamically:

Config::get("database.connections.pgsql.schema");

php artisan code:models --connection=another-connection

Because multiple entries can be defined under search_path, I renamed schema_database to schemas and changed its type to an array.

I hope these changes don’t cause issues for other PostgreSQL users.

With our new database configuration and CLI command, we can successfully generate models from both schemas:

'another_connection' => [
    'driver' => 'pgsql',
    'database' => env('DB_ANOTHER_CONNECTION_DATABASE'),
    'schema' => 'public',
    'search_path' => [
        'public',
        'logging',
    ],
],

Command:

php artisan code:models --connection=another_connection

@Benjaminhu
Copy link
Author

Updates:

  1. add orchestra/testbench for laravel package testing
  2. fix tests namespaces, change bootstrap file
  3. BlueprintTests expanded
  4. add new Postgres\SchemaTest
  5. fix schemanames and $table definition: database.table -> schema.table

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant