⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fastdbconnection.cs

📁 FastDb是高效的内存数据库系统
💻 CS
📖 第 1 页 / 共 2 页
字号:
    /// <param name="FieldName">Name of the field</param>    /// <param name="NewFlags">New index types.</param>    public void AlterIndex(string TableName, string FieldName, CLI.FieldFlags NewFlags) {      CLI.CliCheck(CLI.cli_alter_index(session, TableName, FieldName, NewFlags));    }    /// <summary>    /// Create a new SQL command in this connection. <seealso cref="CLI.FastDbCommand"/>    /// </summary>    /// <param name="sql">SQL text representing a command</param>    /// <returns>FastDbCommand object to be used for executing the SQL command</returns>    public FastDbCommand CreateCommand(string sql) {      lock(typeof(FastDbConnection)) {        int n = commands.Add(new FastDbCommand(this, sql));        return (FastDbCommand)commands[n];      }    }    internal void RemoveCommand(FastDbCommand command) {      lock(typeof(FastDbConnection)) {        commands.Remove(command);      }    }    /// <summary>    /// Attach current thread to the database. Each thread except one opened the database     /// should first attach to the database before any access to the database,     /// and detach after end of the work with database.    /// </summary>    public void Attach() {      CLI.CliCheck(CLI.cli_attach(session));    }    public void Detach() {       Detach(CLI.CliDetachMode.cli_commit_on_detach | CLI.CliDetachMode.cli_destroy_context_on_detach);    }    /// <summary>    /// Detach current thread from the database. Each thread except one opened the database     /// should perform attach to the database before any access to the database,     /// and detach after end of the work with database    /// <seealso cref="CLI.CliDetachMode"/>    /// </summary>    /// <param name="mode">Optional parameter indicating the detach action.</param>    public void Detach(CLI.CliDetachMode mode) {      CLI.CliCheck(CLI.cli_detach(session, mode));    }    /// <summary>    /// Extract a DDL of a table    /// </summary>    /// <param name="TableName">Name of a table</param>    /// <returns>A string representing the table's DDL.</returns>    public string ExtractTableDDL(string TableName) {      FastDbFields flds = DescribeTable(TableName);      StringBuilder result = new StringBuilder("create table "+TableName+" (\n");      int nLen = 0;      for(int i=0; i<flds.Count; i++) nLen = (nLen > flds[i].Name.Length) ? nLen : flds[i].Name.Length;      for(int i=0; i<flds.Count; i++) {        result.AppendFormat("\t{0} {1}{2}", flds[i].Name.PadRight(nLen, ' '), CLI.CliTypeToStr(flds[i].Type, true),          (flds[i].RefTable == null) ? "" : " to "+flds[i].RefTable);        result.Append((i==(flds.Count-1)) ? "" : ",\n");      }      result.Append(");\n");      string IDX_STR = "create {0} on {1}.{2};\n";      for(int i=0; i<flds.Count; i++) {        if (Enum.IsDefined(flds[i].Flags.GetType(), CLI.FieldFlags.cli_hashed))          result.AppendFormat(IDX_STR, "hash",  TableName, flds[i].Name);        if (Enum.IsDefined(flds[i].Flags.GetType(), CLI.FieldFlags.cli_indexed))          result.AppendFormat(IDX_STR, "index",  TableName, flds[i].Name);      }      return result.ToString();    }    /// <summary>    /// Extracts the metadata of the entire FastDB database, and stores it to a file    /// </summary>    /// <param name="FileName">FileName where the DDL is to be saved.</param>    public void SaveDDLtoFile(string FileName) {      System.IO.StreamWriter writer = System.IO.File.CreateText(FileName);      try {        string[] tables = ListTables();        writer.WriteLine("open '{0}';", dbName);        foreach (string table in tables)          writer.Write(ExtractTableDDL(table));        writer.WriteLine("commit;");        writer.WriteLine("exit;");      }      finally {        writer.Close();      }    }    /// <summary>    /// This method implements IDisposable.  It takes this object off     /// the Finalization queue to prevent finalization code for this     /// object from executing a second time.    /// </summary>    public void Dispose() {      Dispose(true);      GC.SuppressFinalize(this);    }    /// <summary>    /// This method executes by a user's call, or by the runtime.    /// </summary>    /// <param name="disposing">If disposing equals true, the method has been called directly    /// or indirectly by a user's code. Managed and unmanaged resources    /// can be disposed. If disposing equals false, the method has been called by the     /// runtime from inside the finalizer and you should not reference     /// other objects. Only unmanaged resources can be disposed.</param>    protected virtual void Dispose(bool disposing) {      if(this.session != -1) {   // Check to see if Dispose has already been called.        if(disposing) {} // Dispose managed resources here.        Close();         // Release unmanaged resources.       }    }    protected void CheckConnection(bool IsConnected) {      if ((IsConnected) ? session == -1 : session != -1)        throw new CliError("The session is " + ((IsConnected) ? "connected" : "not connected"));    }    private static void SessionErrorHandler(int error,       [MarshalAs(UnmanagedType.LPStr)] string msg, int msgarg, IntPtr UserData) {      //Debug.Assert(UserData != IntPtr.Zero, "UserData must be assigned FastDbSession value!");      //int handle; Marshal.Copy(UserData, handle, 0, 1);      // This procedure must raise an error to unwind the stack      throw new CliError(error-100, msg+String.Format(" ({0})", msgarg));    }    private unsafe string[] ListTables(string TableName, ref bool tableExists) {      IntPtr p = new IntPtr(0);      int rc = CLI.CliCheck(CLI.cli_show_tables(session, ref p));      ArrayList tables = new ArrayList(rc);      if (rc > 0) {        try {          CLI.CliTableDescriptor* table = (CLI.CliTableDescriptor*)p.ToPointer();          tableExists = false;          for(int i=0; i < rc; i++, table++) {            string s = Marshal.PtrToStringAnsi(table->name);            if (String.Compare(s, TableName, true) == 0) tableExists = true;            tables.Add(s);          }        }         finally {          CLI.cli_free_memory(session, p.ToPointer());        }      }      return (string[])tables.ToArray(typeof(string));    }    private void Open(bool isLocal, string Host, int Port) {      CheckConnection(false);      if (!isLocal)        session = CLI.cli_open(String.Format("{0}:{1}", Host, Port), maxConnectRetries, reconnectTimeout);      else        session = (int)CLI.ErrorCode.cli_bad_address;      if (session != (int)CLI.ErrorCode.cli_bad_address)         throw new CliError(session, "cli_open failed");      else {        if (enableReplication)           session =             CLI.CliCheck(CLI.cli_create_replication_node(            nodeID,            nodeNames.Length,            nodeNames,            dbName,            dbPath,            (int)openAttributes,            initDbSize,            extQuantum,            initIdxSize,            fileSizeLimit), "cli_create_replication_node failed");        else          session =             CLI.CliCheck(CLI.cli_create(dbName,            dbPath,            transCommitDelay,            (int)openAttributes,            initDbSize,            extQuantum,            initIdxSize,            fileSizeLimit), "cli_create failed");      }      sessionThreadID = System.Threading.Thread.CurrentThread.GetHashCode();      IntPtr dummy    = IntPtr.Zero;      CLI.cli_set_error_handler(session, new CLI.CliErrorHandler(SessionErrorHandler), dummy);    }    private string    dbName;    private string    dbPath;    private int       session            = -1;    private int       initDbSize         = DefaultInitDatabaseSize;    private int       initIdxSize        = DefaultInitIndexSize;    private int       extQuantum         = DefaultExtensionQuantum;    private int       fileSizeLimit      = 0;    private uint      transCommitDelay   = 0;    private CLI.CliOpenAttribute openAttributes = CLI.CliOpenAttribute.oaReadWrite;    private int       sessionThreadID    = -1;    private int       maxConnectRetries  = 0;    private int       reconnectTimeout   = DefReconnectTimeoutSec;    private bool      enableReplication  = false;    private int       nodeID             = 0;    private string[]  nodeNames          = new string[] {};    private bool      threaded           = false;    private ArrayList commands           = new ArrayList();  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -