public override IDatabase Execute()
        {
            var db = Database;
            FbScript script;

            using (var s = GetType().Assembly.GetManifestResourceStream(ScriptResourceName))
            {
                using (var r = new StreamReader(s, Encoding.UTF8))
                {
                    script = new FbScript(r.ReadToEnd());
                    script.Parse();
                }
            }

            try
            {
                using (var con = new FbConnection(db.ConnectionString))
                {
                    con.Open();
                }
            }
            catch
            {
                FbConnection.CreateDatabase(db.ConnectionString);
            }

            using (var con = new FbConnection(db.ConnectionString))
            {
                var be = new FbBatchExecution(con);
                be.AppendSqlStatements(script);
                be.Execute();
            }

            return db;
        }
		public override void PrepareDb()
		{
			// clean
			if(File.Exists(PathToDb))
			{
				File.Delete(PathToDb);
			}
			// create db
			FbConnection.CreateDatabase(pConnectionString);
			// create tables
			string script;
			using(StreamReader reader = new StreamReader(PathToSchema))
			{
				script = reader.ReadToEnd();
			}
			FbScript sqls = new FbScript(script);
			if(sqls.Parse() <= 0)
			{
				throw new DbException("No DB schema found.");
			}
			using(FbConnection connection = new FbConnection(pConnectionString))
			{
				connection.Open();
				foreach(FbCommand create in sqls.Results.Select(sql => new FbCommand(sql, connection)))
				{
					create.ExecuteNonQuery();
				}
			}
		}
