private void CreateTable ()
		{
			VirtuosoCommand cmd = new VirtuosoCommand ();
			cmd.Connection = connection;

			try
			{
				cmd.CommandText = "drop table foo";
				cmd.ExecuteNonQuery ();
			}
			catch (Exception)
			{
			}

			cmd.CommandText = "create table foo (id int primary key, c long varchar, nc long nvarchar, b long varbinary)";
			cmd.ExecuteNonQuery ();
			cmd.Dispose ();

			checkTable = new DataTable ();
			checkTable.Columns.Add ("id", typeof (int));
			checkTable.Columns.Add ("c", typeof (string));
			checkTable.Columns.Add ("nc", typeof (string));
			checkTable.Columns.Add ("b", typeof (byte[]) );
		}
		private void DoGetDataTest (TestCaseResult result, string text, int column,
			CommandBehavior behavior, Selector selector, Sequence sequence)
		{
			VirtuosoCommand cmd = null;
			VirtuosoDataReader dr = null;
			try
			{
				cmd = new VirtuosoCommand (text, connection);
				dr = cmd.ExecuteReader (behavior);
				CheckGetData (result, dr, column, selector, sequence);
			}
			finally
			{
				if (dr != null)
					dr.Close ();
				if (cmd != null)
					cmd.Dispose ();
			}
		}
        /// <summary>
        /// Executes a Query SQL Command against the database and returns the results in a streaming fashion
        /// </summary>
        /// <param name="sqlCmd">SQL Command</param>
        public override System.Data.Common.DbDataReader ExecuteStreamingQuery(string sqlCmd)
        {
            //Get Thread ID
            int thread = Thread.CurrentThread.ManagedThreadId;

            //Create the SQL Command
            VirtuosoCommand cmd = new VirtuosoCommand(sqlCmd, this._dbConnections[thread]);
            if (this._dbTrans[thread] != null)
            {
                //Add to the Transaction if required
                cmd.Transaction = this._dbTrans[thread];
            }

            //Return the Data Reader
            return cmd.ExecuteReader();
        }
        /// <summary>
        /// Executes a Query SQL Command against the database and returns the scalar result (first column of first row of the result)
        /// </summary>
        /// <param name="sqlCmd">SQL Command</param>
        /// <returns>First Column of First Row of the Results</returns>
        public override object ExecuteScalar(string sqlCmd)
        {
            //Get Thread ID
            int thread = Thread.CurrentThread.ManagedThreadId;

            //Create the SQL Command
            VirtuosoCommand cmd = new VirtuosoCommand(sqlCmd, this._dbConnections[thread]);
            if (this._dbTrans[thread] != null)
            {
                //Add to the Transaction if required
                cmd.Transaction = this._dbTrans[thread];
            }

            //Execute the Scalar
            return cmd.ExecuteScalar();
        }
        /// <summary>
        /// Executes a Query SQL Command against the database and returns a DataTable
        /// </summary>
        /// <param name="sqlCmd">SQL Command</param>
        /// <returns>DataTable of results</returns>
        public override DataTable ExecuteQuery(string sqlCmd)
        {
            //Get Thread ID
            int thread = Thread.CurrentThread.ManagedThreadId;

            //Create the SQL Command
            VirtuosoCommand cmd = new VirtuosoCommand(sqlCmd, this._dbConnections[thread]);
            if (this._dbTrans[thread] != null)
            {
                //Add to the Transaction if required
                cmd.Transaction = this._dbTrans[thread];
            }

            //Execute the Query
            VirtuosoDataAdapter adapter = new VirtuosoDataAdapter(cmd);
            DataTable results = new DataTable();
            adapter.Fill(results);

            return results;
        }
        /// <summary>
        /// Executes a Query SQL Command against the database and fills the supplied DataTable with the results
        /// </summary>
        /// <param name="sqlCmd">SQL Command</param>
        /// <param name="data">DataTable to fill with results</param>
        /// <remarks>Allows for queries which wish to strongly type the results for quicker reading</remarks>
        protected override void ExecuteQuery(string sqlCmd, DataTable data)
        {
            //Get Thread ID
            int thread = Thread.CurrentThread.ManagedThreadId;

            //Create the SQL Command
            VirtuosoCommand cmd = new VirtuosoCommand(sqlCmd, this._dbConnections[thread]);
            if (this._dbTrans[thread] != null)
            {
                //Add to the Transaction if required
                cmd.Transaction = this._dbTrans[thread];
            }

            //Execute the Query
            VirtuosoDataAdapter adapter = new VirtuosoDataAdapter(cmd);
            adapter.Fill(data);
        }
        /// <summary>
        /// Updates a Graph in the Quad Store
        /// </summary>
        /// <param name="graphUri">Graph Uri of the Graph to update</param>
        /// <param name="additions">Triples to be added</param>
        /// <param name="removals">Triples to be removed</param>
        public void UpdateGraph(Uri graphUri, IEnumerable<Triple> additions, IEnumerable<Triple> removals)
        {
            try
            {
                this.Open(true);
                int r;

                //Build the Delete Data Command
                if (removals != null)
                {
                    if (removals.Any())
                    {
                        VirtuosoCommand deleteCmd = new VirtuosoCommand();
                        StringBuilder delete = new StringBuilder();
                        delete.AppendLine("SPARQL define output:format '_JAVA_' DELETE DATA");
                        if (graphUri != null)
                        {
                            delete.AppendLine(" FROM <" + graphUri.ToString() + ">");
                        }
                        else
                        {
                            throw new RdfStorageException("Cannot update an unnamed Graph in a Virtuoso Store using this method - you must specify the URI of a Graph to Update");
                        }
                        delete.AppendLine("{");
                        foreach (Triple t in removals)
                        {
                            delete.AppendLine(t.ToString(this._formatter));
                        }
                        delete.AppendLine("}");
                        deleteCmd.CommandText = delete.ToString();
                        deleteCmd.Connection = this._db;
                        deleteCmd.Transaction = this._dbtrans;

                        r = deleteCmd.ExecuteNonQuery();
                        if (r < 0) throw new RdfStorageException("Virtuoso encountered an error when deleting Triples");
                    }
                }

                //Build the Insert Data Command
                if (additions != null)
                {
                    if (additions.Any())
                    {
                        VirtuosoCommand insertCmd = new VirtuosoCommand();
                        StringBuilder insert = new StringBuilder();
                        insert.AppendLine("SPARQL define output:format '_JAVA_' INSERT DATA");
                        if (graphUri != null)
                        {
                            insert.AppendLine(" INTO <" + graphUri.ToString() + ">");
                        }
                        else
                        {
                            throw new RdfStorageException("Cannot update an unnamed Graph in a Virtuoso Store using this method - you must specify the URI of a Graph to Update");
                        }
                        insert.AppendLine("{");
                        foreach (Triple t in additions)
                        {
                            insert.AppendLine(t.ToString(this._formatter));
                        }
                        insert.AppendLine("}");
                        insertCmd.CommandText = insert.ToString();
                        insertCmd.Connection = this._db;
                        insertCmd.Transaction = this._dbtrans;

                        r = insertCmd.ExecuteNonQuery();
                        if (r < 0) throw new RdfStorageException("Virtuoso encountered an error when inserting Triples");
                    }
                }

                this.Close(true, false);
            }
            catch
            {
                this.Close(true, true);
                throw;
            }
        }
			internal Sleeper (string name, VirtuosoCommand command, int delay, int timeout)
			{
				this.name = name;
				this.command = command;
				this.delay = delay;
				this.timeout = timeout;
			}
        /// <summary>
        /// Executes a Query SQL Command against the database and returns the scalar result (first column of first row of the result)
        /// </summary>
        /// <param name="sqlCmd">SQL Command</param>
        /// <returns>First Column of First Row of the Results</returns>
        public object ExecuteScalar(string sqlCmd)
        {
            //Create the SQL Command
            VirtuosoCommand cmd = new VirtuosoCommand(sqlCmd, this._db);
            if (this._dbtrans != null)
            {
                //Add to the Transaction if required
                cmd.Transaction = this._dbtrans;
            }

            //Execute the Scalar
            return cmd.ExecuteScalar();
        }
        /// <summary>
        /// Saves a Graph into the Quad Store (Warning: Completely replaces any existing Graph with the same URI)
        /// </summary>
        /// <param name="g">Graph to save</param>
        /// <remarks>
        /// Completely replaces any previously saved Graph with the same Graph URI
        /// </remarks>
        public void SaveGraph(IGraph g)
        {
            if (g.BaseUri == null) throw new RdfStorageException("Cannot save a Graph without a Base URI to Virtuoso");

            try
            {
                this.Open(false);

                //Delete the existing Graph (if it exists)
                this.ExecuteNonQuery("DELETE FROM DB.DBA.RDF_QUAD WHERE G = DB.DBA.RDF_MAKE_IID_OF_QNAME('" + g.BaseUri.ToString() + "')");

                //Make a call to the TTLP() Virtuoso function
                VirtuosoCommand cmd = new VirtuosoCommand();
                cmd.CommandText = "DB.DBA.TTLP(@data, @base, @graph, 1)";
                 cmd.Parameters.Add("data", VirtDbType.VarChar);
                cmd.Parameters["data"].Value = VDS.RDF.Writing.StringWriter.Write(g, new NTriplesWriter());
                String baseUri = g.BaseUri.ToSafeString();
                cmd.Parameters.Add("base", VirtDbType.VarChar);
                cmd.Parameters.Add("graph", VirtDbType.VarChar);
                cmd.Parameters["base"].Value = baseUri;
                cmd.Parameters["graph"].Value = baseUri;
                cmd.Connection = this._db;
                int result = cmd.ExecuteNonQuery();

                this.Close(false);
            }
            catch
            {
                this.Close(true);
                throw;
            }
        }
        /// <summary>
        /// Executes a Query SQL Command against the database and returns a DataTable
        /// </summary>
        /// <param name="sqlCmd">SQL Command</param>
        /// <returns>DataTable of results</returns>
        public DataTable ExecuteQuery(string sqlCmd)
        {
            //Create the SQL Command
            VirtuosoCommand cmd = new VirtuosoCommand(sqlCmd, this._db);
            if (this._dbtrans != null)
            {
                //Add to the Transaction if required
                cmd.Transaction = this._dbtrans;
            }

            //Execute the Query
            VirtuosoDataAdapter adapter = new VirtuosoDataAdapter(cmd);
            DataTable results = new DataTable();
            adapter.Fill(results);

            return results;
        }
        /// <summary>
        /// Executes a Non-Query SQL Command against the database
        /// </summary>
        /// <param name="sqlCmd">SQL Command</param>
        public void ExecuteNonQuery(string sqlCmd)
        {
            //Create the SQL Command
            VirtuosoCommand cmd = new VirtuosoCommand(sqlCmd, this._db);
            if (this._dbtrans != null)
            {
                //Add to the Transaction if required
                cmd.Transaction = this._dbtrans;
            }

            //Execute
            cmd.ExecuteNonQuery();
        }
        // Используется для организации запросов внутри транзакции
        private IEnumerable<object[]> RunQuery(string sql, VirtuosoCommand runcommand)
        {
            runcommand.CommandText = sql;
            var reader = runcommand.ExecuteReader();

            int ncols = reader.FieldCount;
            object[] data = new object[ncols];
            while (reader.Read())
            {
                reader.GetValues(data);
                yield return data;
            }
            reader.Close();
        }
 // Возвращает како-нибудь тип, приписанных сущности или null
 private string RunGetType(string id, VirtuosoCommand runcommand)
 {
     string t = null;
     var qu = RunQuery("SPARQL SELECT ?o FROM <" + graph + "> {<" + id + "> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?o}", runcommand);
     foreach (var row in qu)
     {
         t = row[0].ToString();
         //break;
     }
     return t;
 }
 public void RunStop(VirtuosoCommand runcommand)
 {
     runcommand.Transaction.Commit();
     connection.Close();
 }