-
Notifications
You must be signed in to change notification settings - Fork 18
Caller identity
It is often desirable to pass some notion of client-side identity along with each query sent to the database, so that some useful database-side logic could capture this identity (in addition to executing the query itself).
One example is database-side logging/auditing of all queries, and linking each query (and/or modifications made by it) to a specific caller identity (ex. "User Id") which triggered that query. Such caller identity would become part of the context of that query.
TinyORM leverages CONTEXT_INFO feature of SQL Server to automatically send 16 bytes of client-side caller identity (ex. a Guid) with each query.
On the client side you can use the .CallerIdentityDelegate property of DbContext instance to set a custom caller identity delegate.
On the database side a query (or a trigger) can read the caller identity from first 16 bytes of CONTEXT_INFO():
SELECT CAST(CONTEXT_INFO() AS UNIQUEIDENTIFIER);Full example:
var dbContext = DbContext.Create("connection string");
dbContext.CallerIdentityDelegate = () =>
{
// replace with your context-specific user id retrieval logic
Guid user_id = new Guid("12345678-ABCD-ABCD-ABCD-0123456789AB");
return new CallerIdentity(user_id);
});
{
dbContext.QueryAsync("SELECT CAST(CONTEXT_INFO() AS UNIQUEIDENTIFIER);").Dump();
// [ key: "UserIdentity", value: 12345678-abcd-abcd-abcd-0123456789ab ]
}If context identity is not explicitly set on a DbContext instance, Guid.Empty is used by default.
Copyright (c) 2016-2022 Stan Drapkin