private void DropStore(DataTypeDescriptor dataTypeDescriptor, DataScopeIdentifier dataScope, CultureInfo cultureInfo)
        {
            string tableName = GetConfiguredTableName(dataTypeDescriptor, dataScope, cultureInfo.Name);

            if (string.IsNullOrEmpty(tableName))
            {
                return;
            }

            try
            {
                var tables = GetTablesList();

                if (tables.Contains(tableName))
                {
                    ExecuteNonQuery(string.Format("DROP TABLE [{0}];", tableName));

                    SqlTableInformationStore.ClearCache(_connectionString, tableName);
                }
            }
            catch (Exception ex)
            {
                throw MakeVerboseException(ex);
            }
        }
        internal void CreateStore(DataTypeDescriptor typeDescriptor, DataScopeIdentifier dataScope, CultureInfo cultureInfo,
                                  Action <string> existingTablesValidator = null)
        {
            string tableName = DynamicTypesCommon.GenerateTableName(typeDescriptor, dataScope, cultureInfo);
            var    tables    = GetTablesList();

            if (tables.Contains(tableName))
            {
                if (existingTablesValidator != null)
                {
                    existingTablesValidator(tableName);
                    return;
                }

                throw new InvalidOperationException("Database already contains a table named {0}".FormatWith(tableName));
            }

            var sql        = new StringBuilder();
            var sqlColumns = typeDescriptor.Fields.Select(fieldDescriptor
                                                          => GetColumnInfo(tableName, fieldDescriptor.Name, fieldDescriptor, true, false)
                                                          ).ToList();

            sql.AppendFormat("CREATE TABLE dbo.[{0}]({1});", tableName, string.Join(",", sqlColumns));
            sql.Append(SetPrimaryKey(tableName, typeDescriptor.KeyPropertyNames, typeDescriptor.PrimaryKeyIsClusteredIndex));

            try
            {
                ExecuteNonQuery(sql.ToString());
            }
            catch (Exception ex)
            {
                throw MakeVerboseException(ex);
            }

            foreach (var index in typeDescriptor.Indexes)
            {
                CreateIndex(tableName, index);
            }

            SqlTableInformationStore.ClearCache(_connectionString, tableName);
        }
Exemple #3
0
        private bool ValidateTable(Type interfaceType, string tableName, StringBuilder errors)
        {
            ISqlTableInformation sqlTableInformation = SqlTableInformationStore.GetTableInformation(_connectionString, tableName);

            if (sqlTableInformation == null)
            {
                errors.AppendLine("Table '{0}' does not exist".FormatWith(tableName));
                return(false);
            }

            int primaryKeyCount = sqlTableInformation.ColumnInformations.Count(column => column.IsPrimaryKey);

            if (primaryKeyCount == 0)
            {
                errors.AppendLine(string.Format("The table '{0}' is missing a primary key", tableName));
                return(false);
            }


            var columns    = new List <SqlColumnInformation>(sqlTableInformation.ColumnInformations);
            var properties = interfaceType.GetPropertiesRecursively();

            foreach (PropertyInfo property in properties)
            {
                if (property.Name == "DataSourceId")
                {
                    continue;
                }

                SqlColumnInformation column = columns.Find(col => col.ColumnName == property.Name);
                if (column == null)
                {
                    errors.AppendLine(string.Format("The interface property named '{0}' does not exist in the table '{1}' as a column", property.Name, sqlTableInformation.TableName));
                    return(false);
                }

                if (!column.IsNullable || column.Type == typeof(string))
                {
                    if (column.Type != property.PropertyType)
                    {
                        errors.AppendLine(string.Format("Type mismatch. The interface type '{0}' does not match the database type '{1}'", property.PropertyType, column.Type));
                        return(false);
                    }
                }
            }

            // Updating schema from C1 4.1, to be removed in future versions.
//            if (typeof (ILocalizedControlled).IsAssignableFrom(interfaceType)
//                && !properties.Any(p => p.Name == "CultureName")
//                && columns.Any(c => c.ColumnName == "CultureName"))
//            {
//                Log.LogInformation(LogTitle, "Removing obsolete 'CultureName' column from table '{0}'", tableName);


//                string selectConstraintName = string.Format(
//                    @"SELECT df.name 'ConstraintName'
//                    FROM sys.default_constraints df
//                    INNER JOIN sys.tables t ON df.parent_object_id = t.object_id
//                    INNER JOIN sys.columns c ON df.parent_object_id = c.object_id AND df.parent_column_id = c.column_id
//                    where t.name = '{0}'
//                    and c.name = 'CultureName'", tableName);


//                var dt = ExecuteReader(selectConstraintName);
//                List<string> constraints = (from DataRow dr in dt.Rows select dr["ConstraintName"].ToString()).ToList();

//                foreach (var constrainName in constraints)
//                {
//                    ExecuteSql("ALTER TABLE [{0}] DROP CONSTRAINT [{1}]".FormatWith(tableName, constrainName));
//                }

//                string sql = "ALTER TABLE [{0}] DROP COLUMN [CultureName]".FormatWith(tableName);

//                ExecuteSql(sql);
//            }

            return(true);
        }
