PostgreSQL-For-Wordpress / postgresql-for-wordpress

A maintained fork of https://wordpress.org/plugins/postgresql-for-wordpress/
GNU General Public License v2.0
228 stars 71 forks source link

CREATE TABLE not converted to CREATE TABLE IF NOT EXISTS #110

Open hahnn opened 7 months ago

hahnn commented 7 months ago

I found one case of a table creation which cannot be converted as CREATE TABLE IF NOT EXISTS as you can see below:

---------------------
[1710082543.2213] Error running :
CREATE TABLE `wp_e_events` (
                        id bigint(20) unsigned auto_increment primary key,
                        event_data text null,
                        created_at datetime not null
                ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;
---- converted to ----
CREATE TABLE wp_e_events (
                        id bigserial primary key,
                        event_data text null,
                        created_at timestamp not null
                );
----> ERROR:  relation « wp_e_events » is already existing

However, in source code v3.4, the code section below is there to handle this kind of conversion, no?

    public function rewrite(): string
    {
        $sql = $this->original();

        $tableSQL = str_replace('CREATE TABLE IF NOT EXISTS ', 'CREATE TABLE ', $sql);
        $pattern = '/CREATE TABLE [`]?(\w+)[`]?/';
        preg_match($pattern, $tableSQL, $matches);
        $table = $matches[1];

        // change all creates into create if not exists
        $pattern = "/CREATE TABLE (IF NOT EXISTS )?(\w+)\s*\(/i";
        $replacement = 'CREATE TABLE IF NOT EXISTS $2 (';
        $sql = preg_replace($pattern, $replacement, $sql);

Maybe this issue could be solved with the code below?

    public function rewrite(): string
    {
        $sql = $this->original();

        $tableSQL = str_replace('CREATE TABLE IF NOT EXISTS ', 'CREATE TABLE ', $sql);
        $pattern = '/CREATE TABLE [`]?(\w+)[`]?/';
        preg_match($pattern, $tableSQL, $matches);
        $table = $matches[1];

        // change all creates into create if not exists
        $pattern = "/CREATE TABLE (IF NOT EXISTS )?[`]?(\w+)[`]?\s*\(/i";
        $replacement = 'CREATE TABLE IF NOT EXISTS $2 (';
        $sql = preg_replace($pattern, $replacement, $sql);
mattbucci commented 7 months ago

Thanks for submitting all this + testing the new build. I won't be able to work on this, this week, but these test cases are really helpful