I just figured this out this week for ActiveRecord in Web Applications so forgive the web app specific terminology.
In this first function I get the db from the Namespace. Desktop should probably do the same as web (haven’t gotten there yet) but in web looks for Session object, if not, then it looks at the current threadID and will go through the gyrations of figuring out which connection to use.
[code]Protected Function db() As SQLiteDatabase
#if TargetDesktop then
return app.db
#elseif TargetWeb then
if session.Available then
//First, look to see if session is available.
return session.db
else
//Second look at the current thread
if app.CurrentThread = nil then
//Main thread if current thread is nil
return app.db
else
//In a thread. Will reuse existing connection if it exists
return AddHandleSpecialURLConnection
end
end
#Endif
End Function
[/code]
[code]Protected Function AddHandleSpecialURLConnection() As SQLiteDatabase
//Get the Current Thread ID
dim iThreadID as integer = app.CurrentThread.ThreadID
//Now create a db object
dim dbHandleSpecialURL as SQLiteDatabase
dim bConnectionFound as boolean
for each oConnection as clsDBConnection in aroConnectionPool
//Just in case thread id’s are reused quicker than we expect check to make sure the thread
//it was created in is still valid.
if oConnection.iThreadID = iThreadID and oConnection.oThreadWeakRef.value <> nil then
dbHandleSpecialURL = oConnection.DB
bConnectionFound = true
exit
end
next
if bConnectionFound = false then
//Not in the existing pool. Create a new one.
dbHandleSpecialURL = Data.OpenDB
dim oConnection as new clsDBConnection
oConnection.iThreadID = iThreadID
oConnection.oThreadWeakRef = new WeakRef(app.CurrentThread)
oConnection.DB = dbHandleSpecialURL
aroConnectionPool.Append oConnection
end
//---------Remove old Connections---------------
for i as integer = aroConnectionPool.Ubound downto 0
dim oConnection as clsDBConnection = aroConnectionPool(i)
if oConnection.oThreadWeakRef.Value = nil then
//Thread is dead. Kill the conneciton object
aroConnectionPool.Remove i
end
next
return dbHandleSpecialURL
End Function
[/code]
clsDBConnection has 3 properties:
db as SQLiteDatabase
iThreadID as integer
oThreadWeakRef as WeakRef
There are probably more efficient ways of doing this and it’s not been extensively tested. If you find something let me know!