PHP and SQLite3 opening file when they don’t exist!

A few days ago I changed a piece of working PHP code to handle SQLite3 databases in a better and more controlled way:

try {
    $database  = new SQLite3( $database_name, SQLITE3_OPEN_READWRITE );

    if ( ! $database ){
        $logger->err( "Cannot open database $database_name!" );
        return;
    }

    // ...

    $database->close();
} catch( Exception $e ) {
    $logger->warning( $e->getMessage() );
}


So far so good, except that whem the file $database_name does not exist the file is not opened and an exception is raised.
By default, SQLite3 constructor opens the file in read-write and create mode and the documentation tells clearly that an exception is thrown on failure, without specifying what a “failure” is.
It turned out that if the SQLite3 file does not exist and is opened to be written to, the exception is thrown and the program was crashing. The fix was simple:

try {
    $database  = new SQLite3( $database_name, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE );
    ...



Why using the default flags? Because depending on the version of the SQLite3 library version a warning is emitted if no flags are specified!

The problem is, according to me, that it is not specified in the documentation that opening in READWRITE mode does not imply CREATE, that can be useful (not to me), but opens a problem.

The article PHP and SQLite3 opening file when they don't exist! has been posted by Luca Ferrari on May 25, 2022