示例#3
0
        public static bool ExecuteBatchScript(
            string connectionString,
            string pathToScriptFile)
        {
            FbScript script = new FbScript(pathToScriptFile);
            if (script.Parse() > 0)
            {
                using (FbConnection connection = new FbConnection(connectionString))
                {
                    connection.Open();
                    try
                    {
                        FbBatchExecution batch = new FbBatchExecution(connection, script);
                        batch.Execute(true);

                    }
                    catch (FbException ex)
                    {
                        log.Error(ex);
                        throw new Exception(pathToScriptFile, ex);
                    }
                    finally
                    {
                        connection.Close();
                    }

                }

            }

            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pathScript"></param>
        private void CreateEmbeddedDb(string pathScript)
        {
            FbConnectionStringBuilder csb = new FbConnectionStringBuilder();
            csb.Charset = "UTF8";
            csb.ServerType = FbServerType.Embedded;
            csb.Database = databaseName;
            csb.UserID = "SYSDBA";
            csb.Password = "******";

            try {
                if (!File.Exists(databaseName)) {

                    OpenFileDialog filedialog = new OpenFileDialog();
                    DialogResult res = filedialog.ShowDialog();
                    filedialog.Title = "Wybierz skrypt sql do utworzenia bazy";
                    FbConnection.CreateDatabase(csb.ToString());
                    // parse the SQL script
                    FbScript script = new FbScript(filedialog.FileName);
                    script.Parse();

                    // execute the SQL script
                    using (FbConnection c = new FbConnection(csb.ToString())) {
                        FbBatchExecution fbe = new FbBatchExecution(c);
                        foreach (string cmd in script.Results) {
                            fbe.SqlStatements.Add(cmd);
                        }
                        fbe.Execute();
                    }
                }

            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message, "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
		public void OneLineCommentOnLastLineTest()
		{
			const string script =
@"select * from foo
-- comment";
			FbScript isql = new FbScript(script);
			Assert.DoesNotThrow(() => isql.Parse());
		}
		public void TwoStatements()
		{
			const string text =
@"select * from foo;select * from bar";
			FbScript script = new FbScript(text);
			script.Parse();
			Assert.AreEqual(2, script.Results.Count());
		}
		public void SimpleStatementNoSemicolonWithEscapedSingleQuoteInLiteral()
		{
			const string text =
@"select * from foo where x = 'foo''bar'";
			FbScript script = new FbScript(text);
			script.Parse();
			Assert.AreEqual(1, script.Results.Count());
			Assert.AreEqual(text, script.Results[0].Text);
		}
		public void SimpleStatementWithSemicolonWithLiteral()
		{
			const string text =
@"select * from foo where x = 'foobar';";
			FbScript script = new FbScript(text);
			script.Parse();
			Assert.AreEqual(1, script.Results.Count());
			Assert.AreEqual(text.Substring(0, text.Length - 1), script.Results[0].Text);
		}
 private static void ExecuteDbCreationScript()
 {
     using (var connection = new FbConnection(GetConnectionString()))
     {
         var batchExecution = new FbBatchExecution(connection);
         var script = new FbScript(DbCreationScript ?? Resources.create_db);
         script.Parse();
         batchExecution.AppendSqlStatements(script);
         batchExecution.Execute();
     }
 }
        public static void CleanTables(FbConnection connection)
        {
            if (connection == null) throw new ArgumentNullException("connection");

            var script = GetStringResource(
                typeof(FirebirdTestObjectsInitializer).Assembly,
                "Hangfire.Firebird.Tests.Clean.sql");

            FbScript fbScript = new FbScript(script);
            fbScript.Parse();

            FbBatchExecution fbBatch = new FbBatchExecution(connection, fbScript);
            fbBatch.Execute(true);
        }
        public static void Install(FbConnection connection)
        {
            if (connection == null) throw new ArgumentNullException("connection");

            Log.Info("Start installing Hangfire SQL objects...");

            int version = 1;
            bool scriptFound = true;

            do
            {
                try
                {
                    var script = GetStringResource(
                        typeof(FirebirdObjectsInstaller).Assembly,
                        string.Format("Hangfire.Firebird.Install.v{0}.sql",
                            version.ToString(CultureInfo.InvariantCulture)));

                    if (!VersionAlreadyApplied(connection, version))
                    {
                        FbScript fbScript = new FbScript(script);
                        fbScript.Parse();

                        FbBatchExecution fbBatch = new FbBatchExecution(connection, fbScript);
                        fbBatch.Execute(true);

                        UpdateVersion(connection, version);
                    }
                }
                catch (FbException)
                {
                    throw;
                }
                catch (Exception)
                {
                    scriptFound = false;
                }

                version++;
            } while (scriptFound);

            Log.Info("Hangfire SQL objects installed.");
        }
示例#12
0
        private void ExecuteScript(FbConnection myConnection, string scriptPath)
        {
            try
            {
                using (FbTransaction myTransaction = myConnection.BeginTransaction())
                {
                    if (!File.Exists(scriptPath))
                        throw new FileNotFoundException("Script not found", scriptPath);

                    string script = File.ReadAllText(scriptPath);

                    // use FbScript to parse all statements
                    FbScript fbs = new FbScript(script);
                    fbs.Parse();

                    // execute all statements
                    FbBatchExecution fbe = new FbBatchExecution(myConnection, fbs);
                    fbe.CommandExecuting += (sender, args) => args.SqlCommand.Transaction = myTransaction;
                    fbe.Execute(true);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                throw;
            }
        }
示例#13
0
 void CreateDb(string ConnStr, string ScriptPath)
 {
     var assembly = Assembly.GetExecutingAssembly();
     var stream = assembly.GetManifestResourceStream(typeof(FbDatabase).Namespace + ".struct.sql");
     string script = new StreamReader(stream, System.Text.Encoding.ASCII).ReadToEnd();
     FbScript fbs = new FbScript(script);
     fbs.Parse();
     FbConnection.CreateDatabase(_conw.ConnectionString);
     using (var c = new FbConnection(ConnStr))
     {
         c.Open();
         try
         {
             using (FbTransaction myTransaction = c.BeginTransaction())
             {
                 FbBatchExecution fbe = new FbBatchExecution(c, fbs);
                 fbe.CommandExecuting += (sender, args) => args.SqlCommand.Transaction = myTransaction;
                 fbe.Execute(true);
             }
         }
         finally
         {
             c.Close();
         }
     }
 }
        /// <summary>
        /// ExecuteScript
        /// </summary>
        private void ExecuteScript(TextReader textReader)
        {
            try
            {
                FbScript fbScript = new FbScript(textReader);
                fbScript.Parse();

                FbBatchExecution fbBatchExection = new FbBatchExecution(this.Connection);
                foreach (string cmd in fbScript.Results)
                {
                    fbBatchExection.SqlStatements.Add(cmd);
                }
                fbBatchExection.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
示例#15
0
        public override void RecreateDataBase()
        {
            // ConnectionString Builder
            FbConnectionStringBuilder csb = new FbConnectionStringBuilder();
            csb.DataSource = "localhost";
            csb.Dialect = 3;
            csb.Charset = "UTF8";
            csb.Pooling = false;
            csb.UserID = "SYSDBA"; // default user
            csb.Password = "******"; // default password

            string serverConnectionString = csb.ToString();
            csb.Database = csb.Database = FQDBFile;

            string databaseConnectionString = csb.ToString();

            Console.WriteLine("-------------------------");
            Console.WriteLine("Using Firebird Database  ");
            Console.WriteLine("-------------------------");

            base.RecreateDataBase();

            // Create simple user
            FbSecurity security = new FbSecurity();
            security.ConnectionString = serverConnectionString;
            var userData = security.DisplayUser(FbUserName);
            if (userData == null)
            {
                userData = new FbUserData();
                userData.UserName = FbUserName;
                userData.UserPassword = FbUserPass;
                security.AddUser(userData);
            }

            // Try to shutdown & delete database
            if (File.Exists(FQDBFile))
            {
                FbConfiguration configuration = new FbConfiguration();
                configuration.ConnectionString = databaseConnectionString;
                try
                {
                    configuration.DatabaseShutdown(FbShutdownMode.Forced, 0);
                    Thread.Sleep(1000);
                }
                finally
                {
                    File.Delete(FQDBFile);
                }
            }

            // Create the new DB
            FbConnection.CreateDatabase(databaseConnectionString, 4096, true, true);
            if (!File.Exists(FQDBFile)) throw new Exception("Database failed to create");

            // Create the Schema
            string script = @"
CREATE TABLE Users(
    UserId integer PRIMARY KEY NOT NULL, 
    Name varchar(200), 
    Age integer, 
    DateOfBirth timestamp, 
    Savings decimal(10,5),
    Is_Male smallint,
    UniqueId char(38),
    TimeSpan time,
    TestEnum varchar(10),
    HouseId integer,
    SupervisorId integer
                );
          
CREATE TABLE ExtraUserInfos(
    ExtraUserInfoId integer PRIMARY KEY NOT NULL, 
    UserId integer NOT NULL, 
    Email varchar(200), 
    Children integer 
);

CREATE TABLE Houses(
    HouseId integer PRIMARY KEY NOT NULL, 
    Address varchar(200)
);

CREATE TABLE CompositeObjects(
    Key1ID integer PRIMARY KEY NOT NULL, 
    Key2ID integer NOT NULL, 
    Key3ID integer NOT NULL, 
    TextData varchar(512), 
    DateEntered timestamp NOT NULL,
    DateUpdated timestamp  
);

CREATE GENERATOR USERS_USERID_GEN;
CREATE GENERATOR EXTRAUSERINFOS_ID_GEN;
CREATE GENERATOR HOUSES_HOUSEID_GEN;

SET TERM ^ ;

CREATE TRIGGER BI_USERS_USERID FOR USERS
ACTIVE BEFORE INSERT
POSITION 0
AS
BEGIN
  IF (NEW.USERID IS NULL) THEN
      NEW.USERID = GEN_ID(USERS_USERID_GEN, 1);
END^


CREATE TRIGGER BI_EXTRAUSERINFOS_ID1 FOR EXTRAUSERINFOS
ACTIVE BEFORE INSERT
POSITION 0
AS
BEGIN
  IF (NEW.EXTRAUSERINFOID IS NULL) THEN
      NEW.EXTRAUSERINFOID = GEN_ID(EXTRAUSERINFOS_ID_GEN, 1);
END^

CREATE TRIGGER BI_HOUSES_HOUSEID FOR HOUSES
ACTIVE BEFORE INSERT
POSITION 0
AS
BEGIN
  IF (NEW.HOUSEID IS NULL) THEN
      NEW.HOUSEID = GEN_ID(HOUSES_HOUSEID_GEN, 1);
END^

SET TERM ; ^

CREATE ROLE %role%;

GRANT SELECT, UPDATE, INSERT, DELETE ON Users TO ROLE %role%;
GRANT SELECT, UPDATE, INSERT, DELETE ON ExtraUserInfos TO ROLE %role%;
GRANT SELECT, UPDATE, INSERT, DELETE ON Houses TO ROLE %role%;
GRANT SELECT, UPDATE, INSERT, DELETE ON CompositeObjects TO ROLE %role%;

GRANT %role% TO %user%;
".Replace("%role%", FbRole).Replace("%user%", FbUserName);

/* 
 * Using new connection so that when a transaction is bound to Connection if it rolls back 
 * it doesn't blow away the tables
 */

            using (var conn = new FbConnection(databaseConnectionString))
            {
                FbScript fbScript = new FbScript(script);
                fbScript.Parse();
                FbBatchExecution fbBatch = new FbBatchExecution(conn, fbScript);
                fbBatch.Execute(true);

                conn.Open();
                Console.WriteLine("Tables (CreateDB): " + Environment.NewLine);
                var dt = conn.GetSchema("Tables", new[] {null, null, null, "TABLE"});
                foreach (DataRow row in dt.Rows)
                {
                    Console.WriteLine(row[2]);
                }

                conn.Close();
            }
        }
		protected override void DbCreateDatabase(DbConnection connection, int? commandTimeout,
#pragma warning disable 3001
			StoreItemCollection storeItemCollection)
#pragma warning restore 3001
		{
			FbConnection.CreateDatabase(connection.ConnectionString, 16384, true, false);
			string script = DbCreateDatabaseScript(GetDbProviderManifestToken(connection), storeItemCollection);
			FbScript fbScript = new FbScript(script);
			fbScript.Parse();
			using (var fbConnection = new FbConnection(connection.ConnectionString))
			{
				var execution = new FbBatchExecution(fbConnection);
				execution.AppendSqlStatements(fbScript);
				execution.Execute();
			}
		}
		public void ManuallySettingStatementType()
		{
			const string text =
@"create db 'foobar'";
			FbScript script = new FbScript(text);
			script.UnknownStatement += (sender, e) =>
			{
				if (e.Statement.Text == text)
				{
					e.NewStatementType = SqlStatementType.CreateDatabase;
					e.Handled = true;
				}
			};
			script.Parse();
			Assert.AreEqual(1, script.Results.Count());
			Assert.AreEqual(SqlStatementType.CreateDatabase, script.Results[0].StatementType);
		}
示例#18
0
        private bool DoDirtyWork(string db, StreamReader sr)
        {
            FbScript script = new FbScript(sr);
            script.Parse();
            FbConnectionStringBuilder fbcs = new FbConnectionStringBuilder(db);
            fbcs.Dialect = 1;
            // execute the SQL script
            using (FbConnection c = new FbConnection(fbcs.ConnectionString))
            {
                c.Open();
                FbBatchExecution fbe = new FbBatchExecution(c);
                fbe.CommandExecuted += new CommandExecutedEventHandler(fbe_CommandExecuted);
                foreach (string cmd in script.Results)
                {
                    if (!cmd.Contains("commit work"))
                        fbe.SqlStatements.Add(cmd);
                }
                try
                {
                    fbe.Execute();
                }
                catch (Exception ex)
                {
                    PutLog(string.Format("Work Error: {0}", ex.Message));
                    ThreadExceptionHandler.SendErrorMessage(string.Format("Work Error: {0}", ex.Message));
                    c.Close();
                    return false;
                }
                c.Close(); while (c.State != ConnectionState.Closed) ;
                FbConnection.ClearAllPools();

            }

            return true;
        }
        /// <summary>
        /// Parses SQL script using native Firebird .NET provider method
        /// </summary>
        /// <param name="sqlScript">Script to parse</param>
        /// <returns>Returns <code>List</code> of SQL commands</returns>
        private IEnumerable<string> ParseSqlScript(string sqlScript)
        {
            var retVal = new List<string>();

            using (TextReader textReader = new StringReader(sqlScript))
            {
                var script = new FbScript(textReader);
                script.Parse();
                retVal.AddRange(script.Results);
            }

            return retVal;
        }
		public void OneStatementWithMultilineCommentNoSemicolon()
		{
			const string text =
@"select * from foo /* foo */";
			FbScript script = new FbScript(text);
			script.Parse();
			Assert.AreEqual(1, script.Results.Count());
			Assert.AreEqual(text, script.Results[0].Text);
		}
		public void OneStatementWithMultilineCommentWithSemicolonWithSemicolonAtTheEnd()
		{
			const string text =
@"select * from foo /* ;foo */;";
			FbScript script = new FbScript(text);
			script.Parse();
			Assert.AreEqual(1, script.Results.Count());
			Assert.AreEqual(text.Substring(0, text.Length - 1), script.Results[0].Text);
		}
		public void SemicolonOnly()
		{
			const string text =
@";";
			FbScript script = new FbScript(text);
			script.Parse();
			Assert.AreEqual(0, script.Results.Count());
		}
		public void MultilineCommentSeparatedBySemicolon()
		{
			const string text =
@"/*
foo
*/;";
			FbScript script = new FbScript(text);
			script.UnknownStatement += (sender, e) =>
			{
				if (e.Statement.Text == text.Substring(0, text.Length - 1))
				{
					e.Ignore = true;
				}
			};
			script.Parse();
			Assert.AreEqual(0, script.Results.Count());
		}
		protected override void DbCreateDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection)
		{
			FbConnection fbConnection = CheckAndCastToFbConnection(connection);
			string script = DbCreateDatabaseScript(GetDbProviderManifestToken(fbConnection), storeItemCollection);
			FbScript fbScript = new FbScript(script);
			fbScript.Parse();
			FbConnection.CreateDatabase(fbConnection.ConnectionString);
			new FbBatchExecution(fbConnection, fbScript).Execute();	
		}
示例#25
0
        private void CreateDatabase()
        {
            // create db folder
            var dbFolderPath = Path.GetDirectoryName(this.dbPath);

            if (!Directory.Exists(dbFolderPath))
                Directory.CreateDirectory(dbFolderPath);

            if (!File.Exists(this.dbPath))
            {
                try
                {
                    var connString = @"ServerType=1; DataSource=localhost; Database={0}; Pooling=false; User=SYSDBA; Password=NA;".Format2(this.dbPath);

                    FbConnection.CreateDatabase(connString);

                    var assembly = Assembly.GetExecutingAssembly();
                    using (var conn = new FbConnection(connString))
                    using (var stream = assembly.GetManifestResourceStream("BitSharp.Storage.Firebird.Sql.CreateDatabase.sql"))
                    using (var reader = new StreamReader(stream))
                    {
                        conn.Open();

                        var script = new FbScript(reader.ReadToEnd());
                        script.Parse();

                        new FbBatchExecution(conn, script).Execute();
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Database create failed: {0}".Format2(e.Message));
                    Debugger.Break();

                    if (File.Exists(this.dbPath))
                        File.Delete(this.dbPath);

                    throw;
                }
            }
        }
示例#26
0
        private void ExecuteDDL(FbConnection db, String fbDDL)
        {
            MemoryStream memStream = new MemoryStream();
            byte[] data = Encoding.ASCII.GetBytes(fbDDL);
            memStream.Write(data, 0, data.Length);
            memStream.Position = 0;
            TextReader txtReader = new StreamReader(memStream);

            // parse the SQL script
            FbScript script = new FbScript(txtReader);
            int i = script.Parse();

            FbBatchExecution fbe = new FbBatchExecution(db);
            foreach (string cmd in script.Results)
            {
                fbe.SqlStatements.Add(cmd);
            }
            if (fbe.SqlStatements.Count > 0) fbe.Execute();
        }
		public void OneStatementWithSemicolonOneAfterSingleLineComment()
		{
			const string text =
@"select * from foo;--select * from bar";
			FbScript script = new FbScript(text);
			script.UnknownStatement += (sender, e) =>
			{
				if (e.Statement.Text == "--select * from bar")
				{
					e.Ignore = true;
				}
			};
			script.Parse();
			Assert.AreEqual(1, script.Results.Count());
			Assert.AreEqual("select * from foo", script.Results[0].Text);
		}
示例#28
0
        public static bool ExecuteBatchScript(
            string connectionString,
            string pathToScriptFile)
        {
            // http://stackoverflow.com/questions/9259034/the-type-of-the-sql-statement-could-not-be-determinated

            //FbScript script = new FbScript(pathToScriptFile);
            FbScript script;
            using (StreamReader sr = File.OpenText(pathToScriptFile))
            {
                script = new FbScript(sr.ReadToEnd());
            }

            FbBatchExecution batch;

            if (script.Parse() > 0)
            {
                using (FbConnection connection = new FbConnection(connectionString))
                {
                    connection.Open();
                    try
                    {
                        batch = new FbBatchExecution(connection, script);
                        batch.Execute(true);
                        


                    }
                    catch (FbException ex)
                    {
                   
                        //log.Error(ex);
                        throw new Exception(pathToScriptFile, ex);
                    }


                }

            }

            return true;

        }
		public void OneStatementNoSemicolonOneAfterSingleLineComment()
		{
			const string text =
@"select * from foo--;select * from bar";
			FbScript script = new FbScript(text);
			script.Parse();
			Assert.AreEqual(1, script.Results.Count());
			Assert.AreEqual(text, script.Results[0].Text);
		}