Example #1
0
        private static void CreateSchemaTables(ISchemaDescriptor schema, MySqlConnection rootConnection)
        {
            foreach (KeyValuePair <ITableDescriptor, IReadOnlyCollection <IColumnDescriptor> > TableEntry in schema.Tables)
            {
                ITableDescriptor Table     = TableEntry.Key;
                string           TableName = Table.Name;
                Debug.Assert(TableName.Length > 0);

                IReadOnlyCollection <IColumnDescriptor> TableStructure = TableEntry.Value;
                Debug.Assert(TableStructure.Count > 0);

                string KeyColumn       = null;
                bool   IsAutoIncrement = false;
                Dictionary <string, string> ColumnTable = new Dictionary <string, string>();
                foreach (IColumnDescriptor ColumnEntry in TableStructure)
                {
                    string ColumnName = ColumnEntry.Name;
                    string TypeName   = ColumnEntry.Type.SqlType;
                    ColumnTable.Add(ColumnName, TypeName);

                    if (KeyColumn == null)
                    {
                        KeyColumn       = ColumnName;
                        IsAutoIncrement = (ColumnEntry.Type is ColumnTypeInt);
                    }
                }

                Debug.Assert(KeyColumn != null);

                string ColumnStringList = "";
                foreach (KeyValuePair <string, string> ColumnEntry in ColumnTable)
                {
                    string ColumnName = ColumnEntry.Key;
                    string TypeName   = ColumnEntry.Value;

                    if (ColumnStringList.Length > 0)
                    {
                        ColumnStringList += ", ";
                    }

                    ColumnStringList += ColumnName + " " + TypeName;

                    if (ColumnName == KeyColumn)
                    {
                        ColumnStringList += " NOT NULL";

                        if (IsAutoIncrement)
                        {
                            ColumnStringList += " AUTO_INCREMENT";
                        }

                        ColumnStringList += " KEY";
                    }
                }

                string CommandString = $"CREATE TABLE IF NOT EXISTS {TableName} ( { ColumnStringList} );";
                TraceCommand(CommandString);
                ExecuteCommand(rootConnection, CommandString);
            }
        }
Example #2
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="Credential"/> class.
 /// </summary>
 /// <parameters>
 /// <param name="server">The server.</param>
 /// <param name="userId">The user identifier.</param>
 /// <param name="password">The password.</param>
 /// <param name="schema">The default schema to use.</param>
 /// </parameters>
 /// <exception cref="ArgumentNullException">
 ///     <paramref name="server"/> is null.
 /// </exception>
 /// <exception cref="ArgumentNullException">
 ///     <paramref name="userId"/> is null.
 /// </exception>
 /// <exception cref="ArgumentNullException">
 ///     <paramref name="password"/> is null.
 /// </exception>
 /// <exception cref="ArgumentNullException">
 ///     <paramref name="schema"/> is null.
 /// </exception>
 public Credential(string server, string userId, string password, ISchemaDescriptor schema)
 {
     Server   = server ?? throw new ArgumentNullException(nameof(server));
     UserId   = userId ?? throw new ArgumentNullException(nameof(userId));
     Password = password ?? throw new ArgumentNullException(nameof(password));
     Schema   = schema ?? throw new ArgumentNullException(nameof(schema));
 }
Example #3
0
 /// <summary>
 /// Builds the specified working folder.
 /// </summary>
 /// <param name="workingFolder">The working folder.</param>
 /// <param name="settings">The settings.</param>
 /// <param name="baseModel">The base model.</param>
 /// <param name="schema">The schema.</param>
 /// <param name="mapFileName">Name of the map file.</param>
 /// <returns></returns>
 protected MapConfig Build(string workingFolder,
                           ProjectSettings settings,
                           ComplexType baseModel,
                           ISchemaDescriptor schema,
                           string mapFileName)
 {
     return(Build(workingFolder, settings, baseModel, schema, new Dictionary <string, string>(), mapFileName));
 }
        /// <summary>
        ///     Initializes a new instance of the <see cref="TableDescriptor"/> class and adds it to the schema it belongs to.
        ///     Columns are added to this table when <see cref="IColumnDescriptor"/> objects are created.
        ///     By convention, the first column added to the table is considered the primary key.
        /// </summary>
        /// <parameters>
        /// <param name="schema">The schema containing the table.</param>
        /// <param name="name">The table name.</param>
        /// </parameters>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="schema"/> is null.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="name"/> is null or empty.
        /// </exception>
        public TableDescriptor(ISchemaDescriptor schema, string name)
        {
            Schema = schema ?? throw new ArgumentNullException(nameof(schema));
            Name   = !string.IsNullOrEmpty(name) ? name : throw new ArgumentNullException(nameof(name));

            if (Schema is SchemaDescriptor WriteableScheme)
            {
                WriteableScheme.AddTable(this);
            }
        }
Example #5
0
        /// <summary>
        /// Creates the map.
        /// </summary>
        /// <param name="schemaDescriptor">The schema descriptor.</param>
        /// <param name="entityRenames">The entity renames.</param>
        /// <param name="baseModel">The base model.</param>
        /// <param name="mapFilename">The map filename.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        /// schemaDescriptor
        /// or
        /// mapFilename
        /// </exception>
        public MapConfig CreateMap(ISchemaDescriptor schemaDescriptor, IDictionary <string, string> entityRenames, ComplexType baseModel, string mapFilename)
        {
            if (schemaDescriptor == null)
            {
                throw new ArgumentNullException(nameof(schemaDescriptor));
            }
            if (string.IsNullOrWhiteSpace(mapFilename))
            {
                throw new ArgumentNullException(nameof(mapFilename));
            }

            var map = codeGen.GenerateMapping(WorkingFolder, schemaDescriptor, entityRenames, Settings, baseModel, rdbms, mapFilename);

            map.MapStatements(QueryProviderName);
            return(map);
        }
        public virtual string FinalizeOperation(MySqlCommand command, ISingleQueryResultInternal result)
        {
            try
            {
                using (MySqlDataReader Reader = command.EndExecuteReader(result.AsyncResult))
                {
                    ITableDescriptor  Table  = Context.Table;
                    ISchemaDescriptor Schema = Table.Schema;
                    IReadOnlyCollection <IColumnDescriptor> TableStructure = Schema.Tables[Table];
                    FillResult(Reader, TableStructure, out List <IResultRow> Rows);

                    result.SetCompletedWithRows(Rows);
                    return($"succeeded, {Rows.Count} row(s) returned");
                }
            }
            catch
            {
                result.SetCompleted(false, ResultError.ErrorExceptionCompletingQuery);
                throw;
            }
        }
Example #7
0
        protected MapConfig Build(string workingFolder,
                                  ProjectSettings settings,
                                  ComplexType baseModel,
                                  ISchemaDescriptor schema,
                                  IDictionary <string, string> entityRenames,
                                  string mapFileName)
        {
            var rwords = Mssq2008Dialect.SqlServerReservedWords.Split(new string[] { " ", "\n", "," }, StringSplitOptions.RemoveEmptyEntries);

            schema.ProjectSettings = settings;
            var generator = new DataModelGenerator(schema, new NameTransformerFactory(settings),
                                                   new DefaultTableNameAbbreviator(rwords));

            MapConfig builder;

            if (baseModel != null)
            {
                builder = generator.GenerateMap(settings, entityRenames, baseModel);
            }
            else
            {
                builder = generator.GenerateMap(settings, entityRenames);
            }

            CreateFolderIfNotExist(workingFolder);

            string mapfile;

            if (!Path.IsPathRooted(mapFileName))
            {
                mapfile = Path.Combine(workingFolder, mapFileName);
            }
            else
            {
                mapfile = mapFileName;
            }

            builder.Save(mapfile, true);
            return(builder);
        }
Example #8
0
 /// <summary>
 /// Generates the mapping.
 /// </summary>
 /// <param name="workingFolder">The working folder.</param>
 /// <param name="schemaDescriptor">The schema descriptor.</param>
 /// <param name="entityRenames">The entity renames.</param>
 /// <param name="settings">The settings.</param>
 /// <param name="baseModel">The base model.</param>
 /// <param name="rdbms">The RDBMS.</param>
 /// <param name="mapFileName">Name of the map file.</param>
 /// <returns></returns>
 public MapConfig GenerateMapping(string workingFolder, ISchemaDescriptor schemaDescriptor, IDictionary <string, string> entityRenames, ProjectSettings settings, ComplexType baseModel, SupportedRdbms rdbms, string mapFileName)
 {
     return(Build(workingFolder, settings, baseModel, schemaDescriptor, entityRenames, mapFileName));
 }
