Exemple #1
0
        public IEnumerable<IEntity> Select(EntityType type, bool useView, String where, params object[] arguments)
        {
            string[] columns = GetColumns(type);
            int n;
            String cmdKey = type.Name + where + useView;
            SqliteCommand cmd;
            if (!_commands.TryGetValue(cmdKey, out cmd))
            {
                String tableName = type.TableName;
                String columnNames = "";
                foreach (string column in columns)
                    columnNames = columnNames + String.Format("{0}{1}", String.IsNullOrEmpty(columnNames) ? "" : ",", column);
                if (!useView)
                    columnNames = columnNames + ",IsTombstone";
                columnNames = columnNames + ",IsDirty";

                cmd = new SqliteCommand
                {
                    Connection = ActiveConnection,
                    CommandText =
                        String.Format("SELECT {0} FROM [{1}]{2}", columnNames, useView ? tableName : "_" + tableName,
                            String.IsNullOrEmpty(@where) ? "" : " " + @where)
                };
                n = 1;
                foreach (object p in arguments)
                {
                    cmd.Parameters.AddWithValue(String.Format("@p{0}", n), p);
                    n++;
                }
                cmd.Prepare();
                _commands.Add(cmdKey, cmd);
            }
            else
            {
                for (int i = 0; i < arguments.Length; i++)
                {
                    cmd.Parameters[i].Value = arguments[i];
                }
            }

            var list = new List<IEntity>();
            using (SqliteDataReader r = cmd.ExecuteReader())
            {
                if (r.HasRows)
                {
                    while (r.Read())
                    {
                        IEntity entity = EntityFactory.CreateInstance(type);
                        n = 0;
                        foreach (string column in columns)
                        {
                            Type t = type.GetPropertyType(column);
                            if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
                                t = Nullable.GetUnderlyingType(t);

                            object value = r[n];
                            if (value.GetType().Equals(typeof(DBNull)))
                                value = null;
                            else
                            {
                                if (t.Equals(typeof(IDbRef)))
                                    value = DbRef.FromString(value.ToString());
                                else
                                {
                                    if (t == typeof(Guid))
                                    {
                                        Guid g;
                                        if (!Guid.TryParse(value.ToString(), out g))
                                        {
                                            if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
                                                value = null;
                                            else
                                                throw new ArgumentException(String.Format("Can't convert value '{0}' to System.Guid", value));
                                        }
                                        else
                                            value = g;
                                    }
                                    else
                                        value = Convert.ChangeType(value, t);
                                }
                            }
                            entity.SetValue(column, value);
                            n++;
                        }

                        bool isTombstone = !useView && (long)r["IsTombstone"] != 0;
                        (entity as ISqliteEntity).IsTombstone = isTombstone;
                        (entity as ISqliteEntity).Load((long)r["IsDirty"] != 0);

                        list.Add(entity);
                    }
                }
            }
            return list;
        }
        public void CreateTable(EntityType type)
        {
            //String[] arr = type.Name.Split('.');
            String tableName = type.TableName;//String.Format("{0}_{1}", arr[arr.Length - 2], arr[arr.Length - 1]);
            String columns = "";
            String columnsOnly = "";

            var indexedFields = new List<string>();

            foreach (string column in type.GetColumns())
            {
                Type columnType = GetType(type.GetPropertyType(column));
                if (!_supportedTypes.ContainsKey(columnType))
                    throw new Exception(String.Format("Unsupported column type '{0}'", columnType));

                String columnName = String.Format("{0}", column);
                String typeDeclaration = String.Format(_supportedTypes[columnType].TypeName);

                String primaryKey = type.IsPrimaryKey(column) ? "PRIMARY KEY" : "";

                const string notNull = "";
                
                if (type.IsIndexed(column))
                    indexedFields.Add(columnName);

                String s = String.Format("[{0}] {1} {2} {3}", columnName, typeDeclaration, notNull, primaryKey);
                String s1 = String.Format("[{0}]", columnName);

                if (!String.IsNullOrEmpty(columns))
                {
                    s = "," + s;
                    s1 = "," + s1;
                }

                columns = columns + s;
                columnsOnly = columnsOnly + s1;
            }

            columns += ",[IsTombstone] INTEGER,[IsDirty] INTEGER";
            columnsOnly += ",[IsDirty]";

            //create table
            using (var cmd = new SqliteCommand(String.Format("CREATE TABLE [_{0}] ({1})", tableName, columns), ActiveConnection))
                cmd.ExecuteNonQuery();

            //create tran table
            using (var cmd = new SqliteCommand(String.Format("CREATE TABLE [__{0}] ({1})", tableName, columns), ActiveConnection))
                cmd.ExecuteNonQuery();

            //create indexes
            indexedFields.Add("IsTombstone");
            foreach (String idx in indexedFields)
            {
                String idxScript = String.Format("CREATE INDEX [{0}_{1}] ON _{0}([{1}])", tableName, idx);
                using (var idxCmd = new SqliteCommand(idxScript, ActiveConnection))
                    idxCmd.ExecuteNonQuery();
            }

            //create view
            using (var cmd = new SqliteCommand(String.Format(
                "CREATE VIEW [{0}] AS SELECT {1} FROM [_{0}] WHERE IsTombstone = 0", tableName, columnsOnly), ActiveConnection))
                cmd.ExecuteNonQuery();
        }