Skip to content

Improve PostgreSQL support by using connection config from config/database.php #320

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: v1.x
Choose a base branch
from

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

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