Disadvantages of this "Lazy" Database Closing (SQLite)
#1

Hey,

I'm looking for a way to automatically clean up my database resources so I do not have to worry about it. One way I've thought of doing it is to have something like this:

pawn Код:
static DB:databaseHandle = DB:0;

stock DB:Database_GetHandle() {
    if (databaseHandle == DB:0) {
        databaseHandle = db_open("my.db");

        // Set a timer which will operate at the next opportunity, this will
        // be sometime after a callback (since Pawn is single threaded)
        SetTimer("Database_Close", 1, false);
    }

    return databaseHandle ;
}

public Database_Close() {
    if (databaseHandle != DB:0) {
        // Close the database ..
        db_close(databaseHandle);
       
        // Invalidate the database handle.
        databaseHandle = DB:0;
    }
}
This code would be used in a context like so:

pawn Код:
public OnPlayerConnect(playerid) {
    new DBResult: dbResult = db_query(Database_GetHandle(), "SELECT ..");
    // Additional code to handle the result
    db_free_result(dbResult);
    // Any additional code, maybe additional queries. The additional queries will
    // use the same method which points to the same handle ..
    // No need to explicitly close the database.
}
Now if my understanding of Pawn using a single thread is correct (see code comments) then I shouldn't run into problems. Does anybody know of any problems this may cause that are not immediately obvious? It's important this database handle is closed because outside applications may be writing to the database.

The main problem I can see is that the open-close time frame has probably increased to >=1ms (depending on how accurate Pawn timers are) rather than <1ms for faster queries. If this time frame becomes problematic then I suppose this can be solved by the outside application having a query buffer.

Does anybody know any other problems that I have not forseen?

Thanks for reading.
Reply
#2

Thanks for the input.

I'm pretty sure databases do not take up the handle 0 ever. I always check against 0 and print errors under the assumption that 0 was not valid. I've never seen the error, which tells me the assumption made was correct (invalid database is not defined in the includes).

I thought that when SA:MP opened a database it was automatically locked for write access. I immediately assumed this from an error another application (phpLiteAdmin) was having when writing data to the database-- I guess I may have to look into if it's the phpLiteAdmin application just bugging out.

If automatic write lock is not in place then I suppose I don't really need to close the database handle. Are there any major disadvantages to not closing a database handle in a SA:MP script?
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)