internal void OnExecutedSelect(EntitySession session, EntityCommand command) { if (ExecutedSelect != null) { ExecutedSelect(session, new EntityCommandEventArgs(session, command)); } }
// Creates new connection or gets previously used from the session public DataConnection GetConnection(EntitySession session, DbConnectionLifetime connLifetime = DbConnectionLifetime.Operation, bool admin = false) { if (admin) { return(new DataConnection(session, this.Settings, connLifetime, true)); } var conn = session.CurrentConnection; if (conn != null) { if (conn.Lifetime < connLifetime) { conn.Lifetime = connLifetime; } return(conn); } // if we have KeepOpen mode (recommended in Web app), then make Lifetime explicit - // i.e. until explicitly called to close; web call context handler will do it after completing // processing requests if (session.Context.DbConnectionMode == DbConnectionReuseMode.KeepOpen) { connLifetime = DbConnectionLifetime.Explicit; } conn = new DataConnection(session, this.Settings, connLifetime, admin: admin); session.CurrentConnection = conn; //it will register it in disposables return(conn); }
public List <BatchDbCommand> BatchCommands; //batch mode only public UpdateSet(DataConnection connection, DateTime updateTime, IList <EntityRecord> records) { Connection = connection; Session = connection.Session; UpdateTime = updateTime; Id = Session.NextTransactionId; //Start explicit transaction only if we have more than one command to execute. UseTransaction = (records.Count + Session.ScheduledCommands.Count) > 1; AllRecords.AddRange(records); //check if we need sequencing var stt = Connection.Database.Settings; var useRefIntegrity = stt.ModelConfig.Options.IsSet(DbOptions.UseRefIntegrity); var canDeferIntegrCheck = stt.Driver.Supports(Driver.DbFeatures.DeferredConstraintCheck); var needSequencing = useRefIntegrity && !canDeferIntegrCheck; if (needSequencing) { SequenceRecords(); //fills entity info set } else { // fill entity Info set EntityInfos.UnionWith(records.Select(r => r.EntityInfo)); } UsesOutParams = AllRecords.Any(r => UsesOutParam(r)); }
internal void OnNewSession(EntitySession session) { if (NewSession != null) { NewSession(session, new EntitySessionEventArgs(session)); } }
internal void OnExecutedNonQuery(EntitySession session, LinqCommand command) { if (ExecutedNonQuery != null) { ExecutedNonQuery(session, new LinqCommandEventArgs(session, command)); } }
private object ExecuteLinqNonQuery(LinqCommand linqCommand, EntitySession session, DataConnection connection) { var translCmd = GetTranslateLinqCommand(linqCommand); var dbCommand = CreateLinqDbCommand(connection, linqCommand, translCmd); var result = ExecuteDbCommand(dbCommand, connection, DbExecutionType.NonQuery); return result; }
internal void OnSaveChangesAborted(EntitySession session) { if (SaveChangesAborted != null) { SaveChangesAborted(session, new EntitySessionEventArgs(session)); } }
public EntityRecord ReadRecord(IDataRecord dataRecord, EntitySession session) { // Some outer join queries may produce entities that are null; so we first try to read Primary key values - if they're all null, we return null. if (_primaryKeyColumns.Count > 0 && PrimaryKeyIsNull(dataRecord)) { return(null); } var entRec = new EntityRecord(_tableInfo.Entity, EntityStatus.Loading); bool isView = _tableInfo.Entity.Kind == EntityKind.View; object dbValue = null; OutColumnMapping colMap = null; //for-i loop is more efficient than foreach for (int i = 0; i < _columns.Count; i++) { try { colMap = _columns[i]; var dbCol = colMap.DbColumn; var isNull = dataRecord.IsDBNull(colMap.ReaderColumnIndex); if (isNull) { // Views might have NULLs unexpectedly in columns like Count() or Sum() - LINQ expr has non-nullable type, but in fact // the view column can return NULL if (isView && !dbCol.Flags.IsSet(DbColumnFlags.Nullable)) { dbValue = dbCol.Member.DefaultValue; } else { dbValue = DBNull.Value; } } else { // not NULL dbValue = dbCol.TypeInfo.ColumnReader(dataRecord, colMap.ReaderColumnIndex); var conv = dbCol.Converter.ColumnToProperty; if (dbValue != null && conv != null) { dbValue = conv(dbValue); } // quick fix: views sometimes have out columns changed from expected if (isView && !ConvertHelper.UnderlyingTypesMatch(dbCol.Member.DataType, dbValue.GetType())) { dbValue = ConvertHelper.ChangeType(dbValue, dbCol.Member.DataType); } } var member = dbCol.Member; entRec.ValuesOriginal[member.ValueIndex] = dbValue; } catch (Exception ex) { ex.AddValue("DataRecord", dataRecord); ex.AddValue("ColumnName", colMap.DbColumn.ColumnName); ex.AddValue("DbValue", dbValue); throw; } } var sessionRec = session.Attach(entRec); //might return different, previously loaded record return(sessionRec); }
public EntityRecord ReadRecord(IDataRecord dataRecord, EntitySession session) { // Some outer join queries may produce entities that are null; so we first try to read Primary key values - if they're all null, we return null. if (_primaryKeyColumns.Count > 0 && PrimaryKeyIsNull(dataRecord)) return null; var entRec = new EntityRecord(_tableInfo.Entity, EntityStatus.Loading); object dbValue = null; OutColumnMapping colMap = null; //for-i loop is more efficient than foreach for (int i = 0; i < _columns.Count; i++) { try { colMap = _columns[i]; dbValue = dataRecord[colMap.ReaderColumnIndex]; //System.Diagnostics.Debug.WriteLine(colMap.DbColumn.ColumnName + " " + dbValue + "(" + dbValue.GetType() + ")"); var conv = colMap.DbColumn.TypeInfo.ColumnToPropertyConverter; if(dbValue != null && conv != null) dbValue = conv(dbValue); entRec.ValuesOriginal[colMap.DbColumn.Member.ValueIndex] = dbValue; } catch (Exception ex) { ex.AddValue("DataRecord", dataRecord); ex.AddValue("ColumnName", colMap.DbColumn.ColumnName); ex.AddValue("DbValue", dbValue); throw; } } var sessionRec = session.Attach(entRec); //might return different, previously loaded record return sessionRec; }
internal void OnError(EntitySession session, Exception exception) { if (Error != null) { Error(session, new AppErrorEventArgs(session, exception)); } }
// Used for efficient reading entities in linq queries public object ReadEntity(IDataRecord dataRecord, EntitySession session) { var entRec = ReadRecord(dataRecord, session); if (entRec == null) return null; return entRec.EntityInstance; }
public void SaveChanges(EntitySession session) { if (session.HasChanges()) { var conn = GetConnection(session); var updateSet = new DbUpdateSet(session, this.DbModel, conn); var batchMode = ShouldUseBatchMode(updateSet); if (batchMode) { SaveChangesInBatchMode(updateSet); } else { SaveChangesNoBatch(updateSet); } } //commit if we have session connection with transaction and CommitOnSave var sConn = session.CurrentConnection; if (sConn != null) { if (sConn.DbTransaction != null && sConn.Flags.IsSet(DbConnectionFlags.CommitOnSave)) { sConn.Commit(); } if (sConn.Lifetime != DbConnectionLifetime.Explicit) { ReleaseConnection(sConn); } } session.ScheduledCommandsAtStart = null; session.ScheduledCommandsAtEnd = null; }
public void RunTest(bool batchMode) { _app = new IdentityRefTestEntityApp(); Startup.ActivateApp(_app); //if(Startup.ServerType == Data.Driver.DbServerType.SQLite) DeleteAllData(); // We create session this way to set the batch mode flag var ctx = new OperationContext(_app); IEntitySession session = new EntitySession(ctx, options: batchMode ? EntitySessionOptions.None : EntitySessionOptions.DisableBatchMode); var john = session.NewUser("john"); var post1 = john.NewPost("john post 1", 1); var post2 = john.NewPost("john post 2", 2); var post3 = john.NewPost("john post 3", 3); var ben = session.NewUser("ben"); var post1b = ben.NewPost("ben post 1", 1); var post2b = ben.NewPost("ben post 2", 2); var post3b = ben.NewPost("ben post 3", 3); session.SaveChanges(); //Check that Identity values immediately changed to actual positive values loaded from database Assert.IsTrue(post1.OrderId > 0, "Invalid OrderID - expected positive value."); Assert.IsTrue(post2.OrderId > 0, "Invalid OrderID - expected positive value."); Assert.IsTrue(post3.OrderId > 0, "Invalid OrderID - expected positive value."); //Start new session, load all and check that IDs and relationships are correct session = _app.OpenSession(); var posts = session.EntitySet <IUserPost>().ToList(); foreach (var post in posts) { Assert.IsTrue(post.OrderId > 0); } }//method
public void SaveChanges(EntitySession session) { if (session.HasChanges()) { var records = session.RecordsChanged.Where(rec => ShouldUpdate(rec)).ToList(); var conn = GetConnection(session); var updateSet = new UpdateSet(conn, _timeService.UtcNow, records); var batchMode = ShouldUseBatchMode(updateSet); if (batchMode) { SaveChangesInBatchMode(updateSet); } else { SaveChangesNoBatch(session, updateSet); } } //commit if we have session connection with transaction and CommitOnSave var sConn = session.CurrentConnection; if (sConn != null) { if (sConn.DbTransaction != null && sConn.Flags.IsSet(ConnectionFlags.CommitOnSave)) { sConn.Commit(); } if (sConn.Lifetime != ConnectionLifetime.Explicit) { ReleaseConnection(sConn); } } session.ScheduledCommands.Clear(); }
public object ExecuteLinqCommand(EntitySession session, LinqCommand command) { object result; if (command.CommandType == LinqCommandType.Select && Cache != null && Cache.TryExecuteLinqQuery(session, command, out result)) { return(result); } result = Database.ExecuteLinqCommand(session, command); //If we are returning entities, cache them if (command.CommandType == LinqCommandType.Select) { var recs = result as IList <EntityRecord>; if (Cache != null && recs != null) { Cache.CacheRecords(recs); //adds to sparse cache } } else { // Update/Insert/Delete statemetns if (Cache != null && command.TargetEntity.CacheType != CacheType.None) { Cache.Invalidate(); } } return(result); }
internal void OnSavedChanges(EntitySession session) { if (SavedChanges != null) { SavedChanges(session, new EntitySessionEventArgs(session)); } }
private void CompileViews() { if (!_dbModel.Driver.Supports(DbFeatures.Views)) { return; } var views = _dbModel.Tables.Where(t => t.Kind == EntityKind.View).ToList(); if (views.Count == 0) { return; } // create dummy session, needed for LINQ translation var dummySession = new EntitySession(new OperationContext(this._entityModel.App), EntitySessionKind.Dummy); var engine = new LinqEngine(_dbModel); var emptyList = new List <string>(); foreach (var viewTbl in views) { var entInfo = viewTbl.Entity; var expr = entInfo.ViewDefinition.Query.Expression; var viewCmd = new DynamicLinqCommand(dummySession, expr, LinqCommandKind.View, LinqOperation.Select); LinqCommandRewriter.RewriteToLambda(viewCmd); var sql = engine.TranslateSelect(viewCmd); var cmdBuilder = new DataCommandBuilder(_driver, mode: SqlGenMode.NoParameters); //there might be some local values that are transformed into params. But they will be replaced with literals // when generating final SQL cmdBuilder.AddLinqStatement(sql, viewCmd.ParamValues); viewTbl.ViewSql = cmdBuilder.GetSqlText(); } }
public object ExecuteLinqSelect(LinqCommand linqCommand, EntitySession session, DataConnection conn) { var translCmd = GetTranslateLinqCommand(linqCommand); //Locks require ongoing transaction object result; var dbCommand = CreateLinqDbCommand(conn, linqCommand, translCmd); IList resultList = translCmd.ResultListCreator(); ExecuteDbCommand(dbCommand, conn, DbExecutionType.Reader, reader => { while (reader.Read()) { var row = translCmd.ObjectMaterializer(reader, session); //row might be null if authorization filtered it out or if it is empty value set from outer join if (row != null) { resultList.Add(row); } } return(resultList.Count); }); //Post processor is extra selection op from the query (Fist,Single,Last) var postProcessor = translCmd.ResultsPostProcessor; if (postProcessor != null) { result = postProcessor.ProcessRows(resultList); } else { result = resultList; } return(result); }
public bool TryExecuteDynamicQuery(EntitySession session, LinqCommand command, out object result) { result = null; if (!CheckFullSetCacheCurrent(session)) { return(false); } var cmdInfo = command.Info; //try getting previously compiled version or compile it var cacheQuery = GetCacheQuery(command); if (cacheQuery == null) { return(false); } var start = _timeService.ElapsedMilliseconds; result = cacheQuery.CacheFunc(session, this, command.ParameterValues); var end = _timeService.ElapsedMilliseconds; var logEntry = new CacheQueryLogEntry(session.Context, cacheQuery.LogString, command.ParameterValues, _timeService.UtcNow, end - start, GetRowCount(result)); session.AddLogEntry(logEntry); session.Context.EntityCacheVersion = CurrentVersion; return(true); }
public void SaveChanges(EntitySession session) { Database.SaveChanges(session); if (Cache != null) { Cache.OnSavedChanges(session); } }
private object ExecuteLinqNonQuery(LinqCommand linqCommand, EntitySession session, DataConnection connection) { var translCmd = GetTranslateLinqCommand(linqCommand); var dbCommand = CreateLinqDbCommand(connection, linqCommand, translCmd); var result = ExecuteDbCommand(dbCommand, connection, DbExecutionType.NonQuery); return(result); }
public DataConnection(EntitySession session, Database database, ConnectionLifetime lifetime, bool admin = false) { Session = session; Database = database; Lifetime = lifetime; var connString = admin ? database.Settings.SchemaManagementConnectionString : database.Settings.ConnectionString; DbConnection = database.DbModel.Driver.CreateConnection(connString); }
public DynamicLinqCommand(EntitySession session, Expression queryExpression, LinqCommandKind kind = LinqCommandKind.Dynamic, LinqOperation op = LinqOperation.Select, EntityInfo updateEntity = null) : base(session, kind, op) { QueryExpression = queryExpression; UpdateEntity = updateEntity; LinqCommandAnalyzer.Analyze(this); }
public static SpecialLinqCommand CreateSelectByKeyValueArray(EntitySession session, EntityKeyInfo key, List <EntityKeyMemberInfo> orderBy, IList keyValues) { var sqlCacheKey = SqlCacheKeyBuilder.BuildSpecialSelectKey(Tag_SelectByKeyArray, key.Entity.Name, key.Name, LockType.None, orderBy); // build the command var paramValues = new object[] { keyValues }; return(new SpecialLinqCommand(session, sqlCacheKey, key, LockType.None, orderBy, paramValues, Setup_SelectByKeyValueArray)); }
public DataConnection(EntitySession session, DbSettings settings, DbConnectionLifetime lifetime, bool admin = false) { Session = session; DbSettings = settings; Lifetime = lifetime; var connString = admin ? settings.SchemaManagementConnectionString : settings.ConnectionString; DbConnection = settings.Driver.CreateConnection(connString); }
public IList<EntityRecord> ExecuteSelect(EntitySession session, EntityCommand command, object[] args) { IList<EntityRecord> records; if(Cache != null && Cache.TryExecuteSelect(session, command, args, out records)) return records; records = Database.ExecuteSelect(session, command, args); if(Cache != null) Cache.CacheRecords(records); return records; }
// Used for efficient reading entities in linq queries public object ReadEntity(IDataRecord dataRecord, EntitySession session) { var entRec = ReadRecord(dataRecord, session); if (entRec == null) { return(null); } return(entRec.EntityInstance); }
}//method #region Logging private void LogCommand(EntitySession session, IDbCommand command, double executionTimeMs, int rowCount = -1) { if (!session.LogEnabled) { return; } var entry = new DbCommandLogEntry(session.Context.LogContext, command, executionTimeMs, rowCount); session.Context.Log.AddEntry(entry); }
private void LogCommand(EntitySession session, IDbCommand command, long executionTime, int rowCount = -1) { if (session.LogDisabled) { return; } var entry = new DbCommandLogEntry(session.Context, command, DbModel.Driver.CommandCallFormat, _timeService.UtcNow, executionTime, rowCount); session.AddLogEntry(entry); }
// forceFullCopy is true when we put (update) records into CacheSession public static IList <EntityRecord> CloneAndAttach(EntitySession toSession, IList <EntityRecord> records, bool forceFullCopy = false) { var newRecs = new List <EntityRecord>(); for (int i = 0; i < records.Count; i++) { newRecs.Add(CloneAndAttach(toSession, records[i], forceFullCopy)); } return(newRecs); }
protected void LogComment(EntitySession session, string comment, params object[] args) { if (!session.LogEnabled) { return; } var entry = new InfoLogEntry(session.Context.LogContext, comment, args); session.AddLogEntry(entry); }
public DbUpdateSet(EntitySession session, DbModel dbModel, DataConnection conn) { Session = session; Connection = conn; Records = session.RecordsChanged.Where(rec => ShouldUpdate(rec)).ToList(); BuildRecordGroups(dbModel); var totalCount = Records.Count + Session.ScheduledCommandsCount(); UseTransaction = totalCount > 1; }
public static TEntity CloneEntity <TEntity>(EntitySession session, TEntity entity) { if (entity == null) { return(default(TEntity)); } var rec = EntityHelper.GetRecord(entity); var clone = CloneAndAttach(session, rec); return((TEntity)(object)clone.EntityInstance); }
private void ExecuteScheduledCommands(DataConnection conn, EntitySession session, IList <LinqCommand> commands) { if (commands == null || commands.Count == 0) { return; } foreach (var cmd in commands) { ExecuteLinqNonQuery(session, cmd, conn); } }
public object GetSequenceNextValue(EntitySession session, SequenceDefinition sequence) { var dbSeq = this.DbModel.LookupDbObject<DbSequenceInfo>(sequence, throwNotFound: true); var conn = GetConnection(session); try { var dbCmd = this.CreateDbCommand(dbSeq.GetNextValueCommand, conn); var result = ExecuteDbCommand(dbCmd, conn, DbExecutionType.Scalar); ReleaseConnection(conn); return result; } catch { ReleaseConnection(conn, inError: true); throw; } }
public object ExecuteLinqCommand(EntitySession session, LinqCommand command) { var conn = GetLinqCommandConnection(session, command.Info.Flags); try { object result = command.CommandType == LinqCommandType.Select ? ExecuteLinqSelect(command, session, conn) : ExecuteLinqNonQuery(command, session, conn); ReleaseConnection(conn); return result; } catch (Exception dex) { ReleaseConnection(conn, inError: true); dex.AddValue(DataAccessException.KeyLinqQuery, command.QueryExpression); throw; } }
// Creates new connection or gets previously used from the session public DataConnection GetConnection(EntitySession session, ConnectionLifetime minLifetime = ConnectionLifetime.Operation, bool admin = false) { if (admin) return new DataConnection(session, this, minLifetime, true); var conn = session.CurrentConnection; if(conn != null) { if (conn.Lifetime < minLifetime) conn.Lifetime = minLifetime; return conn; } if (session.Context.DbConnectionMode == DbConnectionReuseMode.KeepOpen) minLifetime = ConnectionLifetime.Explicit; conn = new DataConnection(session, this, minLifetime, admin: admin); session.CurrentConnection = conn; //it will register it in disposables return conn; }
public EntityRecord Lookup(EntityKey primaryKey, EntitySession session) { var strKey = primaryKey.AsString(); var data = _cacheTable.Lookup(strKey); if(data == null) return null; var needVersion = session.Context.EntityCacheVersion; if(data.Version < needVersion) { _cacheTable.Remove(primaryKey.AsString()); return null; } var rec = new EntityRecord(primaryKey); Array.Copy(data.Values, rec.ValuesOriginal, data.Values.Length); rec.SourceCacheType = CacheType.Sparse; session.Attach(rec); return rec; }
public object ExecuteLinqCommand(EntitySession session, LinqCommand command) { object result; if(command.CommandType == LinqCommandType.Select && Cache != null && Cache.TryExecuteLinqQuery(session, command, out result)) return result; result = Database.ExecuteLinqCommand(session, command); //If we are returning entities, cache them if(command.CommandType == LinqCommandType.Select) { var recs = result as IList<EntityRecord>; if(Cache != null && recs != null) Cache.CacheRecords(recs); //adds to sparse cache } else { // Update/Insert/Delete statemetns if (Cache != null && command.TargetEntity.CacheType != CacheType.None) Cache.Invalidate(); } return result; }
public object ExecuteLinqSelect(LinqCommand linqCommand, EntitySession session, DataConnection conn) { var translCmd = GetTranslateLinqCommand(linqCommand); //Locks require ongoing transaction object result; var dbCommand = CreateLinqDbCommand(conn, linqCommand, translCmd); IList resultList = translCmd.ResultListCreator(); ExecuteDbCommand(dbCommand, conn, DbExecutionType.Reader, reader => { while(reader.Read()) { var row = translCmd.ObjectMaterializer(reader, session); //row might be null if authorization filtered it out or if it is empty value set from outer join if(row != null) resultList.Add(row); } return resultList.Count; }); //Post processor is extra selection op from the query (Fist,Single,Last) var postProcessor = translCmd.ResultsPostProcessor; if (postProcessor != null) result = postProcessor.ProcessRows(resultList); else result = resultList; return result; }
public bool TryExecuteSelect(EntitySession session, EntityCommand command, object[] args, out IList<EntityRecord> records) { records = _empty; if(!Settings.CacheEnabled || session.CacheDisabled) return false; if (!string.IsNullOrWhiteSpace(command.Filter)) return false; var cachingType = command.TargetEntityInfo.CacheType; if(cachingType == CacheType.None) return false; switch(cachingType) { case CacheType.None: return false; case CacheType.FullSet: var start = _timeService.ElapsedMilliseconds; var result = _fullSetCache.TryExecuteSelect(session, command, args, out records); if(result) { var end = _timeService.ElapsedMilliseconds; var rowCount = records == null ? 0 : records.Count; LogCommand(session, command, args, cachingType, end - start, rowCount); } return result; case CacheType.Sparse: var getByPk = command.Kind == EntityCommandKind.SelectByKey && command.SelectKey.KeyType.IsSet(KeyType.PrimaryKey); if(getByPk) { var pk = new EntityKey(command.SelectKey, args); var rec = _sparseCache.Lookup(pk, session); if(rec != null) { records = new EntityRecord[] { rec }; LogCommand(session, command, args, cachingType, 0, 1); return true; } } return false; }//switch return false; }
public bool TryExecuteLinqQuery(EntitySession session, LinqCommand command, out object result) { result = null; if(!Settings.CacheEnabled || session.CacheDisabled || command.Info.Options.IsSet(QueryOptions.NoEntityCache)) return false; if(_fullSetCache.TryExecuteDynamicQuery(session, command, out result)) { return true; } return false; }
internal void OnError(EntitySession session, Exception exception) { if (Error != null) Error(session, new AppErrorEventArgs(session, exception)); }
public UpdateSet(DataConnection connection, DateTime updateTime, IList<EntityRecord> records) { Connection = connection; Session = connection.Session; UpdateTime = updateTime; Id = Session.NextTransactionId; //Start explicit transaction only if we have more than one command to execute. UseTransaction = (records.Count + Session.ScheduledCommands.Count) > 1; AllRecords.AddRange(records); //check if we need sequencing var stt = Connection.Database.Settings; var useRefIntegrity = stt.ModelConfig.Options.IsSet(DbOptions.UseRefIntegrity); var canDeferIntegrCheck = stt.Driver.Supports(Driver.DbFeatures.DeferredConstraintCheck); var needSequencing = useRefIntegrity && !canDeferIntegrCheck; if(needSequencing) SequenceRecords(); //fills entity info set else { // fill entity Info set EntityInfos.UnionWith(records.Select(r => r.EntityInfo)); } UsesOutParams = AllRecords.Any(r => UsesOutParam(r)); }
internal void OnExecutedSelect(EntitySession session, EntityCommand command) { if (ExecutedSelect != null) ExecutedSelect(session, new EntityCommandEventArgs(session, command)); }
internal void OnExecutedQuery(EntitySession session, LinqCommand command) { if (ExecutedQuery != null) ExecutedQuery(session, new LinqCommandEventArgs(session, command)); }
internal void OnSaveChangesAborted(EntitySession session) { if (SaveChangesAborted != null) SaveChangesAborted(session, new EntitySessionEventArgs(session)); }
public IList<EntityRecord> ExecuteSelect(EntitySession session, EntityCommand command, object[] args) { EntityInfo entInfo = command.TargetEntityInfo; var dbCommandInfo = GetDbCommandInfo(command); if (dbCommandInfo == null) { //check if it is request for SelectAllPaged and driver does not support paging - then substitute with SelecAll if (command == entInfo.CrudCommands.SelectAllPaged) dbCommandInfo = GetDbCommandInfo(entInfo.CrudCommands.SelectAll); } if (dbCommandInfo == null) Util.Throw("Db command not found for entity command " + command.CommandName); var conn = GetConnection(session); try { var cmd = CreateDbCommand(dbCommandInfo, conn); if (dbCommandInfo.IsTemplatedSql) FormatTemplatedSql(dbCommandInfo, cmd, args); else SetCommandParameterValues(dbCommandInfo, cmd, args); var records = new List<EntityRecord>(); var result = ExecuteDbCommand(cmd, conn, DbExecutionType.Reader, (reader) => { while(reader.Read()) records.Add(dbCommandInfo.EntityMaterializer.ReadRecord(reader, session)); return records.Count; }); ReleaseConnection(conn); return records; } catch { ReleaseConnection(conn, true); throw; } }
public DataConnection GetConnection(EntitySession session, bool admin = false) { return this.Database.GetConnection(session, admin: admin); }
internal void OnSavingChanges(EntitySession session) { if (SavingChanges != null) SavingChanges(session, new EntitySessionEventArgs(session)); }
public void SaveChanges(EntitySession session) { Database.SaveChanges(session); }
private IncludeQueryHelper(IEntitySession session, IList<LambdaExpression> includes) { _session = (EntitySession)session; _includes = includes; }
private void SaveChangesNoBatch(EntitySession session, UpdateSet updateSet) { var conn = updateSet.Connection; var withTrans = conn.DbTransaction == null && updateSet.UseTransaction; try { var start = CurrentTickCount; if(withTrans) conn.BeginTransaction(commitOnSave: true); //execute commands if (session.ScheduledCommands.Count > 0) ExecuteScheduledCommands(conn, session, CommandSchedule.TransactionStart); //Apply record updates foreach(var rec in updateSet.AllRecords) ApplyUpdate(conn, rec); //Execute scheduled commands if (session.ScheduledCommands.Count > 0) ExecuteScheduledCommands(conn, session, CommandSchedule.TransactionEnd); if (conn.DbTransaction != null && conn.Flags.IsSet(ConnectionFlags.CommitOnSave)) conn.Commit(); ReleaseConnection(conn); } catch { ReleaseConnection(conn, inError: true); throw; } }
private void LogCommand(EntitySession session, EntityCommand command, object[] args, CacheType cachingType, long time, int rowCount) { var logEntry = new CacheCommandLogEntry(session.Context, command.CommandName, args, _timeService.UtcNow, time, rowCount, cachingType); session.AddLogEntry(logEntry); }
internal void OnNewSession(EntitySession session) { if (NewSession != null) NewSession(session, new EntitySessionEventArgs(session)); }
private void ExecuteScheduledCommands(DataConnection conn, EntitySession session, CommandSchedule schedule) { if (session.ScheduledCommands.Count == 0) return; foreach (var cmd in session.ScheduledCommands) if (cmd.Schedule == schedule) { ExecuteLinqNonQuery(cmd.Command, session, conn); } }
public void SaveChanges(EntitySession session) { if (session.HasChanges()) { var records = session.RecordsChanged.Where(rec => ShouldUpdate(rec)).ToList(); var conn = GetConnection(session); var updateSet = new UpdateSet(conn, _timeService.UtcNow, records); var batchMode = ShouldUseBatchMode(updateSet); if (batchMode) SaveChangesInBatchMode(updateSet); else SaveChangesNoBatch(session, updateSet); } //commit if we have session connection with transaction and CommitOnSave var sConn = session.CurrentConnection; if (sConn != null) { if (sConn.DbTransaction != null && sConn.Flags.IsSet(ConnectionFlags.CommitOnSave)) sConn.Commit(); if (sConn.Lifetime != ConnectionLifetime.Explicit) ReleaseConnection(sConn); } session.ScheduledCommands.Clear(); }
//we need to check if we require transaction (if we are setting LOCK) private DataConnection GetLinqCommandConnection(EntitySession session, LinqCommandFlags flags) { var conn = GetConnection(session); if (conn.DbTransaction == null && flags.IsSet(LinqCommandFlags.ReadLock | LinqCommandFlags.WriteLock)) { //We need to start transaction with proper isolation level. We also need to associate connection with session, // so it will stay there and will be reused for all coming operations if (conn.Lifetime < ConnectionLifetime.Transaction) conn.Lifetime = ConnectionLifetime.Transaction; session.CurrentConnection = conn; var isoLevel = _driver.GetIsolationLevel(flags); conn.BeginTransaction(commitOnSave: true, isolationLevel: isoLevel); } return conn; }
private bool HasCacheUpdates(EntitySession session) { return session.RecordsChanged.Any(r => r.EntityInfo.CacheType != CacheType.None); }