You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm running on this issue when I have a web-server that uses SQLProvider and there are multiple requests at the same time (from different users, or from async JavaScript). e.g.:
User A calls let e = query { for m in dbContext.MyTable do where (m.Id = "A") select (m) }
User B calls let e = query { for m in dbContext.MyTable do where (m.Id = "B") select (m) }
User A continues with e.SetColumn("mycol", 1) and dbContext.SubmitUpdates()
User B continues with e.SetColumn("mycol", 2) and dbContext.SubmitUpdates()
Crash Unchanged entity encountered in update list - this should not be possible!
The problem is basically the same as #173 but how should I do a good workaround?
These users are not touching the same rows in the database.
You could have multiple data contexts, there is no real disadvantage to this since the connections are closed and reopened with each action, which are pooled via normal ado mechanics - would that sort it ?
Ok I think this is a basic problem that gets solved if I wrap my queries to transactions so that both query and the SubmitUpdates are inside of a same transaction. By default, they are not; how could query know anything.
So basically if I have read-only-operations they are ok to execute as is, but if I have SubmitUpdates then I have to wrap the queries related to this to a transaction. Inside SubmitUpdates is made a new transaction with default options (which is enlist to existing transaction or make a new if none exists) which is good.
I made a little wrapper to do the transaction:
let dbReadOnlyContext =
if cstr = null then TypeProviderConnection.GetDataContext()
else TypeProviderConnection.GetDataContext cstr
let writeWithDbContextManualComplete() =
let isMono = Type.GetType ("Mono.Runtime") <> null
let context = TypeProviderConnection.GetDataContext cstr
let scope =
match isMono with
| true -> new Transactions.TransactionScope()
| false ->
// Note1: On Mono, 4.6.1 or newer is requred for compiling TransactionScopeAsyncFlowOption.
// Note2: We should here also set the transaction option isolation level.
new Transactions.TransactionScope(System.Transactions.TransactionScopeAsyncFlowOption.Enabled)
// new Transactions.TransactionScope(
// Transactions.TransactionScopeOption.Required,
// new Transactions.TransactionOptions(
// IsolationLevel = Transactions.IsolationLevel.RepeatableRead),
// System.Transactions.TransactionScopeAsyncFlowOption.Enabled) scope, context
// note that scope.Dispose() will complete the transaction if scope.Complete() is done
open System.Threading.Tasks
/// Write operations should be wrapped to transaction with this.
let writeWithDbContext<'T> (func:TypeProviderConnection.dataContext -> Task<'T>) =
task {
let transaction, context = writeWithDbContextManualComplete()
use scope = transaction
let! res = func context
if not isMono then
if not (isNull scope) then
try
scope.Complete()
scope.Dispose()
with
| :? ObjectDisposedException -> ()
return res
}
let writeWithDbContextAsync<'T> (func:TypeProviderConnection.dataContext -> Async<'T>) =
async {
let transaction, context = writeWithDbContextManualComplete()
use scope = transaction
let! res = func context
if not isMono then
if not(isNull scope) then
try
scope.Complete()
scope.Dispose()
with
| :? ObjectDisposedException -> ()
return res
}
And I use it like this, only add this one extra line of code to the beginning of an existing write-methods:
let doStuff () =
writeWithDbContext <| fun (dbContext:DataContext) ->
let e = query { for m in dbContext.MyTable do where (m.Id = "A") select (m) }
e.SetColumn("mycol", 1)
dbContext.SubmitUpdates()
Some more tales from production... I'm using currently one context only, the same for all the read operations. And then new contexts (and transactions as described above) for every operation containing also write-operations.
I'm using separate Azure SQL-database. The network connection to Azure database is not totally reliable. Sometimes the connection creation just throws network exception:
System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) ---> System.ComponentModel.Win32Exception (0x80004005): The network path was not found
So I had to create a retry like this (actually I'm using Logary for logging but anyways):
letinternalcreateDbReadOnlyContext()=let reccreateCon x =tryif cstr =nullthen TypeProviderConnection.GetDataContext()else TypeProviderConnection.GetDataContext cstr
with|:? System.Data.SqlClient.SqlException as ex when x <3->
System.Console.WriteLine("Error connecting SQL, retrying... "+ ex.Message)
System.Threading.Thread.Sleep 50
createCon (x+1)|:? System.Data.SqlClient.SqlException as ex when x <5->
System.Console.WriteLine("Error connecting SQL, retrying... "+ ex.Message)
System.Threading.Thread.Sleep 1500
createCon (x+1)
createCon 0
After that, the connection seems to be more error prone. I'm running my program as a auto-starting Windows service on Azure machine. Then the next problem I faced was that Windows servers on Azure does maintenance boots every now and then. And now, if the database connection is not working when the service starts (which is probable because the database can also be running update at the same time), the connection will be on some kind of failed state: the read-connection won't start working even when the SQL-database goes back online.
So for that, I changed the read-only connection to have a backing-static-container-variable and replace the connection on failures:
typeDataContext= TypeProviderConnection.dataContext
let mutableinternalcontextHolder= Unchecked.defaultof<Lazy<DataContext>>letdbReadOnlyContext()=if contextHolder =null||not(contextHolder.IsValueCreated)thentryletitm=lazy(createDbReadOnlyContext())
contextHolder <- itm
with| e -> System.Console.WriteLine("SQL connection failed: "+ e.Message)
contextHolder.Force()
The sad thing is I have to call my dbReadOnlyContext as a function, even if it's usually not using the function but just fetching a static variable:
let!items=
query {for item in dbReadOnlyContext().Dbo.MyTable do//...
but now it seems to be durable enough to start the process without SQL-database connection and then restore the connection after the failure time is over.
We could include this kind of error tolerance to SQLProvider itself (as there are sometimes some invisible error-management on database-driver-level also), or some extension-module. Now I have the source codes in my project, but they are not at all project-specific codes. What do you think?
We could include this kind of error tolerance to SQLProvider itself (as there are sometimes some invisible error-management on database-driver-level also), or some extension-module. Now I have the source codes in my project, but they are not at all project-specific codes. What do you think?
Is it already included nowadays or should I introduce such a mechanism in my specific project?
Last friday a user of mine received the Error: "Unchanged entity encountered in update list - this should not be possible!". Today the situation seems fine anyway, but I'm a bit worried it might happen again...
In my DB module I have a single, initial let context = Sql.GetDataContext // ... conn string from config
Up till now I haven't had such errors, do you think I can consider it an exceptional case and ignore it for the moment or should I think about some helpers like your writeWithDbContext or dbReadOnlyContext or anything special for updates?
Actually I see some commits and merge linked above so I guess this sort of "error tolerance" is already part of SQLProvider itself, isn't it? Thanks
Edit 1
I see that unfortunately the error is still present in my production env so I actually need to prepare a fix for it in my project. I will share it if anyone is interested as soon as it is ready.
Edit 2
In my project I've replaced context.SubmitUpdates() with a safer helper:
let safeSaveContext msg =
try
context.SubmitUpdates()
Result.Ok msg
with
| exc ->
context.ClearUpdates() |> ignore
Result.Error exc.Message
@Thorium Have you ever used the None branch of you match in production? It would need a x.ClearUpdates() there: that's why it is a bad idea having to explicitly call it.
I haven't, it's only for canopy web-tests, where I don't bother the long run. :-)
I see your point, however I kind of like SQLProvider to not depend on any logging framework.
Activity
pezipink commentedon Apr 7, 2016
I am not 100% sure why this is happening - if it is a sync problem can you not just lock or sync via a mailbox?
I will look at this when I get back around to doing some work on this type provider.
Thorium commentedon Apr 8, 2016
Are you suggesting that I would have only one web-user accessing the database at time?
I would rather like to see some kind of "if this error, refresh the context and retry"-operation...
pezipink commentedon Apr 9, 2016
You could have multiple data contexts, there is no real disadvantage to this since the connections are closed and reopened with each action, which are pooled via normal ado mechanics - would that sort it ?
Thorium commentedon May 2, 2016
Ok I think this is a basic problem that gets solved if I wrap my queries to transactions so that both
queryand theSubmitUpdatesare inside of a same transaction. By default, they are not; how could query know anything.So basically if I have read-only-operations they are ok to execute as is, but if I have SubmitUpdates then I have to wrap the queries related to this to a transaction. Inside SubmitUpdates is made a new transaction with default options (which is enlist to existing transaction or make a new if none exists) which is good.
I made a little wrapper to do the transaction:
And I use it like this, only add this one extra line of code to the beginning of an existing write-methods:
I'm happy for now, this issue should be ok.
Thorium commentedon May 9, 2016
Note, in the existing code, this is not thread-safe:
let pendingChanges = HashSet<SqlEntity>()Thorium commentedon May 29, 2016
Much better now!
Thorium commentedon Dec 25, 2016
Some more tales from production... I'm using currently one context only, the same for all the read operations. And then new contexts (and transactions as described above) for every operation containing also write-operations.
I'm using separate Azure SQL-database. The network connection to Azure database is not totally reliable. Sometimes the connection creation just throws network exception:
So I had to create a retry like this (actually I'm using Logary for logging but anyways):
After that, the connection seems to be more error prone. I'm running my program as a auto-starting Windows service on Azure machine. Then the next problem I faced was that Windows servers on Azure does maintenance boots every now and then. And now, if the database connection is not working when the service starts (which is probable because the database can also be running update at the same time), the connection will be on some kind of failed state: the read-connection won't start working even when the SQL-database goes back online.
So for that, I changed the read-only connection to have a backing-static-container-variable and replace the connection on failures:
The sad thing is I have to call my dbReadOnlyContext as a function, even if it's usually not using the function but just fetching a static variable:
but now it seems to be durable enough to start the process without SQL-database connection and then restore the connection after the failure time is over.
We could include this kind of error tolerance to SQLProvider itself (as there are sometimes some invisible error-management on database-driver-level also), or some extension-module. Now I have the source codes in my project, but they are not at all project-specific codes. What do you think?
giuliohome commentedon Feb 24, 2020
Is it already included nowadays or should I introduce such a mechanism in my specific project?
Last friday a user of mine received the Error: "
Unchanged entity encountered in update list - this should not be possible!". Today the situation seems fine anyway, but I'm a bit worried it might happen again...In my DB module I have a single, initial
let context = Sql.GetDataContext // ... conn string from configUp till now I haven't had such errors, do you think I can consider it an exceptional case and ignore it for the moment or should I think about some helpers like your
writeWithDbContextordbReadOnlyContextor anything special for updates?Actually I see some commits and merge linked above so I guess this sort of "error tolerance" is already part of SQLProvider itself, isn't it? Thanks
Edit 1
I see that unfortunately the error is still present in my production env so I actually need to prepare a fix for it in my project. I will share it if anyone is interested as soon as it is ready.
Edit 2
In my project I've replaced
context.SubmitUpdates()with a safer helper:Thorium commentedon Feb 25, 2020
I have been using async version, and this has been in my production for a long time already, feel free to copy&modify:
Thorium commentedon Feb 25, 2020
Also, this is related.
giuliohome commentedon Feb 25, 2020
@Thorium Have you ever used the
Nonebranch of youmatchin production? It would need ax.ClearUpdates()there: that's why it is a bad idea having to explicitly call it.Thorium commentedon Feb 25, 2020
I haven't, it's only for canopy web-tests, where I don't bother the long run. :-)
I see your point, however I kind of like SQLProvider to not depend on any logging framework.