Skip to content
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

Add a code example on how to create corresponding tables for models in database #18

Closed
mrmoric opened this issue Mar 4, 2024 · 9 comments
Assignees
Labels
enhancement New feature or request

Comments

@mrmoric
Copy link

mrmoric commented Mar 4, 2024

Normally we use the following code to create tables in WordPress:

 add_action('init', [$this, 'migrate']);


function migrate() {
        global $wpdb;

        $PluginSettings = $this->ConfigService->getPluginSettings();
        $charsetCollate = $wpdb->get_charset_collate();

        $sqlConversationTable = <<<EOD
            CREATE TABLE %s (
                  id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                  accountId BIGINT(20) UNSIGNED NOT NULL,
                  userId BIGINT(20) UNSIGNED NULL,
                  chatbotId BIGINT(20) UNSIGNED NOT NULL,
                  ipAddress VARCHAR(32) NULL,
                  created DATETIME NOT NULL,
                  updated DATETIME NOT NULL,
                  PRIMARY KEY (id)
                ) %s;
        EOD;

        $sqlConversationTable = sprintf(
            $sqlConversationTable, $this->ConfigService->getChatbotConversationTable(), $charsetCollate
        );

        $sqlConversationMessageTable = <<<EOD
            CREATE TABLE %s (
                  id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                  conversationId BIGINT(20) UNSIGNED NOT NULL,
                  author VARCHAR(32) NULL,
                  message longtext NULL,
                  created DATETIME NOT NULL,
                  updated DATETIME NOT NULL,
                  PRIMARY KEY (id)
                ) %s;
        EOD;

        $sqlConversationMessageTable = sprintf(
            $sqlConversationMessageTable, $this->ConfigService->getChatbotConversationMessageTable(), $charsetCollate
        );

        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        dbDelta([
            $sqlConversationTable,
            $sqlConversationMessageTable
        ]);

}

But how it should be done using your package? I guess we still need to use 'dbDelta' piece, but code for table creation should be done in a different way. Perhaps we have to use QueryBuilder or somehow get table schema from Models?

If we don't need to use WordPress approach but use migrations instead. Then anyway how to run these migrations only once, so it doesn't try to create tables on each page init

@mrmoric mrmoric added the enhancement New feature or request label Mar 4, 2024
@axi
Copy link

axi commented Mar 4, 2024

I'm looking for the same answers ! Funny time synchronisation :-)
I'm new to Eloquent but it seems that the "right way" would be to use Illuminate\Support\Facades\Schema see here

if (Schema::hasTable('payouts')) {
    Schema::create('payouts', static function (Blueprint $table) {
        $table->increments('id');
        $table->decimal(Payout::AMOUNT, 8, 2);
    });
}

Trying that led me to an "A facade root has not been set." error for now

@axi
Copy link

axi commented Mar 4, 2024

So I guess the question could be: how can we configure Schema to work/access our wordpress db

@mrmoric
Copy link
Author

mrmoric commented Mar 4, 2024

This package adds the following dependencies to your composer.json

  "require": {
    "php": ">=8.1",
    "robmorgan/phinx": "^0.12.5",
    "illuminate/database": "^10.0"
  },

I think If you want to use

Illuminate\Support\Facades\Schema

you have to install one more package Support package

but in my project I want to use minimum dependencies. Even this wp-orm is quite large but its a cost of using ORM with Wordpress

@axi
Copy link

axi commented Mar 4, 2024

illuminate/support is a required dependency of illuminate/database, already installed then

@axi
Copy link

axi commented Mar 4, 2024

Lol, chatGPT helped

@mrmoric
Copy link
Author

mrmoric commented Mar 4, 2024

Need to add getDefaultSchemaGrammar method to Dbout\WpOrm\Orm\Database class.

It's strange but this method is not added to the ConnectionInterface but they add it for example in Illuminate\Database\MySqlConnection

If such method will be added then we can set the connection in Facade Illuminate\Support\Facades\Schema:

    public static function connection($name)
    {
        return static::$app['db']->connection($name)->getSchemaBuilder();
    }

And then we will be able to use Scheme to generate sql quires for tables

@dimitriBouteille
Copy link
Owner

Bonjour @mrmoric et @axi

As indicated by @mrmoric , the package contains a dependency to robmorgan/phinx that allows you to simply create database migrations.

This tool works very simply because you just need to create a config-phinx.php configuration file at the root of your project and then create the migrations. An example of this configuration file can be found here: https://github.com/dimitriBouteille/wp-orm/blob/master/doc/migration.md#migration

If you use a tool other than Bedrock, I invite you to propose an MR to explain how to use the tool on another Framework than Bedrock so that other people can enjoy it:)

Here is an example of a migration that adds a column:

declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

final class V20210812221926 extends AbstractMigration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function change(): void
    {
        $table = $this->table(\MyModel::table());
        if ($table->exists()) {
            $table
                ->addColumn(\MyModel::MY_PROPERTY, 'string', ['null' => true])
                ->update();
        }
    }
}

You can look this documentation for more information: https://book.cakephp.org/phinx/0/en/migrations.html#


@axi The dependency to the robmorgan/phinx package is temporary since the objective is to remove this dependency in order to use \Illuminate\Support\Facades\Schema.

This migration will take some time, I plan to work on this topic in April or May.


I remain available if you need help using Phinx or if you have ideas to improve this package :)

@axi
Copy link

axi commented Mar 4, 2024

@dimitriBouteille thanks for that answer. Yes I thing the goal of removing the robmorgan/phinx is a good idea. I won't use it because I already use doctrine-migration and don't want to have 2 "migrators". In the meantime, shouldn't this library be put in "require-dev" or "suggest" ? With a BC because other project might haven't explicitely required it.

@dimitriBouteille
Copy link
Owner

I close this issue, I opened the following issues :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants