예제 #1
0
        /// <summary>
        /// Register Data Object Type if not already Registered
        /// </summary>
        /// <param name="dataObjectType">DataObject Type</param>
        public override void RegisterDataObject(Type dataObjectType)
        {
            var tableName = AttributesUtils.GetTableOrViewName(dataObjectType);
            var isView    = AttributesUtils.GetViewName(dataObjectType) != null;
            var viewAs    = AttributesUtils.GetViewAs(dataObjectType);

            DataTableHandler existingHandler;

            if (TableDatasets.TryGetValue(tableName, out existingHandler))
            {
                if (dataObjectType != existingHandler.ObjectType)
                {
                    throw new DatabaseException(string.Format("Table Handler Duplicate for Type: {2}, Table Name '{0}' Already Registered with Type : {1}", tableName, existingHandler.ObjectType, dataObjectType));
                }

                return;
            }

            var dataTableHandler = new DataTableHandler(dataObjectType);

            try
            {
                if (isView)
                {
                    if (!string.IsNullOrEmpty(viewAs))
                    {
                        ExecuteNonQueryImpl(string.Format("DROP VIEW IF EXISTS `{0}`", tableName));
                        ExecuteNonQueryImpl(string.Format("CREATE VIEW `{0}` AS {1}", tableName, string.Format(viewAs, string.Format("`{0}`", AttributesUtils.GetTableName(dataObjectType)))));
                    }
                }
                else
                {
                    CheckOrCreateTableImpl(dataTableHandler);
                }

                lock (Lock)
                {
                    TableDatasets.Add(tableName, dataTableHandler);
                }

                // Init PreCache
                if (dataTableHandler.UsesPreCaching)
                {
                    var primary = dataTableHandler.PrimaryKeys.Single();
                    var objects = MultipleSelectObjectsImpl(dataTableHandler, new [] { WhereClause.Empty }).First();

                    foreach (var obj in objects)
                    {
                        dataTableHandler.SetPreCachedObject(primary.GetValue(obj), obj);
                    }
                }
            }
            catch (Exception e)
            {
                if (log.IsErrorEnabled)
                {
                    log.ErrorFormat("RegisterDataObject: Error While Registering Table \"{0}\"\n{1}", tableName, e);
                }
            }
        }
예제 #2
0
        /// <summary>
        /// Retrieve All DataTables Type
        /// </summary>
        public static IList <Type> GetAllDataTableTypes()
        {
            var result = new List <Type>();

            try
            {
                // Walk through each assembly in scripts
                foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
                {
                    // Walk through each type in the assembly
                    foreach (var type in asm.GetTypes())
                    {
                        if (!type.IsClass || type.IsAbstract || !typeof(DataObject).IsAssignableFrom(type))
                        {
                            continue;
                        }

                        // Don't Keep Views...
                        if (type.GetCustomAttributes <DataTable>(false).Any() && AttributesUtils.GetViewName(type) == null)
                        {
                            result.Add(type);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("Error while Listing Data Tables", ex);
                }
            }

            return(result);
        }
예제 #3
0
        /// <summary>
        /// Create new instance of <see cref="DataTableHandler"/>
        /// </summary>
        /// <param name="ObjectType">DataObject Type</param>
        public DataTableHandler(Type ObjectType)
        {
            if (!typeof(DataObject).IsAssignableFrom(ObjectType))
            {
                throw new ArgumentException("DataTableHandler can only register DataObject Types", "ObjectType");
            }

            this.ObjectType = ObjectType;
            // Init Cache and Table Params
            TableName = AttributesUtils.GetTableOrViewName(ObjectType);

            var isView = AttributesUtils.GetViewName(ObjectType) != null;

            HasRelations   = false;
            UsesPreCaching = AttributesUtils.GetPreCachedFlag(ObjectType);
            if (UsesPreCaching)
            {
                _precache = new ConcurrentDictionary <object, DataObject>();
            }

            // Parse Table Type
            ElementBindings = ObjectType.GetMembers().Select(member => new ElementBinding(member)).Where(bind => bind.IsDataElementBinding).ToArray();

            // Views Can't Handle Auto GUID Key
            if (!isView)
            {
                // If no Primary Key AutoIncrement add GUID
                if (FieldElementBindings.Any(bind => bind.PrimaryKey != null && !bind.PrimaryKey.AutoIncrement))
                {
                    ElementBindings = ElementBindings.Concat(new [] {
                        new ElementBinding(ObjectType.GetProperty("ObjectId"),
                                           new DataElement()
                        {
                            Unique = true
                        },
                                           string.Format("{0}_ID", TableName))
                    }).ToArray();
                }
                else if (FieldElementBindings.All(bind => bind.PrimaryKey == null))
                {
                    ElementBindings = ElementBindings.Concat(new [] {
                        new ElementBinding(ObjectType.GetProperty("ObjectId"),
                                           new PrimaryKey(),
                                           string.Format("{0}_ID", TableName))
                    }).ToArray();
                }
            }

            // Prepare Table
            Table = new DataTable(TableName);
            var multipleUnique = new List <ElementBinding>();
            var indexes        = new Dictionary <string, ElementBinding[]>();

            //Build Table for DataSet
            foreach (var bind in ElementBindings)
            {
                if (bind.Relation != null)
                {
                    HasRelations = true;
                    continue;
                }

                var column = Table.Columns.Add(bind.ColumnName, bind.ValueType);

                if (bind.PrimaryKey != null)
                {
                    column.AutoIncrement = bind.PrimaryKey.AutoIncrement;
                    Table.PrimaryKey     = new [] { column };
                }

                if (bind.DataElement != null)
                {
                    column.AllowDBNull = bind.DataElement.AllowDbNull;

                    // Store Multi Unique for definition after table
                    // Single Unique can be defined directly.
                    if (!string.IsNullOrEmpty(bind.DataElement.UniqueColumns))
                    {
                        multipleUnique.Add(bind);
                    }
                    else if (bind.DataElement.Unique)
                    {
                        Table.Constraints.Add(new UniqueConstraint(string.Format("U_{0}_{1}", TableName, bind.ColumnName), column));
                    }

                    // Store Indexes for definition after table
                    if (!string.IsNullOrEmpty(bind.DataElement.IndexColumns))
                    {
                        indexes.Add(string.Format("I_{0}_{1}", TableName, bind.ColumnName), bind.DataElement.IndexColumns.Split(',')
                                    .Select(col => FieldElementBindings.FirstOrDefault(ind => ind.ColumnName.Equals(col.Trim(), StringComparison.OrdinalIgnoreCase)))
                                    .Concat(new [] { bind }).ToArray());
                    }
                    else if (bind.DataElement.Index)
                    {
                        indexes.Add(string.Format("I_{0}_{1}", TableName, bind.ColumnName), new [] { bind });
                    }

                    if (bind.DataElement.Varchar > 0)
                    {
                        column.ExtendedProperties.Add("VARCHAR", bind.DataElement.Varchar);
                    }
                }
            }

            // Set Indexes when all columns are set
            Table.ExtendedProperties.Add("INDEXES", indexes.Select(kv => new KeyValuePair <string, DataColumn[]>(
                                                                       kv.Key,
                                                                       kv.Value.Select(bind => Table.Columns[bind.ColumnName]).ToArray()))
                                         .ToDictionary(kv => kv.Key, kv => kv.Value));

            // Set Unique Constraints when all columns are set.
            foreach (var bind in multipleUnique)
            {
                var columns = bind.DataElement.UniqueColumns.Split(',').Select(column => column.Trim()).Concat(new [] { bind.ColumnName });
                Table.Constraints.Add(new UniqueConstraint(string.Format("U_{0}_{1}", TableName, bind.ColumnName),
                                                           columns.Select(column => Table.Columns[column]).ToArray()));
            }
        }