sqlite-database-integration icon indicating copy to clipboard operation
sqlite-database-integration copied to clipboard

support ALTER TABLE AUTO_INCREMENT

Open batonac opened this issue 1 year ago • 2 comments

The query in this function (edit: example from a third-party plugin) produces an error (with the latest trunk):

public function reset_auto_increment_availability_table()
{
    global $wpdb;
    $tablename      = $wpdb->prefix.$this->availability_tablename;
    $row            = $wpdb->get_row( "SELECT Max(sno) as max_sno FROM $tablename" );
    
    $auto_increment = (int) $row->max_sno + 1;
    // error_log('auto_increment : '.print_r($auto_increment,1));
    $prepare_values = array( $auto_increment );
    $query 			= $wpdb->prepare( "ALTER TABLE $tablename AUTO_INCREMENT = %d", $prepare_values);
    $status         = $wpdb->query($query);
}

Here's the temporary workaround I used (thanks to ChatGPT):

public function reset_auto_increment_availability_table()
{
    global $wpdb;
    $tablename      = $wpdb->prefix.$this->availability_tablename;
    $row            = $wpdb->get_row( "SELECT Max(sno) as max_sno FROM $tablename" );

    $auto_increment = (int) $row->max_sno + 1;
    // error_log('auto_increment : '.print_r($auto_increment,1));
    $prepare_values = array( $auto_increment );
    
    // Check if the database is SQLite
    if ($wpdb instanceof WP_SQLite_DB) {
        $query = $wpdb->prepare( "UPDATE sqlite_sequence SET seq = %d WHERE name = %s", array($auto_increment, $tablename));
    } else {
        $query = $wpdb->prepare( "ALTER TABLE $tablename AUTO_INCREMENT = %d", $prepare_values);
    }

    $status = $wpdb->query($query);
}

batonac avatar May 05 '23 19:05 batonac