Example #9
0
        public override void Execute(AppOptionInfo opts, CodeGenRunner codeGenRunner)
        {
            Console.WriteLine("\n\nCreate Map...");
            var         providerFactory = new ProviderFactory();
            ComplexType baseModel       = null;
            var         mapFileName     = Path.Combine(opts.WorkingFolder, opts.MapFile);
            var         baseMap         = new MapConfig();

            if (!string.IsNullOrWhiteSpace(opts.BaseModelXml) && File.Exists(opts.BaseModelXml))
            {
                Console.WriteLine("\n\nRead base model.");
                baseMap.Load(opts.BaseModelXml);
                if (baseMap.ComplexTypes.Count > 0)
                {
                    baseModel = baseMap.ComplexTypes[0];
                    codeGenRunner.Settings.BaseModel = baseModel.FullName;
                }
            }

            var rdbms = GetSupportedRdbms(opts);

            string[] whiteList;

            FilterSettings filterSettings = new FilterSettings();

            if (!string.IsNullOrWhiteSpace(opts.Include))
            {
                whiteList = opts.Include.Split(new string[] { ",", "|" }, StringSplitOptions.RemoveEmptyEntries);
                filterSettings.Exclude         = false;
                filterSettings.TableFilterList = whiteList;
            }
            else
            {
                filterSettings.Exclude         = true;
                filterSettings.TableFilterList = opts.ExcludedArray;
            }

            using (ISchemaDescriptor schemaDescriptor = providerFactory
                                                        .CreateDbSchemaDescriptor(rdbms, codeGenRunner.Settings, filterSettings))
            {
                var map = codeGenRunner.CreateMap(schemaDescriptor, opts.EntitiesToRename, baseModel, mapFileName);
                if (!string.IsNullOrWhiteSpace(opts.MappedStatementFile) && File.Exists(opts.MappedStatementFile))
                {
                    Console.WriteLine("Load mapped statements from {0} into {1}", opts.MappedStatementFile, mapFileName);
                    map.LoadMappedStatements(opts.MappedStatementFile);
                    CodeGenRunner.ProcessMappedStatements(map);
                }

                //let's try to read order from log if exists
                string primaOrda         = Path.Combine(opts.WorkingFolder, PrimaOrdaFile);
                var    previousOrderDict = new Dictionary <string, Tuple <int, string> >();
                var    orderCount        = 0;
                if (File.Exists(primaOrda))
                {
                    using (var sr = new StreamReader(primaOrda))
                    {
                        var contentLog = sr.ReadToEnd();
                        if (!string.IsNullOrWhiteSpace(contentLog))
                        {
                            var split = contentLog.Split(new string[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);
                            for (var i = 0; i < split.Length; i++)
                            {
                                var tbName = split[i];
                                previousOrderDict.Add(tbName, Tuple.Create(i + 1, tbName));
                            }

                            orderCount = split.Length;
                        }
                    }
                }

                map.MergeMap(baseMap);

                foreach (var ent in map.EntityConfigs)
                {
                    ProcessMetadata(opts, ent);
                    ProcessActivatedProperties(opts, ent);

                    Tuple <int, string> tbOrder;
                    if (previousOrderDict.TryGetValue(ent.FullName, out tbOrder))
                    {
                        ent.Order = tbOrder.Item1;
                    }
                    else
                    {
                        previousOrderDict.Add(ent.FullName, Tuple.Create(ent.Order, ent.FullName));
                        orderCount = orderCount + 1;
                        ent.Order  = orderCount;
                    }

                    //process keygen
                    if (!string.IsNullOrWhiteSpace(opts.DefaultKeygen))
                    {
                        if (ent.PrimaryKey != null)
                        {
                            foreach (var k in ent.PrimaryKey.Keys)
                            {
                                if (string.IsNullOrWhiteSpace(k.KeyGenerationStrategy))
                                {
                                    k.KeyGenerationStrategy = opts.DefaultKeygen;
                                }
                            }
                        }
                    }

                    foreach (var prop in ent)
                    {
                        ProcessMetadata(opts, ent, prop);
                        ProcessActivatedProperties(opts, ent, prop);

                        if (!string.IsNullOrWhiteSpace(opts.ComplexTypeMap))
                        {
                            var    key = string.Concat(ent.Name, ".", prop.Name);
                            string complextType;
                            if (opts.ComplexTypesTypeMap.TryGetValue(key, out complextType))
                            {
                                prop.ComplexTypeName = complextType;
                                prop.IsComplexType   = true;
                                opts.ComplexTypesTypeMap.Remove(key);
                            }
                        }
                    }

                    var unprocessedComplexTypes = opts.ComplexTypesTypeMap.Where(c => c.Key.StartsWith($"{ent.Name}.")).ToList();
                    if (unprocessedComplexTypes.Count > 0)
                    {
                        ProcessComplexTypes(unprocessedComplexTypes, ent, map);
                    }
                }

                map.Save(mapFileName, true, true);
                using (var file = new StreamWriter(primaOrda))
                {
                    foreach (var tbOrder in previousOrderDict.Keys)
                    {
                        file.WriteLine(tbOrder);
                    }
                }
            }
        }
Example #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DataModelGenerator"/> class.
 /// </summary>
 /// <param name="schemaDescriptor">The schema descriptor.</param>
 /// <param name="transformerFactory">The transformer factory.</param>
 /// <param name="tableAbbreviator">The table abbreviator.</param>
 public DataModelGenerator(ISchemaDescriptor schemaDescriptor, NameTransformerFactory transformerFactory, ITableNameAbbreviator tableAbbreviator)
 {
     this.schemaDescriptor = schemaDescriptor;
     transfactory          = transformerFactory;
     this.tableAbbreviator = tableAbbreviator;
 }