internal DbConnection OpenConnection() { DbConnection connection = DbDriver.CreateConnection(); int times = 2; while (times > 0) { times--; try { if (connection.State != ConnectionState.Open) { connection.Open(); if (ConnectionState.Open == connection.State) { times = -1; } } else { times = -1; } } catch (Exception ex) { if (times == 0) { throw new DataException("Connection Failed." + connectionName, ex); } Thread.Sleep(0x3e8); } } return(connection); }
public DbModelConfig(DbDriver driver, DbOptions options = DbOptions.Default, DbNamingPolicy namingPolicy = null, IDictionary <string, string> schemaMappings = null) { Util.Check(driver != null, "Driver parameter may not be null."); Driver = driver; Options = options; NamingPolicy = namingPolicy ?? new DbNamingPolicy(); //import schema mappings if (schemaMappings != null) { foreach (var de in schemaMappings) { SchemaMappings[de.Key] = de.Value; } } //Verify options if (!Driver.Supports(DbFeatures.StoredProcedures)) { Options &= ~DbOptions.UseStoredProcs; } //Batch mode is not available without stored procedures if (!Options.IsSet(DbOptions.UseStoredProcs)) { Options &= ~DbOptions.UseBatchMode; } }
public DbFirstConfig(XmlDocument xmlConfig) { ProviderType = xmlConfig.GetValue(ToolConfigNames.Provider); ConnectionString = xmlConfig.GetValue(ToolConfigNames.ConnectionString); Driver = ToolHelper.CreateDriver(ProviderType, ConnectionString); Options = ReflectionHelper.ParseEnum <DbFirstOptions>(xmlConfig.GetValue(ToolConfigNames.Options)); Schemas = xmlConfig.GetValueList(ToolConfigNames.Schemas); OutputPath = xmlConfig.GetValue(ToolConfigNames.OutputPath); Namespace = xmlConfig.GetValue(ToolConfigNames.Namespace); AppClassName = xmlConfig.GetValue(ToolConfigNames.AppClassName); var autoValueSpec = xmlConfig.GetValue(ToolConfigNames.AutoValues); AutoValues = ParseAutoValuesSpec(autoValueSpec); var dataTypesSpec = xmlConfig.GetValue(ToolConfigNames.ForceDataTypes); ForceDataTypes = ParseDataTypesSpec(dataTypesSpec); IgnoreTables = new StringSet(); var ignoreList = xmlConfig.GetValue(ToolConfigNames.IgnoreTables); if (!string.IsNullOrWhiteSpace(ignoreList)) { IgnoreTables.UnionWith(ignoreList.Split(new [] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)); } }
/// <summary> /// 获取数据库驱动 /// </summary> /// <param name="typeEnum">数据库驱动类型</param> /// <param name="connectionString">数据库连接字符串</param> /// <param name="timeout">数据库超时时间</param> /// <returns></returns> public static DbDriver GetDbDriver(DbDriverTypeEnum typeEnum, string connectionString, int timeout) { DbDriver dbDriver = null; var factoryNamespace = _namespaceFactory; if (DbDriverTypeEnum.SqlServer == typeEnum) { factoryNamespace += _sqlServerFactoryStr; } else if (DbDriverTypeEnum.MySql == typeEnum) { factoryNamespace += _mySqlFactoryStr; } else if (DbDriverTypeEnum.Oracle == typeEnum) { factoryNamespace += _oracleSqlFactoryStr; } var dbFactory = (DbDriverFactory)Assembly.Load(_namespace).CreateInstance(factoryNamespace); if (dbFactory != null) { dbDriver = dbFactory.GetDbDriver(connectionString, timeout); } return(dbDriver); }
public DbFirstConfig(XmlDocument configDoc) { var rootEl = configDoc.DocumentElement; ProviderType = rootEl.GetValue(ToolConfigNames.Provider); var serverType = StringHelper.ParseEnum <DbServerType>(ProviderType); ConnectionString = rootEl.GetValue(ToolConfigNames.ConnectionString); Driver = DataUtility.CreateDriver(serverType); var strOptions = rootEl.GetValue(ToolConfigNames.Options); Options = StringHelper.ParseEnum <DbFirstOptions>(strOptions, DbFirstOptions.None); Schemas = rootEl.GetValueList(ToolConfigNames.Schemas); OutputPath = rootEl.GetValue(ToolConfigNames.OutputPath); Namespace = rootEl.GetValue(ToolConfigNames.Namespace); AppClassName = rootEl.GetValue(ToolConfigNames.AppClassName); var autoValueSpec = rootEl.GetValue(ToolConfigNames.AutoValues); AutoValues = ParseAutoValuesSpec(autoValueSpec); var dataTypesSpec = rootEl.GetValue(ToolConfigNames.ForceDataTypes); ForceDataTypes = ParseDataTypesSpec(dataTypesSpec); var ignoreList = rootEl.GetValue(ToolConfigNames.IgnoreTables); if (!string.IsNullOrWhiteSpace(ignoreList)) { IgnoreTables.UnionWith(ignoreList.Split(new [] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)); } // }
public IHttpActionResult GetDriver([FromUri] string senderID, [FromUri] string userIdToGet) { Driver result = null; if (!LoggedUsers.Contains(senderID)) { return(Content(HttpStatusCode.Unauthorized, "Not logged in.")); } try { if (DbDriver.Exists(userIdToGet)) { if (!DbAdmin.Exists(senderID) || senderID != userIdToGet) { return(Content(HttpStatusCode.Unauthorized, "Not a dispatcher nor the user whose information are requested.")); } result = DbDriver.GetSingleEntityByKey(userIdToGet); } } catch (Exception e) { Trace.Write($"Error on 'GetDriver()'. Error message: {e.Message}"); Trace.Write($"[STACK_TRACE] {e.StackTrace}"); return(InternalServerError(e)); } if (result == null) { return(NotFound()); } return(Ok(result)); }
public DbModelBuilder(EntityModel entityModel, DbModelConfig config) { _entityModel = entityModel; _config = config; _log = entityModel.App.SystemLog; _driver = _config.Driver; }
public DbBatchBuilder(Database db) { _db = db; _driver = _db.DbModel.Driver; _dbModel = _db.DbModel; _sqlFactory = _db.SqlFactory; }
public IHttpActionResult GetUsers([FromUri] string senderID) { List <IUser> result = new List <IUser>(); if (!LoggedUsers.Contains(senderID)) { return(Content(HttpStatusCode.Unauthorized, "Not logged in.")); } //other rights? try { (DbAdmin.GetAll()).ToList().ForEach(a => result.Add(a)); (DbCustomer.GetAll()).ToList().ForEach(c => result.Add(c)); (DbDriver.GetAll()).ToList().ForEach(d => result.Add(d)); } catch (Exception e) { Trace.Write($"Error on 'GetUsers()'. Error message: {e.Message}"); Trace.Write($"[STACK_TRACE] {e.StackTrace}"); return(InternalServerError(e)); } return(Ok(result)); }
public static bool IsSignatureEqual(ProcState a, ProcState b, DbDriver dbDriver) { if (object.ReferenceEquals(a, b)) { return(true); } if (a == null || b == null) { return(false); } var aFunc = a as FunctionState; var bFunc = b as FunctionState; if (aFunc != null && bFunc != null) { // If they're both functions, the return types need to match. if (!dbDriver.StringEquals(aFunc.ReturnType, bFunc.ReturnType)) { return(false); } } else if (aFunc != null || bFunc != null) { // If one of them is a function but NOT both, they aren't equal. return(false); } return(Enumerable.SequenceEqual(a.Parameters, b.Parameters, ProcParam.GetComparer(dbDriver))); }
public IHttpActionResult GetPage([FromUri] string senderID) { if (!LoggedUsers.Contains(senderID)) { return(Content(HttpStatusCode.Unauthorized, "Not logged in.")); } try { if (DbAdmin.Exists(senderID)) { return(Ok("./Content/partials/adminProfile.html")); } else if (DbDriver.Exists(senderID)) { return(Ok("./Content/partials/driverProfile.html")); } else if (DbCustomer.Exists(senderID)) { return(Ok("./Content/partials/customerProfile.html")); } else { return(NotFound()); } } catch (Exception e) { Trace.Write($"Error on 'Login()'. Error message: {e.Message}"); Trace.Write($"[STACK_TRACE] {e.StackTrace}"); return(InternalServerError(e)); } }
// constructors public Database(EntityApp app, DbSettings settings) { _app = app; Settings = settings; _driver = Settings.ModelConfig.Driver; _entityModel = app.Model; _timeService = _app.TimeService; //Set list of all schemas var allSchemas = app.Areas.Select(a => settings.ModelConfig.GetSchema(a)); settings.SetSchemas(allSchemas); //Check if model is shared var modelConfig = Settings.ModelConfig; bool modelIsShared = modelConfig.Options.IsSet(DbOptions.ShareDbModel); lock (modelConfig) { //we need lock to prevent collision on shared model if (modelIsShared) { DbModel = modelConfig.SharedDbModel; } if (DbModel == null) { var dbmBuilder = new DbModelBuilder(app.Model, modelConfig); DbModel = dbmBuilder.Build(); if (modelIsShared) { modelConfig.SharedDbModel = DbModel; } } }//lock //Save }
public DbModelBuilder(EntityModel entityModel, DbModelConfig config, IActivationLog log) { _entityModel = entityModel; _dbModelConfig = config; _namingPolicy = _dbModelConfig.NamingPolicy; _log = log; _driver = _dbModelConfig.Driver; }
public SqlFactory(DbModel dbModel) { _dbModel = dbModel; _driver = _dbModel.Driver; _sqlCache = new SqlCache(10000); _linqEngine = new LinqEngine(_dbModel); _crudSqlBuilder = _dbModel.Driver.CreateCrudSqlBuilder(_dbModel); }
// constructors public Database(DbModel dbModel, DbSettings settings) { this.DbModel = dbModel; Settings = settings; _driver = Settings.Driver; _timeService = dbModel.EntityApp.TimeService; SqlFactory = new SqlFactory(dbModel); }
public override void InitConnection(DbDriver driver, IDbConnection conn) { if (ConfigReader.Config.Database.UseForeignKey) { using (IDbCommand e = driver.GetDbCommand(new SqlStatement("PRAGMA foreign_keys = ON;"), conn)) { e.ExecuteNonQuery(); } } }
//Prepares for full run with a specified server public static void Reset(DbServerType serverType) { DeleteLocalLogFiles(); InitAppConfig(); ServerType = serverType; if (ServerType == DbServerType.SQLite) { DeleteSqliteDbFile(); //it will be created on connect, creat-option in conn string } Driver = DataUtility.CreateDriver(ServerType); //Load connection string var connStringName = ServerType.ToString() + "ConnectionString"; // For SQLite we can use either provider var useMsSqlite = AppConfig["UseMsSqliteProvider"] == "true"; if (ServerType == DbServerType.SQLite && useMsSqlite) { var sqliteDriver = (Data.SQLite.SQLiteDbDriver)Driver; sqliteDriver.ConnectionFactory = (s) => new Microsoft.Data.Sqlite.SqliteConnection(s); sqliteDriver.CommandFactory = () => new Microsoft.Data.Sqlite.SqliteCommand(); connStringName += "_MS"; } var connString = AppConfig[connStringName]; Util.Check(!string.IsNullOrEmpty(connString), "Connection string not found for key: {0}.", connStringName); if (connString.Contains("{bin}")) { var asmPath = Assembly.GetExecutingAssembly().Location; var binFolder = Path.GetDirectoryName(asmPath); connString = connString.Replace("{bin}", binFolder); } ConnectionString = connString; DbOptions = Driver.GetDefaultOptions(); //enable batch var useBatch = AppConfig["useBatchMode"] == "true"; if (useBatch && Driver.Supports(DbFeatures.BatchedUpdates)) { DbOptions |= DbOptions.UseBatchMode; } else { DbOptions &= ~DbOptions.UseBatchMode; } //check connection if (!DataUtility.TestConnection(Driver, ConnectionString, out var error)) { Util.Throw("Failed to connect to the database: {0} \r\n Connection string: {1}", error, ConnectionString); } }
public readonly string SchemaManagementConnectionString; //optional, admin-privilege conn string public DbSettings(DbDriver driver, DbOptions options, string connectionString, string schemaManagementConnectionString = null, DbUpgradeMode upgradeMode = DbUpgradeMode.NonProductionOnly, DbUpgradeOptions upgradeOptions = DbUpgradeOptions.Default, IDbNamingPolicy namingPolicy = null, string dataSourceName = "(Default)") : this(new DbModelConfig(driver, options, namingPolicy), connectionString, schemaManagementConnectionString, upgradeMode, upgradeOptions, dataSourceName) { }
public override int ExecuteNonQuery(string cmd, int timeout = 0) { DbCommand command = DbDriver.CreateCommand(cmd, _connection); if (timeout > 0) { command.CommandTimeout = timeout; } return(command.ExecuteNonQuery()); }
public override DbDataReader ExecuteReader(string cmd, int timeout = 0) { DbCommand command = DbDriver.CreateCommand(cmd, _connection); if (timeout > 0) { command.CommandTimeout = timeout; } return(command.ExecuteReader()); }
/// <summary> /// Gets the example query meta data. /// </summary> /// <param name="dbDriver">The driver.</param> /// <param name="sampleSQL">The sample SQL.</param> /// <param name="metadataSetting">The metadata setting.</param> /// <param name="contextAttributes">The context attributes.</param> /// <returns></returns> private static QueryMetaData GetExampleQueryMetaData( DbDriver dbDriver, string sampleSQL, ColumnSettings metadataSetting, IEnumerable<Attribute> contextAttributes) { var sampleSQLFragments = PlaceholderParser.ParsePlaceholder(sampleSQL); using (var dbCommand = dbDriver.CreateCommand(sampleSQLFragments, metadataSetting, contextAttributes)) { return dbCommand.MetaData; } }
public DbUpdateConfig(XmlDocument xmlConfig) { ProviderType = xmlConfig.GetValue(ToolConfigNames.Provider); ConnectionString = xmlConfig.GetValue(ToolConfigNames.ConnectionString); Driver = ToolHelper.CreateDriver(ProviderType, ConnectionString); ModelUpdateOptions = ReflectionHelper.ParseEnum <DbUpgradeOptions>(xmlConfig.GetValue(ToolConfigNames.ModelUpdateOptions)); DbOptions = ReflectionHelper.ParseEnum <DbOptions>(xmlConfig.GetValue(ToolConfigNames.DbOptions)); AssemblyPath = xmlConfig.GetValue(ToolConfigNames.AssemblyPath); AppClassName = xmlConfig.GetValue(ToolConfigNames.AppClassName); OutputPath = xmlConfig.GetValue(ToolConfigNames.OutputPath); }
/// <summary> /// 创建数据库操作器 /// </summary> /// 执行用户代码时应该使用由主操作器分配的无特权用户 public static BaseDbOperator Create(DbLangConfig dbConfig) { string connString = dbConfig.ConnectionString; DbDriver driver = DbDriverLoader.Load(dbConfig.DriverPath); if (dbConfig.Name == DatabaseType.mysql.ToString()) { return(new MySqlOperator(connString, driver)); } throw new NotImplementedException("Db operator not implemented: " + dbConfig.Name); }
public DataCommandBuilder(DbDriver driver, bool batchMode = false, SqlGenMode mode = SqlGenMode.PreferParam) { _driver = driver; _sqlDialect = _driver.SqlDialect; _batchMode = batchMode; _genMode = mode; _maxLiteralLength = _driver.SqlDialect.MaxLiteralLength; _dbCommand = _driver.CreateCommand(); //reserve spots: #0 for batch-begin (BEGIN; in ORACLE); #2 for Begin Trans _sqlStrings.Add(string.Empty); _sqlStrings.Add(string.Empty); }
public IHttpActionResult PostDriver([FromUri] string senderID, [FromBody] DriverModel driverModel) { Driver driver = new Driver(driverModel.Username, driverModel.Password) { FirstName = driverModel.FirstName, LastName = driverModel.LastName, Gender = driverModel.Gender, JMBG = driverModel.JMBG, Phone = driverModel.Phone, Email = driverModel.Email, DriversLocation = DbLocation.GetSingleEntityByKey(driverModel.DriversLocationID), DriversVehicle = DbVehicle.GetSingleEntityByKey(driverModel.DriversVehicleID), }; driverModel.TaxiDrivesIDs.ForEach(td => driver.TaxiDrives.Add(DbTaxiDrive.GetSingleEntityByKey(td))); if (!LoggedUsers.Contains(senderID)) { return(Content(HttpStatusCode.Unauthorized, "Not logged in.")); } else if (!DbAdmin.Exists(senderID)) { return(Content(HttpStatusCode.Unauthorized, "Not a dispatcher.")); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } bool result; try { result = DbDriver.Add(driver); } catch (Exception e) { Trace.Write($"Error on 'PostDriver()'. Error message: {e.Message}"); Trace.Write($"[STACK_TRACE] {e.StackTrace}"); return(InternalServerError(e)); } if (result) { return(Ok(driver)); } else { return(BadRequest("Driver already exists.")); } }
public DbUpdateConfig(XmlDocument xmlConfig) { ProviderType = xmlConfig.GetValue(ToolConfigNames.Provider); var serverType = (DbServerType)Enum.Parse(typeof(DbServerType), ProviderType); ConnectionString = xmlConfig.GetValue(ToolConfigNames.ConnectionString); Driver = DataUtility.CreateDriver(serverType); ModelUpdateOptions = StringHelper.ParseEnum <DbUpgradeOptions>(xmlConfig.GetValue(ToolConfigNames.ModelUpdateOptions)); DbOptions = StringHelper.ParseEnum <DbOptions>(xmlConfig.GetValue(ToolConfigNames.DbOptions)); AssemblyPath = xmlConfig.GetValue(ToolConfigNames.AssemblyPath); AppClassName = xmlConfig.GetValue(ToolConfigNames.AppClassName); OutputPath = xmlConfig.GetValue(ToolConfigNames.OutputPath); }
/// <summary> /// 使用连接字符串名构造, 支持是否使用事务。 /// 注意:使用事务的情况下, 请务必调用CommitTransaction方法。 /// </summary> /// <param name="connectionName">连接字符串名</param> /// <param name="useTransaction">是否使用事务</param> public DbSession(string connectionName, bool useTransaction, IsolationLevel isolationLevel) { this.connectionName = connectionName; dbDriver = DbDriverFactory.Instance.GetInstance(connectionName); Thread.BeginThreadAffinity(); _parent = _head; _head = this; this.useTransaction = useTransaction; this.isolationLevel = isolationLevel; }
//Prepares for full run with a specified server internal static void Reset(TestConfig config) { if (BooksApp != null) { BooksApp.Flush(); } Thread.Sleep(100); //to allow log dump of buffered messages DeleteLogFiles(); //it will happen only once WriteLog("\r\n------------------------ " + config.ToString() + "---------------------------------------------\r\n\r\n"); ServerType = config.ServerType; CacheEnabled = config.EnableCache; UseBatchMode = config.UseBatchMode; BooksApp = null; _initFailed = false; var protectedSection = (NameValueCollection)ConfigurationManager.GetSection("protected"); //Load connection string ConnectionString = ReplaceBinFolderToken(protectedSection[ServerType + "ConnectionString"]); Util.Check(!string.IsNullOrEmpty(ConnectionString), "Connection string not found for server: {0}.", ServerType); LogConnectionString = ReplaceBinFolderToken(protectedSection[ServerType + "LogConnectionString"]); LogConnectionString = LogConnectionString ?? ConnectionString; LoginCryptoKey = protectedSection["LoginInfoCryptoKey"]; Driver = ToolHelper.CreateDriver(ServerType, ConnectionString); var dbOptions = ToolHelper.GetDefaultOptions(ServerType); if (config.UseStoredProcs) { dbOptions |= DbOptions.UseStoredProcs; } else { dbOptions &= ~DbOptions.UseStoredProcs; } if (config.UseBatchMode) { dbOptions |= DbOptions.UseBatchMode; } else { dbOptions &= ~DbOptions.UseBatchMode; } // dbOptions |= DbOptions.ForceArraysAsLiterals; -- just to test this flag DbSettings = new DbSettings(Driver, dbOptions, ConnectionString, upgradeMode: DbUpgradeMode.Always); //Test: remap login schema into login2 // if (ServerType == DbServerType.MsSql) // DbSettings.ModelConfig.MapSchema("login", "login2"); }
// PUT api/drivers/5 public IHttpActionResult PutDriver([FromUri] string senderID, [FromBody] DriverModel driverModel) { bool result = false; if (!LoggedUsers.Contains(senderID)) { return(Content(HttpStatusCode.Unauthorized, "Not logged in.")); } if (DbDriver.Exists(driverModel.Username)) { if (!DbAdmin.Exists(senderID) || senderID != driverModel.Username) { return(Content(HttpStatusCode.Unauthorized, "Not a dispatcher nor a user to be modified.")); } try { Driver driver = new Driver(driverModel.Username, driverModel.Password) { FirstName = driverModel.FirstName, LastName = driverModel.LastName, Gender = driverModel.Gender, JMBG = driverModel.JMBG, Phone = driverModel.Phone, Email = driverModel.Email, DriversLocation = DbLocation.GetSingleEntityByKey(driverModel.DriversLocationID), DriversVehicle = DbVehicle.GetSingleEntityByKey(driverModel.DriversVehicleID), }; driverModel.TaxiDrivesIDs.ForEach(td => driver.TaxiDrives.Add(DbTaxiDrive.GetSingleEntityByKey(td))); result = DbDriver.Modify(driver); } catch (Exception e) { Trace.Write($"Error on 'PutDriver()'. Error message: {e.Message}"); Trace.Write($"[STACK_TRACE] {e.StackTrace}"); return(InternalServerError(e)); } } if (result) { return(Ok(driverModel)); } else { return(NotFound()); } }
public static bool TestConnection(DbDriver driver, string connString, out string message) { message = null; var conn = driver.CreateConnection(connString); try { conn.Open(); conn.Close(); return(true); } catch (Exception ex) { message = " Connection test failed: " + ex.Message; return(false); } }//method
public DataSourceDriver() { _dbDriver = new DbDriver(); }
public MatchDataDriver() { _dbDriver = new DbDriver(); }
public void LoadSettings() { try { _showconsole = _ini.GetBoolSetting("General", "ShowConsole"); } catch { _showconsole = false; } try { _logRequests = _ini.GetBoolSetting("General", "LogRequests"); } catch { _logRequests = false; } try { _cacheData = _ini.GetBoolSetting("General", "CacheData", true); } catch { _cacheData = true; } try { var driver = _ini.GetSetting("General", "Driver", "sqlite").ToLower(); switch (driver) { case "sqlite": _driver = DbDriver.Sqlite; break; case "mysql": _driver = DbDriver.Mysql; break; default: Logger.Log(String.Format("Unknown driver {0}", _driver), typeof (Settings)); _driver = DbDriver.Sqlite; break; } } catch { _driver = DbDriver.Sqlite; } try { _mysqlHost = _ini.GetSetting("MySQL", "Host", "localhost"); } catch { _mysqlHost = "localhost"; } try { _mysqlPort = Convert.ToInt16(_ini.GetSetting("MySQL", "Port", "3306")); } catch { _mysqlPort = 3306; } try { _mysqlUser = _ini.GetSetting("MySQL", "User", "root"); } catch { _mysqlUser = "******"; } try { _mysqlPassword = _ini.GetSetting("MySQL", "Password"); } catch { _mysqlPassword = ""; } try { _mysqlDatabase = _ini.GetSetting("MySQL", "Database"); } catch { _mysqlDatabase = ""; } try { _sqlitefile = _ini.GetSetting("Sqlite", "DBFile", @"db\eposql.db"); } catch { _sqlitefile = ""; } SaveSettings(); }