///<summary> /// Creates a SelectQueryDB, wrapping an ISelectQuery (Decorator pattern) ///</summary> ///<param name="selectQuery"></param> ///<param name="databaseConnection"></param> public SelectQueryDB(ISelectQuery selectQuery, IDatabaseConnection databaseConnection) { Aliases = new Dictionary<string, string>(); _selectQuery = selectQuery; _databaseConnection = databaseConnection; SetupAliases(); }
public static void MyClassInitialize(TestContext testContext) { ObjectFactory.Inject<IDatabaseConnection>(new DatabaseConnection()); ObjectFactory.Inject<IEnvironment>(new Environment()); _databaseConnection = ObjectFactory.GetInstance<IDatabaseConnection>(); }
/// <summary> /// Invokes the GetSessions business operation. /// </summary> private async Task<GetSessionsBusinessResponse> InvokeGetSessions(IDatabaseConnection databaseConnection) { try { // Build the GetSessions business request. GetSessionsBusinessRequest getSessionsBusinessRequest = new GetSessionsBusinessRequest(); // Invoke the GetSessions business operation. GetSessionsBusinessResponse getSessionsBusinessResponse = await this.schedulingBusinessLogicComponent.GetSessions(databaseConnection, getSessionsBusinessRequest); // The business operation succeeded. return getSessionsBusinessResponse; } catch (GetSessionsBusinessException getSessionsBusinessException) { // Wrap the GetSessions business exception into a service exception. ServiceException serviceException = ServiceExceptionBuilder.BuildServiceException( "SchedulingServiceComponent.SessionsController.Get()", getSessionsBusinessException, getSessionsBusinessException.Errors.Select(error => error.ErrorCode.ToString()).ToArray(), getSessionsBusinessException.Errors.Select(error => error.ErroneousValue).ToArray()); // Throw the ErrorCode service exception. throw serviceException; } }
private void ShowConnectionDescription(IDatabaseConnection currentConnection) { switch (currentConnection.EngineType) { case DatabaseEngineType.SqlServer: SqlCommon.SqlForm.status.Items[SectionEngine].Image = Resources.SqlServer016; break; case DatabaseEngineType.Oracle: SqlCommon.SqlForm.status.Items[SectionEngine].Image = Resources.Oracle016; break; } SqlCommon.SqlForm.status.Items[SectionEngine].Text = string.Format(" Type: {0} ", currentConnection.EngineName); SqlCommon.SqlForm.status.Items[SectionDataSource].Text = string.Format(" {0}: {1} ", currentConnection.DataSourceDescription, currentConnection.DataSourceValue); SqlCommon.SqlForm.status.Items[SectionDatabase].Text = string.Format(" {0}: {1} ", currentConnection.DatabaseDescription, currentConnection.DatabaseValue); if (currentConnection.IsUbwDatabase) { SqlCommon.SqlForm.status.Items[SectionUbw].Image = Resources.Unit4016; SqlCommon.SqlForm.status.Items[SectionUbw].Text = string.Format(" UBW {0} ", currentConnection.UbwDatabaseDescription); } else { SqlCommon.SqlForm.status.Items[SectionUbw].Image = Resources.NoUnit4016; SqlCommon.SqlForm.status.Items[SectionUbw].Text = " Ikke en UBW database "; } SqlCommon.SqlForm.status.Items[SectionName].Text = string.Format(" {0} ", currentConnection.Name); SetNotConnectedVisible(false); }
/// <summary> /// Reads the single Session data row matching the specified SessionID. /// </summary> public async Task<SessionDataRow> ReadBySessionID(IDatabaseConnection databaseConnection, int sessionID) { // Build the SQL command. using (SqlCommand sqlCommand = new SqlCommand("SELECT * FROM [Session] WHERE [SessionID] = @sessionID;")) { // Use the specified database connection. SqlConnection sqlConnection = (databaseConnection as DatabaseConnection).SqlConnection; sqlCommand.Connection = sqlConnection; // Set the SQL command parameter values. sqlCommand.Parameters.Add("@sessionID", SqlDbType.Int).Value = sessionID; // Execute the SQL command. using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) { // Read the Session data row. SessionDataRow sessionDataRow = null; if (await sqlDataReader.ReadAsync()) { sessionDataRow = this.GetSqlDataReaderValues(sqlDataReader); } // Return the Session data row. return sessionDataRow; } } }
/// <summary> /// Reads the single CourseSchedule data row matching the specified CourseScheduleID. /// </summary> public async Task<CourseScheduleDataRow> ReadByCourseScheduleID(IDatabaseConnection databaseConnection, int courseScheduleID) { // Build the SQL command. using (SqlCommand sqlCommand = new SqlCommand("SELECT * FROM [CourseSchedule] WHERE [CourseScheduleID] = @courseScheduleID;")) { // Use the specified database connection. SqlConnection sqlConnection = (databaseConnection as DatabaseConnection).SqlConnection; sqlCommand.Connection = sqlConnection; // Set the SQL command parameter values. sqlCommand.Parameters.Add("@courseScheduleID", SqlDbType.Int).Value = courseScheduleID; // Execute the SQL command. using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) { // Read the CourseSchedule data row. CourseScheduleDataRow courseScheduleDataRow = null; if (await sqlDataReader.ReadAsync()) { courseScheduleDataRow = this.GetSqlDataReaderValues(sqlDataReader); } // Return the CourseSchedule data row. return courseScheduleDataRow; } } }
/// <summary> /// Invokes the NewSession business operation. /// </summary> private async Task<NewSessionBusinessResponse> InvokeNewSession(IDatabaseConnection databaseConnection, SessionResource resource) { try { // Build the NewSession business request. NewSessionBusinessRequest newSessionBusinessRequest = new NewSessionBusinessRequest(); // Build the Session business request element. if (resource.Session != null) { NewSessionBusinessRequest.SessionBusinessRequestElement sessionBusinessRequestElement = new NewSessionBusinessRequest.SessionBusinessRequestElement(); sessionBusinessRequestElement.Name = resource.Session.Name; sessionBusinessRequestElement.StartDate = resource.Session.StartDate; newSessionBusinessRequest.Session = sessionBusinessRequestElement; } // Invoke the NewSession business operation. NewSessionBusinessResponse newSessionBusinessResponse = await this.schedulingBusinessLogicComponent.NewSession(databaseConnection, newSessionBusinessRequest); // The business operation succeeded. return newSessionBusinessResponse; } catch (NewSessionBusinessException newSessionBusinessException) { // Wrap the NewSession business exception into a service exception. ServiceException serviceException = ServiceExceptionBuilder.BuildServiceException( "SchedulingServiceComponent.SessionsController.Post()", newSessionBusinessException, newSessionBusinessException.Errors.Select(error => error.ErrorCode.ToString()).ToArray(), newSessionBusinessException.Errors.Select(error => error.ErroneousValue).ToArray()); // Throw the service exception. throw serviceException; } }
/// <summary> /// Executes the GetSessions business operation. /// </summary> public async virtual Task<GetSessionsBusinessResponse> GetSessions(IDatabaseConnection databaseConnection, GetSessionsBusinessRequest businessRequest) { // Validate the business request. this.ValidateGetSessionsRequest(businessRequest); // Initialize the operation data. GetSessionsOperationData operationData = new GetSessionsOperationData(); // Validate the business operation. await this.ValidateGetSessionsOperation(databaseConnection, businessRequest, operationData); // Read the Session data rows. operationData.SessionDataRows = await this.sessionDataAccessComponent.ReadAll(databaseConnection); // Build the business response. GetSessionsBusinessResponse businessResponse = new GetSessionsBusinessResponse(); // Build the Session business response elements. List<GetSessionsBusinessResponse.SessionBusinessResponseElement> sessionBusinessResponseElements = new List<GetSessionsBusinessResponse.SessionBusinessResponseElement>(); foreach (SessionDataRow sessionDataRow in operationData.SessionDataRows) { // Build the Session business response element. GetSessionsBusinessResponse.SessionBusinessResponseElement sessionBusinessResponseElement = new GetSessionsBusinessResponse.SessionBusinessResponseElement(); sessionBusinessResponseElement.SessionCode = sessionDataRow.SessionCode; sessionBusinessResponseElement.Name = sessionDataRow.Name; sessionBusinessResponseElement.StartDate = sessionDataRow.StartDate; sessionBusinessResponseElements.Add(sessionBusinessResponseElement); } // Set the Session business response elements. businessResponse.Sessions = sessionBusinessResponseElements.ToArray(); // Return the business response. return businessResponse; }
/// <summary> /// Executes the NewSession business operation. /// </summary> public async virtual Task<NewSessionBusinessResponse> NewSession(IDatabaseConnection databaseConnection, NewSessionBusinessRequest businessRequest) { // Validate the business request. this.ValidateNewSessionRequest(businessRequest); // Initialize the operation data. NewSessionOperationData operationData = new NewSessionOperationData(); // Validate the business operation. await this.ValidateNewSessionOperation(databaseConnection, businessRequest, operationData); // Generate a unique Session code. string sessionCode = this.uniqueTokenGenerator.GenerateUniqueToken(); // Create the Session data row. operationData.SessionDataRow = new SessionDataRow(); operationData.SessionDataRow.SessionCode = sessionCode; operationData.SessionDataRow.Name = businessRequest.Session.Name; operationData.SessionDataRow.StartDate = businessRequest.Session.StartDate; await this.sessionDataAccessComponent.Create(databaseConnection, operationData.SessionDataRow); // Build the business response. NewSessionBusinessResponse businessResponse = new NewSessionBusinessResponse(); // Build the Session business response element. NewSessionBusinessResponse.SessionBusinessResponseElement sessionBusinessResponseElement = new NewSessionBusinessResponse.SessionBusinessResponseElement(); sessionBusinessResponseElement.SessionCode = operationData.SessionDataRow.SessionCode; businessResponse.Session = sessionBusinessResponseElement; // Return the business response. return businessResponse; }
public void TestFixtureSetUp() { // initialize a server connection to a locally-running MongoDB server _serverConnection = new ServerConnection(LOCAL_MONGO_SERVER_CONNECTION_STRING); // connect to the existing db on the server (or create it if it does not already exist) _databaseConnection = new DatabaseConnection(_serverConnection, "MyFirstDatabase"); }
public void Save(IDatabaseConnection connection) { LoadAll(); DeleteFromList(connection.Name); _connections.Insert(0, connection); SaveAll(); }
public void SetupTest() { conn = Substitute.For<IDatabaseConnection>(); statement = new SqlStatement(DatabaseConnection.CurrentConnection); statement.Statement.Append(Sql); conn.LoadDataTable(statement, "", "").Returns(dt); conn.GetConnection().Returns(DatabaseConnection.CurrentConnection.GetConnection()); }
private void TerminateCurrentConnectionIfAny() { SqlCommon.SqlForm.menuWindowNewSame.Enabled = false; if (null != CurrentConnection) { SqlCommon.DatabaseContent.ShowDatabaseDisconnected(); CurrentConnection = null; } }
public IDatabaseConnection Add(DataSource source, IDatabaseConnection connection) { Infrastructure.Guard.AgainstNull(connection, "connection"); Guard(); connections.Add(source.Key, connection); return connection; }
private void PrepareCurrentConnection(IDatabaseConnection connection) { CurrentConnection = connection; CurrentConnection.Open(); SqlCommon.Status.Set(CurrentConnection); CurrentConnection.Close(); SqlCommon.SqlForm.Text = String.Format("{0} - {1}", connection.Name, Global.FullTitle); SqlCommon.DatabaseContent.ConnectedTo(); SqlCommon.SqlForm.menuWindowNewSame.Enabled = true; }
public void HandleFirstTimeConnect(IDatabaseConnection connection) { FirstTimeConnectForm form = new FirstTimeConnectForm(connection); if (form.ShowDialog(SqlCommon.SqlForm) == DialogResult.OK) { TerminateCurrentConnectionIfAny(); PrepareCurrentConnection(form.Connection); SqlCommon.SqlForm.tools.Invalidate(); } }
public void SetupTest() { dbConnMock = new DynamicMock(typeof (IDatabaseConnection)); conn = (IDatabaseConnection) dbConnMock.MockInstance; statement = new SqlStatement(DatabaseConnection.CurrentConnection); statement.Statement.Append(Sql); dbConnMock.ExpectAndReturn("LoadDataTable", dt, new object[] {statement, "", ""}); dbConnMock.ExpectAndReturn("GetConnection", DatabaseConnection.CurrentConnection.GetConnection(), new object[] {}); }
public AuthenticatedSession(User user, IDatabaseConnection connection) { if (user == null) throw new ArgumentNullException("user"); if (connection == null) throw new ArgumentNullException("connection"); User = user; Connection = connection; }
public bool Identical(IDatabaseConnection connection) { LoadAll(); foreach (IDatabaseConnection existingConnection in _connections) { if (connection.Equals(existingConnection)) return true; if (connection.Name == existingConnection.Name) return false; } return false; }
public void Set(IDatabaseConnection connection) { if (null == connection) { ShowNoConnection(); } else { ShowConnectionDescription(connection); } }
public DatabaseCountOperator( ITable table, QueryFilter query) { this.table = table; this.query = query; if (!(query is SelectFilter) || !((SelectFilter)query).IsCount) { throw new Exception("Invalid query filter. It should be a select filter and should have IsCount set to true"); } this.connection = DatabaseConnectionFactory.Instance.CreateDatabaseConnection(); }
public DatabaseQueryOperator( ITable table, QueryFilter query) { this.table = table; this.query = query; if (!(query is SelectFilter)) { throw new Exception("Invalid query filter. It should be a select filter"); } this.connection = DatabaseConnectionFactory.Instance.CreateDatabaseConnection(); }
public void SetupTestFixture() { var config = new DatabaseConfig(DatabaseConfig.SqlServer, "test", "test", "test", "test", "1000"); _connection = new DatabaseConnectionFactory().CreateConnection(config); _testStatement = new SqlStatement(_connection); _rawStatement = "insert into tb1 (field1, field2, field3) values (@Param1, @Param2, @Param3)"; _testStatement.Statement.Append(_rawStatement); _addedParameter = _testStatement.AddParameter("Param1", "12345"); _testStatement.AddParameter("Param2", "67890"); _testStatement.AddParameter("Param3", "13579"); _command = _connection.GetConnection().CreateCommand(); _testStatement.SetupCommand(_command); }
public bool Equals(IDatabaseConnection other) { if (Name != other.Name) return false; if (Description != other.Description) return false; if (EngineName != other.EngineName) return false; if (ServerName != other.ServerName) return false; if (EngineType != other.EngineType) return false; OracleDatabaseConnection typedOther = other as OracleDatabaseConnection; if (null == typedOther) return false; if (SidOrServiceName != typedOther.SidOrServiceName) return false; if (Port != typedOther.Port) return false; if (UserName != other.UserName) return false; if (Password != other.Password) return false; return true; }
public void SetupFixture() { GlobalRegistry.ApplicationName = appName; GlobalRegistry.ApplicationVersion = appVersion; GlobalRegistry.DatabaseVersion = dbVersion; GlobalRegistry.Settings = settings; GlobalRegistry.UIExceptionNotifier = exNotifier; itsConn = Substitute.For<IDatabaseConnection>(); itsDbMigrator = new DBMigrator(itsConn); itsDbMigrator.AddMigration(1, "migration1;"); itsDbMigrator.AddMigration(2, "migration2;"); itsDbMigrator.AddMigration(3, "migration3;"); _itsSettings = Substitute.For<ISettings>(); }
/// <summary> /// Constructor to initialise a new sql statement /// </summary> /// <param name="connection">A database connection</param> public SqlStatement(IDatabaseConnection connection) { if (connection == null) throw new ArgumentNullException("connection"); _parameters = new List<IDbDataParameter>(); DatabaseConnection = connection; _idbConnection = DatabaseConnection.GetConnection(); if (_idbConnection != null) { _sampleCommand = _idbConnection.CreateCommand(); _gen = connection.CreateParameterNameGenerator(); } else { _gen = new ParameterNameGenerator(null); } _statement = new StringBuilder(100); }
public void SetupFixture() { GlobalRegistry.ApplicationName = appName; GlobalRegistry.ApplicationVersion = appVersion; GlobalRegistry.DatabaseVersion = dbVersion; GlobalRegistry.Settings = settings; GlobalRegistry.UIExceptionNotifier = exNotifier; itsConnMock = new DynamicMock(typeof(IDatabaseConnection)); itsConn = (IDatabaseConnection)itsConnMock.MockInstance; itsDbMigrator = new DBMigrator(itsConn); itsDbMigrator.AddMigration(1, "migration1;"); itsDbMigrator.AddMigration(2, "migration2;"); itsDbMigrator.AddMigration(3, "migration3;"); itsSettingsMock = new DynamicMock(typeof(ISettings)); _itsSettings = (ISettings)itsSettingsMock.MockInstance; }
public bool Equals(IDatabaseConnection other) { if (Name != other.Name) return false; if (Description != other.Description) return false; if (EngineName != other.EngineName) return false; if (ServerName != other.ServerName) return false; if (EngineType != other.EngineType) return false; SqlServerDatabaseConnection typedOther = other as SqlServerDatabaseConnection; if (null == typedOther) return false; if (InstanceName != typedOther.InstanceName) return false; if (DatabaseName != typedOther.DatabaseName) return false; if (WindowsAuthentication != typedOther.WindowsAuthentication) return false; if (!WindowsAuthentication) { if (UserName != other.UserName) return false; if (Password != other.Password) return false; } return true; }
/// <summary> /// Creates the specified Session data row. /// </summary> public async Task Create(IDatabaseConnection databaseConnection, SessionDataRow sessionDataRow) { // Build the SQL command. using (SqlCommand sqlCommand = new SqlCommand("INSERT INTO [Session] VALUES (@sessionCode, @name, @startDate); SELECT CAST(SCOPE_IDENTITY() AS INT);")) { // Use the specified database connection. SqlConnection sqlConnection = (databaseConnection as DatabaseConnection).SqlConnection; sqlCommand.Connection = sqlConnection; // Set the SQL command parameter values. this.SetSqlCommandParameterValues(sqlCommand, sessionDataRow, setPrimaryKeyValue: false); // Execute the SQL command. int sessionID = (int)await sqlCommand.ExecuteScalarAsync(); // Assign the generated SessionID. sessionDataRow.SessionID = sessionID; } }
/// <summary> /// Creates the specified CourseSchedule data row. /// </summary> public async Task Create(IDatabaseConnection databaseConnection, CourseScheduleDataRow courseScheduleDataRow) { // Build the SQL command. using (SqlCommand sqlCommand = new SqlCommand("INSERT INTO [CourseSchedule] VALUES (@courseScheduleCode, @sessionID, @dayOfWeek, @time); SELECT CAST(SCOPE_IDENTITY() AS INT);")) { // Use the specified database connection. SqlConnection sqlConnection = (databaseConnection as DatabaseConnection).SqlConnection; sqlCommand.Connection = sqlConnection; // Set the SQL command parameter values. this.SetSqlCommandParameterValues(sqlCommand, courseScheduleDataRow, setPrimaryKeyValue: false); // Execute the SQL command. int courseScheduleID = (int)await sqlCommand.ExecuteScalarAsync(); // Assign the generated CourseScheduleID. courseScheduleDataRow.CourseScheduleID = courseScheduleID; } }
public void EnsureRunErrorsAreReturned() { foreach (var typeOfRun in runTypes) { // Open an in-memory database. database = new SQLite(); database.OpenDatabase(":memory:", readOnly: false); // Create a simulation and add a datastore. var simulation = new Simulation() { Name = "Sim", FileName = Path.GetTempFileName(), Children = new List <Model>() { new Clock() { StartDate = new DateTime(1980, 1, 3), EndDate = new DateTime(1980, 1, 4) }, new MockSummary(), new DataStore(database), new MockModelThatThrows() } }; // Run simulations. Runner runner = new Runner(simulation, runType: typeOfRun); var exceptions = runner.Run(); // Make sure an exception is returned. Assert.IsTrue(exceptions[0].ToString().Contains("Intentional exception")); database.CloseDatabase(); } }
public IQueryResult Execute(IDatabaseConnection databaseConnection, IQuery query) { var sqlQuery = query.GetQuery(); var match = Regex.Match(sqlQuery, MATCH, RegexOptions.IgnoreCase); if (!match.Success) { return(new SqlQueryResult(0, false, string.Format("Invalid query: --{0}--", sqlQuery), null)); } var databaseName = match.Groups["databaseName"].Value; var newDatabaseName = match.Groups["newDatabaseName"].Value; var databaseLocation = databaseConnection.GetServerLocation() + "/" + databaseName; if (!databaseConnection.GetDatabaseConfiguration().DatabaseStorageService.ExistsDatabase(databaseLocation)) { return(new SqlQueryResult(0, false, string.Format("Database does not exist: --{0}--", sqlQuery), null)); } var newDatabaseLocation = databaseConnection.GetServerLocation() + "/" + newDatabaseName; if (databaseConnection.GetDatabaseConfiguration().DatabaseStorageService.ExistsDatabase(newDatabaseLocation)) { return(new SqlQueryResult(0, false, string.Format("Database already exists: --{0}--", sqlQuery), null)); } try { databaseConnection.GetDatabaseConfiguration().DatabaseStorageService.MoveDatabase(databaseLocation, newDatabaseLocation); return(new SqlQueryResult(0, true, "Database successfully renamed", null)); } catch (Exception exception) { return(new SqlQueryResult(0, false, string.Format("An error occured: --{0}--", exception.Message), null)); } }
/// <summary> /// Deletes all rows in a given table. /// </summary> /// <param name="This">The database connection.</param> /// <typeparam name="T">The mapped type.</typeparam> public static void DeleteAllRows <T>(this IDatabaseConnection This) { var tableMapping = TableMapping.Get <T>(); This.Execute(SQLBuilder.DeleteAll(tableMapping.TableName)); }
/// <summary> /// Drops the table if it exists. Otherwise this is a no-op. /// </summary> /// <param name="This">The database connection.</param> /// <typeparam name="T">The mapped type.</typeparam> /// <seealso href="https://www.sqlite.org/lang_droptable.html"/> public static void DropTableIfExists <T>(this IDatabaseConnection This) { var tableMapping = TableMapping.Get <T>(); This.Execute(SQLBuilder.DropTableIfExists(tableMapping.TableName)); }
protected DapperRepoBase(IDatabaseConnectionFactory connectionFactory) { DatabaseConnection = connectionFactory.GetDatabaseConnection(Database.Main); }
public PlayerBankAccountRepository(IDatabaseConnection databaseConnectionFactory) => _databaseConnectionFactory = databaseConnectionFactory;
public AcessoOpcaoMenuRepository(IDatabaseConnection connection) : base(connection) { }
public IStatement PrepareStatement(IDatabaseConnection connection, string sql) => connection.PrepareStatement(sql);
public TemeDao() { connection = DataBaseConnection.getInstance(); builder = new TemeBuilder(); }
public DatabaseLogger(IDatabaseConnection databaseConnection) { DatabaseConnection = databaseConnection; }
public DatabaseQueryContext(IDatabaseConnection connection) { this.connection = connection; }
public MainContentRepository(IDatabaseConnection databaseConnection) { this.databaseConnection = databaseConnection; }
public BetRepoService(IDatabaseConnectionFactory databaseConnectionFactory, IBetQueries betQueries) { _betQueries = betQueries; _databaseConnection = databaseConnectionFactory.GetDatabaseConnection(Database.Main); }
public DataStoreVersionRepositoryBuilder() { this.versions = new List <DataStoreVersionEntity>(); this.connection = new ConnectionBuilder().Build(); }
public DataStoreVersionRepositoryBuilder WithConnection(IDatabaseConnection connection) => this.With(ref this.connection, connection);
public IStatement PrepareStatementSafe(IDatabaseConnection connection, string sql) { return(connection.PrepareStatement(sql)); }
public DataProvider(IDatabaseConnection db) { _db = db; ImportXML(db); LoadAllProjects(db); }
public List <IStatement> PrepareAllSafe(IDatabaseConnection connection, IEnumerable <string> sql) { return(sql.Select(connection.PrepareStatement).ToList()); }
protected void DatabaseConnectionAsync() { _mongoDatabaseConnection = new DatabaseConnection(_mongoServerConnection, MONGO_DATABASE_1_NAME); _mongoDatabaseConnection.ConnectAsyncDelegate(_mongoDatabaseConnection_Connected); _databaseConnectionAutoResetEvent.WaitOne(); }
public bool CanAddCustomClient(IDatabaseConnection cnn) => cnn.ExecuteScalar(SQLCountCodeClientNotUsedForOneObject, new { ObjectId }) > 0;
public IEnumerable <IStatement> PrepareAll(IDatabaseConnection connection, IEnumerable <string> sql) => sql.Select(connection.PrepareStatement);
/// <summary>Create a table</summary> /// <param name="database">The db to create the table in.</param> /// <param name="tableName">The name of the table to create.</param> /// <param name="columnNames">The column names.</param> /// <param name="columnTypes">The column types.</param> /// <param name="rowValues">The row values to insert into the table.</param> private void CreateTable(IDatabaseConnection database, string tableName, List <string> columnNames, List <string> columnTypes, List <object[]> rowValues) { database.CreateTable(tableName, columnNames, columnTypes); database.InsertRows(tableName, columnNames, rowValues); }
public List <IStatement> PrepareAll(IDatabaseConnection connection, IEnumerable <string> sql) { return(PrepareAllSafe(connection, sql)); }
public UserRepository(IDatabaseConnection databaseConnection) { _databaseConnection = databaseConnection; }
public IQueryResult Execute(IDatabaseConnection databaseConnection, IQuery query) { var sqlQuery = query.GetQuery(); var match = Regex.Match(sqlQuery, MATCH, RegexOptions.IgnoreCase); if (!match.Success) { return(new SqlQueryResult(0, false, string.Format("Invalid query: --{0}--", sqlQuery), null)); } var tableName = match.Groups["tableName"].Value; var tableLocation = databaseConnection.GetServerLocation() + "/" + databaseConnection.GetDatabaseName() + "/" + tableName; if (!databaseConnection.GetDatabaseConfiguration().DatabaseStorageService.ExistsTable(tableLocation)) { return(new SqlQueryResult(0, false, string.Format("Table does not exist: --{0}--", sqlQuery), null)); } var columns = match.Groups["columns"].Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (!columns.Any()) { return(new SqlQueryResult(0, false, string.Format("Invalid columns: --{0}--", sqlQuery), null)); } var tableData = databaseConnection.GetDatabaseConfiguration().DatabaseStorageService.ReadAllLines(tableLocation); var orderedTableColumns = tableData.FirstOrDefault().Split(',').ToList(); var tableColumns = orderedTableColumns.ToDictionary(k => k.Split(':')[0], v => v.Split(':')[1]); if (columns.Count == 1 && columns[0].Equals("*")) { columns = tableColumns.Keys.ToList(); } foreach (var columnName in columns) { if (!tableColumns.ContainsKey(columnName)) { return(new SqlQueryResult(0, false, string.Format("Column does not exist: --{0}--", columnName), null)); } } var whereClause = new WhereClause(databaseConnection.GetDatabaseConfiguration()); if (match.Groups["whereClause"].Success) { var whereExpression = match.Groups["whereClause"].Success ? match.Groups["whereExpression"].Value : string.Empty; whereClause.Build(whereExpression, tableColumns); } var result = new List <Dictionary <string, object> >(); for (var i = 1; i < tableData.Length; i++) { var row = tableData[i]; var rowData = GetRowData(databaseConnection.GetDatabaseConfiguration(), row, orderedTableColumns); if (whereClause.MatchesRow(rowData)) { var record = new Dictionary <string, object>(); foreach (var column in columns) { record[column] = rowData[column]; } result.Add(record); } } return(new SqlQueryResult(0, true, "Query successfully executed", result)); }
public ClassDao() { connection = DataBaseConnection.getInstance(); }
public UsersController(IDatabaseConnection conn) { this.dbConn = conn; }
public UserRepository(IDatabaseConnection connection, IUserQueryCacheService userQueryCacheService, ISimplePasswordHash simplePasswordHash) { _connection = connection; _userQueryCacheService = userQueryCacheService; _simplePasswordHash = simplePasswordHash; }
private void SaveDisplayPreferences(DisplayPreferences displayPreferences, Guid userId, string client, IDatabaseConnection connection) { var serialized = _jsonSerializer.SerializeToBytes(displayPreferences); using (var statement = connection.PrepareStatement("replace into userdisplaypreferences (id, userid, client, data) values (@id, @userId, @client, @data)")) { statement.TryBind("@id", displayPreferences.Id.ToGuidBlob()); statement.TryBind("@userId", userId.ToGuidBlob()); statement.TryBind("@client", client); statement.TryBind("@data", serialized); statement.MoveNext(); } }
/// <summary> /// Returns a new empty lookup-list /// </summary> /// <param name="connection">A parameter preserved for polymorphism. /// This can be set to null.</param> /// <returns>Returns an empty lookup-list</returns> public Dictionary <string, string> GetLookupList(IDatabaseConnection connection) { return(new Dictionary <string, string>()); }