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;
        }
示例#2
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;
        }
		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();
				}
			}
		}
        /// <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 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 OneLineCommentOnLastLineTest()
		{
			const string script =
@"select * from foo
-- comment";
			FbScript isql = new FbScript(script);
			Assert.DoesNotThrow(() => isql.Parse());
		}
		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 void IsqlScriptTest()
		{
			string fileName = ConfigurationManager.AppSettings["IsqlScript"];
			if (System.IO.File.Exists(fileName))
			{
				FbScript isql = new FbScript(fileName);
				foreach (string command in isql.Results)
				{
					Console.WriteLine(command);
				}
			}
		}
		public void IsqlScriptTest()
		{
			string fileName = TestsSetup.IsqlScript;
			if (System.IO.File.Exists(fileName))
			{
				FbScript isql = new FbScript(fileName);
				foreach (string command in isql.Results)
				{
					Console.WriteLine(command);
				}
			}
		}
        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.");
        }
示例#14
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();
         }
     }
 }
示例#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();
			}
		}
示例#17
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;
                }
            }
        }
		public FbBatchExecution(FbConnection sqlConnection, FbScript isqlScript)
			: this(sqlConnection)
		{
			AppendSqlStatements(isqlScript);
		}
		/// <summary>
		/// Appends SQL statements from <see cref="FbScript"/> instance. <see cref="FbScript.Parse"/> should be already called.
		/// </summary>
		/// <param name="isqlScript">A <see cref="FbScript"/> object.</param>
		public void AppendSqlStatements(FbScript isqlScript)
		{
			_sqlStatements.AddRange(isqlScript.Results);
		}
示例#20
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 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());
		}
示例#22
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;
            }
        }
		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 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);
		}
		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);
		}
		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);
		}
		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();	
		}
示例#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 FbBatchExecution(FbConnection sqlConnection, FbScript isqlScript)
     : this(sqlConnection)
 {
     AppendSqlStatements(isqlScript);
 }
 /// <summary>
 /// Appends SQL statements from <see cref="FbScript"/> instance. <see cref="FbScript.Parse"/> should be already called.
 /// </summary>
 /// <param name="isqlScript">A <see cref="FbScript"/> object.</param>
 public void AppendSqlStatements(FbScript isqlScript)
 {
     _statements.AddRange(isqlScript.Results);
 }
        /// <summary>
        /// Initializes a new instance of the <b>FbBatchExecution</b> class with the given
        /// <see cref="FbConnection" /> and <see cref="FbScript"/> instances.
        /// </summary>
        /// <param name="sqlConnection">A <see cref="FbConnection"/> object.</param>
        /// <param name="isqlScript">A <see cref="FbScript"/> object.</param>
        public FbBatchExecution(FbConnection sqlConnection, FbScript isqlScript)
        {
            if (sqlConnection == null)
            {
                this.sqlConnection = new FbConnection(); // do	not	specify	the	connection string
                this.connectionString = new FbConnectionStringBuilder();
            }
            else
            {
                this.sqlConnection = sqlConnection;
                this.connectionString = new FbConnectionStringBuilder(sqlConnection.ConnectionString);
            }

            if (isqlScript != null)
            {
                foreach (string sql in isqlScript.Results)
                {
                    this.SqlStatements.Add(sql);
                }
            }
        }
示例#32
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;
        }