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

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

Open
hahnn opened this issue Mar 10, 2024 · 1 comment
Open

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

hahnn opened this issue Mar 10, 2024 · 1 comment

Comments

@hahnn
Copy link

hahnn commented Mar 10, 2024

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
Copy link
Collaborator

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

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

No branches or pull requests

2 participants