Exemple #4
0
        private static void DoInitialize()
        {
            int startTime = Environment.TickCount;

            Guid installationId = InstallationInformationFacade.InstallationId;

            Log.LogVerbose(LogTitle, "Initializing the system core - installation id = " + installationId);

            using (new LogExecutionTime(LogTitle, "Initialization of the static data types"))
            {
                DataProviderRegistry.InitializeDataTypes();
            }


            using (new LogExecutionTime(LogTitle, "Auto update of static data types"))
            {
                bool typesUpdated = AutoUpdateStaticDataTypes();
                if (typesUpdated)
                {
                    using (new LogExecutionTime(LogTitle, "Reinitialization of the static data types"))
                    {
                        SqlTableInformationStore.Flush();
                        DataProviderRegistry.Flush();
                        DataProviderPluginFacade.Flush();


                        DataProviderRegistry.InitializeDataTypes();
                    }

                    CodeGenerationManager.GenerateCompositeGeneratedAssembly(true);
                }
            }


            using (new LogExecutionTime(LogTitle, "Ensure data stores"))
            {
                bool dataStoresCreated = DataStoreExistenceVerifier.EnsureDataStores();

                if (dataStoresCreated)
                {
                    Log.LogVerbose(LogTitle, "Initialization of the system was halted, performing a flush");
                    _initializing = false;
                    GlobalEventSystemFacade.FlushTheSystem();
                    return;
                }
            }



            using (new LogExecutionTime(LogTitle, "Initializing data process controllers"))
            {
                ProcessControllerFacade.Initialize_PostDataTypes();
            }


            using (new LogExecutionTime(LogTitle, "Initializing data type references"))
            {
                DataReferenceRegistry.Initialize_PostDataTypes();
            }


            using (new LogExecutionTime(LogTitle, "Initializing data type associations"))
            {
                DataAssociationRegistry.Initialize_PostDataTypes();
            }


            using (new LogExecutionTime(LogTitle, "Initializing internal urls"))
            {
                InternalUrls.Initialize_PostDataTypes();
            }


            using (new LogExecutionTime(LogTitle, "Initializing functions"))
            {
                MetaFunctionProviderRegistry.Initialize_PostDataTypes();
            }


            Log.LogVerbose(LogTitle, "Starting initialization of administrative secondaries");


            if (SystemSetupFacade.IsSystemFirstTimeInitialized && !SystemSetupFacade.SetupIsRunning)
            {
                using (new LogExecutionTime(LogTitle, "Initializing workflow runtime"))
                {
                    WorkflowFacade.EnsureInitialization();
                }
            }


            if (!RuntimeInformation.IsUnittest)
            {
                using (new LogExecutionTime(LogTitle, "Initializing flow system"))
                {
                    FlowControllerFacade.Initialize();
                }

                using (new LogExecutionTime(LogTitle, "Initializing console system"))
                {
                    ConsoleFacade.Initialize();
                }
            }


            using (new LogExecutionTime(LogTitle, "Auto installing packages"))
            {
                DoAutoInstallPackages();
            }


            using (new LogExecutionTime(LogTitle, "Loading element providers"))
            {
                ElementProviderLoader.LoadAllProviders();
            }


            int executionTime = Environment.TickCount - startTime;

            Log.LogVerbose(LogTitle, "Done initializing of the system core. ({0} ms)".FormatWith(executionTime));
        }
        private void AlterStore(UpdateDataTypeDescriptor updateDataTypeDescriptor, DataTypeChangeDescriptor changeDescriptor, DataScopeIdentifier dataScope, CultureInfo culture)
        {
            try
            {
                string originalTableName = GetConfiguredTableName(changeDescriptor.OriginalType, dataScope, culture.Name);
                string alteredTableName  = originalTableName;

                // This could be done more nicely! But only give the table a new name if the type has changed its name and not because we changed the naming scheme
                if (updateDataTypeDescriptor.OldDataTypeDescriptor.Name != updateDataTypeDescriptor.NewDataTypeDescriptor.Name ||
                    updateDataTypeDescriptor.OldDataTypeDescriptor.Namespace != updateDataTypeDescriptor.NewDataTypeDescriptor.Namespace)
                {
                    alteredTableName = DynamicTypesCommon.GenerateTableName(changeDescriptor.AlteredType, dataScope, culture);
                }

                var tables = GetTablesList();

                if (!tables.Contains(originalTableName))
                {
                    throw new InvalidOperationException(
                              string.Format(
                                  "Unable to alter data type store. The database does not contain expected table {0}",
                                  originalTableName));
                }


                bool primaryKeyChanged = changeDescriptor.AddedKeyFields.Any() ||
                                         changeDescriptor.DeletedKeyFields.Any() ||
                                         changeDescriptor.KeyFieldsOrderChanged ||
                                         changeDescriptor.OriginalType.PrimaryKeyIsClusteredIndex != changeDescriptor.AlteredType.PrimaryKeyIsClusteredIndex;

                DropConstraints(originalTableName, primaryKeyChanged);

                if (originalTableName != alteredTableName)
                {
                    if (tables.Contains(alteredTableName))
                    {
                        throw new InvalidOperationException(
                                  string.Format("Can not rename table to {0}. A table with that name already exists",
                                                alteredTableName));
                    }
                    RenameTable(originalTableName, alteredTableName);
                }

                var newIndexes = changeDescriptor.AlteredType.Indexes.Select(i => i.ToString()).ToList();
                foreach (var oldIndex in changeDescriptor.OriginalType.Indexes)
                {
                    if (!newIndexes.Contains(oldIndex.ToString()))
                    {
                        DropIndex(alteredTableName, oldIndex);
                    }
                }

                DropFields(alteredTableName, changeDescriptor.DeletedFields, changeDescriptor.OriginalType.Fields);
                ImplementFieldChanges(alteredTableName, changeDescriptor.ExistingFields);


                Dictionary <string, object> defaultValues = null;
                if (updateDataTypeDescriptor.PublicationAdded)
                {
                    defaultValues = new Dictionary <string, object>
                    {
                        { "PublicationStatus", GenericPublishProcessController.Draft }
                    };
                }

                AppendFields(alteredTableName, changeDescriptor.AddedFields, defaultValues);

                // Clustered index has to be created first.
                var createIndexActions = new List <Tuple <bool, Action> >();

                if (primaryKeyChanged)
                {
                    bool isClusteredIndex = changeDescriptor.AlteredType.PrimaryKeyIsClusteredIndex;

                    createIndexActions.Add(new Tuple <bool, Action>(isClusteredIndex,
                                                                    () => ExecuteNonQuery(SetPrimaryKey(alteredTableName, changeDescriptor.AlteredType.KeyPropertyNames, isClusteredIndex))
                                                                    ));
                }

                var oldIndexes = changeDescriptor.OriginalType.Indexes.Select(i => i.ToString()).ToList();
                foreach (var newIndex in changeDescriptor.AlteredType.Indexes)
                {
                    if (!oldIndexes.Contains(newIndex.ToString()))
                    {
                        var index = newIndex;

                        createIndexActions.Add(new Tuple <bool, Action>(newIndex.Clustered,
                                                                        () => CreateIndex(alteredTableName, index)));
                    }
                }

                createIndexActions.Sort((a, b) => b.Item1.CompareTo(a.Item1));

                foreach (var createIndex in createIndexActions)
                {
                    createIndex.Item2();
                }

                SqlTableInformationStore.ClearCache(_connectionString, originalTableName);
                SqlTableInformationStore.ClearCache(_connectionString, alteredTableName);
            }
            catch (Exception ex)
            {
                throw MakeVerboseException(ex);
            }
        }