public override void Call()
        {
            Progress.Caption = "Simplificando regiones...";
            var ci = context.Data.Session.Query <ClippingRegionItem>()
                     .ToList();

            Progress.Total = ci.Count;
            var session = medea.context.Data.Session;
            int i       = 1;

            foreach (var item in ci)
            {
                IGeometry geo = session.GetGeometry <ClippingRegionItem>(item.Id.Value,
                                                                         x => x.Geometry);
                i++;
                item.GeometryR1 = (Geometry)Simplifications.Simplify(geo, QualityEnum.High);
                if (item.GeometryR1.Coordinates.Length == 0)
                {
                    item.GeometryR1 = (Geometry)geo;
                }
                string sql = "update clipping_region_item set "
                             + "cli_geometry_r1 = " + InsertGenerator.GetValueEscaped(item.GeometryR1) +
                             " where cli_id = " + item.Id.Value;
                try
                {
                    session.SqlActions.ExecuteNonQuery(sql);
                }
                catch (Exception e)
                {
                    Errors.Add("falló: " + item.Id.Value + " - " + e.ToString());
                }

                Progress.Increment();
            }
        }
示例#2
0
        public void Insert_Simple()
        {
            var generator = new InsertGenerator <NotUpdateObject>();

            Console.WriteLine(generator.GetSql());
            Assert.AreEqual("INSERT INTO (`Id`, `Long`) VALUES (?p0, ?p1);", generator.GetSql());
        }
示例#3
0
        public void Insert_Simple()
        {
            var generator = new InsertGenerator <SimpleObject>();

            Console.WriteLine(generator.GetSql());
            Assert.AreEqual("INSERT INTO `table_name`(`LongColumnName`, `SomeString`, `NullableLong`, `Guid`, `NullableGuid`, `IntBasedEnum`, `NullableIntBasedEnum`) VALUES (?p0, ?p1, ?p2, ?p3, ?p4, ?p5, ?p6); SELECT LAST_INSERT_ID();", generator.GetSql());
        }
示例#4
0
        /// <summary>
        /// Insert a ingle row
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connection"></param>
        /// <param name="param">object</param>
        /// <param name="table">Optional table name</param>
        /// <param name="commandTimeout">commandTimeout</param>
        /// <param name="transaction">transaction</param>
        /// <returns>Numbers of rows affected</returns>
        public static int InsertSingle <T>(this IDbConnection connection, T param, int?commandTimeout = null, IDbTransaction transaction = null)
        {
            if (param == null)
            {
                throw new ArgumentNullException("param can not be null.");
            }

            if (param is IEnumerable)
            {
                throw new ArgumentException("param can not be a IEnumerable. Call InsertMany instead.");
            }

            var type = typeof(T);

            string cachedCommand;
            var    value = StringCache.TryGetCommand(type, Operation.Insert, out cachedCommand);

            if (string.IsNullOrEmpty(cachedCommand))
            {
                cachedCommand = InsertGenerator.GenerateSingle(param);
                StringCache.Add(type, Operation.Insert, cachedCommand);
            }

            return(connection.Execute(cachedCommand, param, commandTimeout: commandTimeout, transaction: transaction));
        }
示例#5
0
        /// <summary>
        /// Insert many rows
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connection"></param>
        /// <param name="insert">INSERT command "insert into Bar values "</param>
        /// <param name="values">sql values</param>
        /// <param name="list">IList<T> objects</param>
        /// <param name="maxItens">Maximun values per execution</param>
        /// <param name="maxPacketSize">Max size of command in bytes</param>
        /// <param name="commandTimeout">commandTimeout</param>
        /// <param param name="transaction">transaction</param>
        /// <returns>Numbers of rows affected</returns>
        public static int InsertMany <T>(this IDbConnection connection, string insert, string values, IList <T> list, int maxItens = 1000, int maxPacketSize = 4194304, int?commandTimeout = null, IDbTransaction transaction = null)
        {
            if (string.IsNullOrWhiteSpace(insert))
            {
                throw new ArgumentNullException("insert can not be null or white space.");
            }

            if (string.IsNullOrWhiteSpace(values))
            {
                throw new ArgumentNullException("values can not be null or white space.");
            }

            if (list == null)
            {
                throw new ArgumentNullException("list can not be null.");
            }

            if (maxItens < 0)
            {
                throw new ArgumentException("maxItens can not be less than 0.");
            }

            var commands = InsertGenerator.GenerateMany(insert, values, list, maxItens, maxPacketSize);

            var total = 0;

            foreach (var command in commands)
            {
                total += connection.Execute(command, commandTimeout: commandTimeout, transaction: transaction);
            }

            return(total);
        }
示例#6
0
        public void GeneratedFullCommand()
        {
            var insert = "Insert into table values";
            var values = "(@Foo1, @Foo2, 'murilo', 10, 11.12, @Foo3, @Foo4, @Foo5, @Foo6, @Foo7)";

            var commands = InsertGenerator.GenerateMany(insert, values, new List <Bar>
            {
                new Bar {
                    Foo1 = "uma string",
                    Foo2 = "outra string",
                    Foo3 = "mais uma string",
                    Foo4 = true,
                    Foo5 = null,
                    Foo6 = 15.1m,
                    Foo7 = 10.1d
                },
                new Bar {
                    Foo1 = "1",
                    Foo2 = "2",
                    Foo3 = "3",
                    Foo4 = false,
                    Foo5 = null,
                    Foo6 = 20,
                    Foo7 = 10.1d
                },
            }, 1000, 4194304);

            Assert.AreEqual("Insert into table values ('uma string', 'outra string', 'murilo', 10, 11.12, 'mais uma string', 1, null, 15.1, 10.1), ('1', '2', 'murilo', 10, 11.12, '3', 0, null, 20, 10.1);", commands[0]);
        }
示例#7
0
        public void GenerateMultipleInsertTyped()
        {
            var commands = InsertGenerator.GenerateMany(new List <Bar>
            {
                new Bar {
                    Foo1 = "uma string",
                    Foo2 = "outra string",
                    Foo3 = "mais uma string",
                    Foo4 = true,
                    Foo5 = null,
                    Foo6 = 15.1m
                },
                new Bar {
                    Foo1 = "1",
                    Foo2 = "2",
                    Foo3 = "3",
                    Foo4 = false,
                    Foo5 = null,
                    Foo6 = 20
                },
            }, 1000, 4194304);

            var value = "INSERT INTO Bar (Foo1, Foo2, Foo3, Foo4, Foo5, Foo6, Foo7) VALUES ('uma string', 'outra string', 'mais uma string', 1, null, 15.1, null), ('1', '2', '3', 0, null, 20, null);";

            Assert.AreEqual(value, commands[0]);
        }
        protected override DbCommandDefinition CreateDbCommandDefinition(
            DbProviderManifest providerManifest, DbCommandTree commandTree)
        {
            if (commandTree == null)
                throw new ArgumentNullException("commandTree");

            SqlGenerator generator = null;
            if (commandTree is DbQueryCommandTree)
                generator = new SelectGenerator();
            else if (commandTree is DbInsertCommandTree)
                generator = new InsertGenerator();
            else if (commandTree is DbUpdateCommandTree)
                generator = new UpdateGenerator();
            else if (commandTree is DbDeleteCommandTree)
                generator = new DeleteGenerator();
            else if (commandTree is DbFunctionCommandTree)
                generator = new FunctionGenerator();

            string sql = generator.GenerateSQL(commandTree);

            EFMySqlCommand cmd = new EFMySqlCommand();
            cmd.CommandText = sql;
            if (generator is FunctionGenerator)
                cmd.CommandType = (generator as FunctionGenerator).CommandType;

            SetExpectedTypes(commandTree, cmd);

            EdmFunction function = null;
            if (commandTree is DbFunctionCommandTree)
                function = (commandTree as DbFunctionCommandTree).EdmFunction;

            // Now make sure we populate the command's parameters from the CQT's parameters:
            foreach (KeyValuePair<string, TypeUsage> queryParameter in commandTree.Parameters)
            {
                DbParameter parameter = cmd.CreateParameter();
                parameter.ParameterName = queryParameter.Key;
                parameter.Direction = ParameterDirection.Input;
                parameter.DbType = Metadata.GetDbType(queryParameter.Value);

                FunctionParameter funcParam;
                if (function != null &&
                    function.Parameters.TryGetValue(queryParameter.Key, false, out funcParam))
                {
                    parameter.ParameterName = funcParam.Name;
                    parameter.Direction = Metadata.ModeToDirection(funcParam.Mode);
                    parameter.DbType = Metadata.GetDbType(funcParam.TypeUsage);
                }
                cmd.Parameters.Add(parameter);
            }

            // Now add parameters added as part of SQL gen
            foreach (DbParameter p in generator.Parameters)
                cmd.Parameters.Add(p);

            return CreateCommandDefinition(cmd);
        }
示例#9
0
        public void source_with_null_values()
        {
            var sw = new System.IO.StringWriter();

            var source = new Mock <IReader>();

            source.SetupSequence(x => x.Read())                     //Will return 2 records
            .Returns(true)
            .Returns(true)
            .Returns(false);
            source.Setup(x => x.AsNumber(0))                        //Setup values for first record
            .Returns(10);
            source.Setup(x => x.AsString(1))
            .Returns("John's house");
            source.Setup(x => x.AsBoolean(2))
            .Returns(true);
            source.SetupSequence(x => x.IsNull(It.IsAny <int>()))   //The IsNull method is called for each nullable field before try to convert the value
            .Returns(false)                                         //First row has values
            .Returns(false)
            .Returns(false)
            .Returns(true)                                          //Second row has all fields NULL
            .Returns(true)
            .Returns(true);

            var tbDef = new TableDef {
                TableName = "TestTable"
            };

            tbDef.Fields.AddRange(new List <FieldDef> {              //Al fiellds defined as nullable for this test
                new FieldDef {
                    Name            = "Id",
                    FieldType       = FieldType.Numeric,
                    OrdinalPosition = 0
                },
                new FieldDef {
                    Name            = "Name",
                    FieldType       = FieldType.Text,
                    OrdinalPosition = 1
                },
                new FieldDef {
                    Name            = "Enabled",
                    FieldType       = FieldType.Bool,
                    OrdinalPosition = 2
                }
            });

            var sut = new InsertGenerator(source.Object, NullLogger <InsertGenerator> .Instance, tbDef);

            sut.Generate(sw);
            string[] lines = sw.ToString().Split(sw.NewLine, StringSplitOptions.RemoveEmptyEntries);
            Assert.Collection(lines,
                              x => Assert.Equal("INSERT INTO [TestTable] ([Id], [Name], [Enabled]) VALUES (10, 'John''s house', 1);", x),
                              x => Assert.Equal("INSERT INTO [TestTable] ([Id], [Name], [Enabled]) VALUES (NULL, NULL, NULL);", x));
        }
示例#10
0
        private void SaveItems(Dictionary <string, int> ci)
        {
            if (!fileAdded)
            {
                return;
            }

            Progress.Caption = "Leyendo ítems";
            var features = ShapeFile.ReadShapefile(Basename + ".shp");

            Progress.Caption = "Preparando ítems";

            current.ClippingRegionItems.Clear();
            Progress.Total = 0;
            Progress.Total = features.Count;
            foreach (var feature in features)
            {
                ClippingRegionItem item = new ClippingRegionItem();
                item.Centroid = (Point)feature.Geometry.Centroid;
                item.Code     = feature.Attributes[iCode].ToString();
                if (iCaption != "")
                {
                    item.Caption = feature.Attributes[iCaption].ToString();
                }
                if (item.Caption.Contains("\n"))
                {
                    item.Caption = item.Caption.Split('\n')[0];
                }
                if (ci != null)
                {
                    var parent = feature.Attributes[iParent].ToString();
                    item.Parent = new ClippingRegionItem(ci[parent]);
                }
                else
                {
                    item.Parent = country;
                }

                item.Geometry   = (Geometry)feature.Geometry;
                item.GeometryR1 = (Geometry)Simplifications.Simplify(feature.Geometry, QualityEnum.High);

                item.ClippingRegion = current;
                current.ClippingRegionItems.Add(item);
                Progress.Increment();
            }

            Progress.Caption = "Guardando ítems";

            var sql = InsertGenerator.FromList(current.ClippingRegionItems);

            context.Data.Session.SqlActions.BulkInsert(sql, Progress);
            context.Data.Session.Flush();
            current.ClippingRegionItems.Clear();
        }
示例#11
0
        private void SaveItems()
        {
            var session = context.Data.Session;

            Progress.Caption = "Guardando ítems de región por geografía";

            var sql = InsertGenerator.FromList(current.ClippingRegionItemGeographyItems);

            context.Data.Session.SqlActions.BulkInsert(sql, Progress);
            context.Data.Session.Flush();
            current.ClippingRegionItemGeographyItems.Clear();
        }
示例#12
0
        public void InvalidProperty()
        {
            var insert = "Insert into table values";
            var values = "(@Foo1, @FooX)";

            var commands = InsertGenerator.GenerateMany(insert, values, new List <Bar>
            {
                new Bar()
            }, 1000, 4194304);

            Assert.AreEqual("Insert into table values ('uma string', 'outra string', 'murilo', 10, 11.12, 'mais uma string', 1, null, 15.1, 10.1), ('1', '2', 'murilo', 10, 11.12, '3', 0, null, 20, 10.1);", commands[0]);
        }
示例#13
0
        public void n_rows_source_generates_n_lines_output()
        {
            var sw = new System.IO.StringWriter();

            var source = new Mock <IReader>();

            source.SetupSequence(x => x.Read())
            .Returns(true)
            .Returns(true)
            .Returns(false);
            source.SetupSequence(x => x.AsNumber(0))
            .Returns(10)
            .Returns(11);
            source.SetupSequence(x => x.AsString(1))
            .Returns("John's house")
            .Returns("Moe tavern");
            source.SetupSequence(x => x.AsBoolean(2))
            .Returns(true)
            .Returns(false);


            var tbDef = new TableDef {
                TableName = "TestTable"
            };

            tbDef.Fields.AddRange(new List <FieldDef> {
                new FieldDef {
                    Name            = "Id",
                    FieldType       = FieldType.Numeric,
                    IsKey           = true,
                    IsNullable      = false,
                    OrdinalPosition = 0
                },
                new FieldDef {
                    Name            = "Name",
                    FieldType       = FieldType.Text,
                    OrdinalPosition = 1
                },
                new FieldDef {
                    Name            = "Enabled",
                    FieldType       = FieldType.Bool,
                    OrdinalPosition = 2
                }
            });

            var sut = new InsertGenerator(source.Object, NullLogger <InsertGenerator> .Instance, tbDef);

            sut.Generate(sw);
            string[] lines = sw.ToString().Split(sw.NewLine, StringSplitOptions.RemoveEmptyEntries);
            Assert.Equal(2, lines.Length);
        }
示例#14
0
        public void GenerateInsertCommand()
        {
            var command = InsertGenerator.GenerateSingle(new Bar
            {
                Foo1 = "uma string",
                Foo2 = "outra string",
                Foo3 = "mais uma string",
                Foo4 = true,
                Foo5 = null,
                Foo6 = 15.1m
            });

            Assert.AreEqual("INSERT INTO Bar (Foo1, Foo2, Foo3, Foo4, Foo5, Foo6, Foo7) VALUES (@Foo1, @Foo2, @Foo3, @Foo4, @Foo5, @Foo6, @Foo7);", command);
        }
示例#15
0
        public void CallDirect()
        {
            Progress.Caption = "Simplificando geografías...";
            var ci = context.Data.Session.Query <GeographyItem>()
                     .ToList();

            Progress.Total = ci.Count;
            var    session = medea.context.Data.Session;
            string cad     = "";
            int    i       = 0;

            foreach (var item in ci)
            {
                i++;
                IGeometry geo = session.GetGeometry <GeographyItem>(item.Id.Value,
                                                                    x => x.Geometry);

                Simplifications.FillSimplifiedGeometries((Geometry)geo, item);

                string sql = "update geography_item set "
                             + "gei_geometry_r1 = " + InsertGenerator.GetValueEscaped(item.GeometryR1)
                             + ", gei_geometry_r2 = " + InsertGenerator.GetValueEscaped(item.GeometryR2)
                             + ", gei_geometry_r3 = " + InsertGenerator.GetValueEscaped(item.GeometryR3)
                             + ", gei_geometry_r4 = " + InsertGenerator.GetValueEscaped(item.GeometryR4)
                             + ", gei_geometry_r5 = " + InsertGenerator.GetValueEscaped(item.GeometryR5)
                             + ", gei_geometry_r6 = " + InsertGenerator.GetValueEscaped(item.GeometryR6)
                             + " where gei_id = " + item.Id.Value + ";";
                cad = cad + sql;
                try
                {
                    if (i % 20 == 0)
                    {
                        session.SqlActions.ExecuteNonQuery(cad);
                        cad = "";
                    }
                }
                catch (Exception e)
                {
                    Errors.Add("falló: " + item.Id.Value + " - " + e.ToString());
                }

                Progress.Increment();
            }

            session.SqlActions.ExecuteNonQuery(cad);
            cad = "";
        }
示例#16
0
        public void long_text_is_truncated_at_maxLenght_position()
        {
            var sw = new System.IO.StringWriter();

            var source = new Mock <IReader>();

            source.SetupSequence(x => x.Read())                     //Will return 1 record
            .Returns(true)
            .Returns(true)
            .Returns(false);
            source.SetupSequence(x => x.AsNumber(0))
            .Returns(1)
            .Returns(2);
            source.SetupSequence(x => x.AsString(1))
            .Returns("0123456789")
            .Returns("012");


            var tbDef = new TableDef {
                TableName = "TestTable"
            };

            tbDef.Fields.AddRange(new List <FieldDef> {              //Al fiellds defined as nullable for this test
                new FieldDef {
                    Name            = "Id",
                    FieldType       = FieldType.Numeric,
                    OrdinalPosition = 0
                },
                new FieldDef {
                    Name            = "Name",
                    FieldType       = FieldType.Text,
                    MaxLength       = 5,
                    OrdinalPosition = 1
                }
            });

            var sut = new InsertGenerator(source.Object, NullLogger <InsertGenerator> .Instance, tbDef);

            sut.Generate(sw);
            string[] lines = sw.ToString().Split(sw.NewLine, StringSplitOptions.RemoveEmptyEntries);
            Assert.Collection(lines,
                              x => Assert.Equal("INSERT INTO [TestTable] ([Id], [Name]) VALUES (1, '01234');", x),
                              x => Assert.Equal("INSERT INTO [TestTable] ([Id], [Name]) VALUES (2, '012');", x));
        }
示例#17
0
        public void TestMaxItens()
        {
            var barList = new List <Bar>();

            for (int i = 0; i < 101; i++)
            {
                barList.Add(new Bar
                {
                    Foo1 = "uma string",
                    Foo2 = "outra string",
                    Foo3 = "mais uma string",
                    Foo4 = true,
                    Foo5 = null,
                    Foo6 = 15.1m
                });
            }

            var commands = InsertGenerator.GenerateMany(barList, 10, 4194304);

            Assert.AreEqual(11, commands.Count);
        }
示例#18
0
        public void TestMaxPacketSize()
        {
            var barList = new List <Bar>();

            for (int i = 0; i < 101; i++)
            {
                barList.Add(new Bar
                {
                    Foo1 = $"uma string {i}",
                    Foo2 = "outra string",
                    Foo3 = "mais uma string",
                    Foo4 = true,
                    Foo5 = null,
                    Foo6 = 15.1m
                });
            }

            var commands = InsertGenerator.GenerateMany(barList, 1000, 250);

            Assert.AreEqual(51, commands.Count);
        }
示例#19
0
        public void basic_insert()
        {
            var source = new Mock <IReader>();

            source.Setup(x => x.Read())
            .Returns(false);
            source.Setup(x => x.AsNumber(0))
            .Returns(10);
            source.Setup(x => x.AsString(1))
            .Returns("John's house");
            source.Setup(x => x.AsBoolean(2))
            .Returns(true);
            var tbDef = new TableDef {
                TableName = "TestTable"
            };

            tbDef.Fields.AddRange(new List <FieldDef> {
                new FieldDef {
                    Name            = "Id",
                    FieldType       = FieldType.Numeric,
                    IsKey           = true,
                    IsNullable      = false,
                    OrdinalPosition = 0
                },
                new FieldDef {
                    Name            = "Name",
                    FieldType       = FieldType.Text,
                    OrdinalPosition = 1
                },
                new FieldDef {
                    Name            = "Enabled",
                    FieldType       = FieldType.Bool,
                    OrdinalPosition = 2
                }
            });
            var    sut = new InsertGenerator(source.Object, NullLogger <InsertGenerator> .Instance, tbDef);
            string sql = sut.GenerateSQL();

            Assert.Equal("INSERT INTO [TestTable] ([Id], [Name], [Enabled]) VALUES (10, 'John''s house', 1);", sql);
        }
示例#20
0
        public void empty_source_generates_empty_output()
        {
            var sw = new System.IO.StringWriter();

            var source = new Mock <IReader>();

            source.Setup(x => x.Read())
            .Returns(false);
            var tbDef = new TableDef {
                TableName = "TestTable"
            };

            tbDef.Fields.AddRange(new List <FieldDef> {
                new FieldDef {
                    Name            = "Id",
                    FieldType       = FieldType.Numeric,
                    IsKey           = true,
                    IsNullable      = false,
                    OrdinalPosition = 0
                },
                new FieldDef {
                    Name            = "Name",
                    FieldType       = FieldType.Text,
                    OrdinalPosition = 1
                },
                new FieldDef {
                    Name            = "Enabled",
                    FieldType       = FieldType.Bool,
                    OrdinalPosition = 2
                }
            });

            var sut = new InsertGenerator(source.Object, NullLogger <InsertGenerator> .Instance, tbDef);

            sut.Generate(sw);

            Assert.Equal(string.Empty, sw.ToString());
        }
示例#21
0
        private async Task <int> Insert(object viewModel, Type type,
                                        CancellationToken cancellationToken, ReflectionTable reflectionTable,
                                        SqlTransaction transaction = null)
        {
            var insertGenerator = new InsertGenerator();
            var query           = insertGenerator.GetInsertQueryAndParameters(reflectionTable,
                                                                              viewModel, type);
            int affectedRowsCount;

            using (var conection = _connectionService.Create())
            {
                using (SqlCommand cmd = conection.CreateCommand())
                {
                    cmd.CommandText = query.Query;
                    cmd.Transaction = transaction;
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddRange(query.Params.ToArray());
                    affectedRowsCount = await cmd.ExecuteNonQueryAsync(cancellationToken);
                }
            }

            return(affectedRowsCount);
        }
示例#22
0
        protected override System.Data.Entity.Core.Common.DbCommandDefinition CreateDbCommandDefinition(
            System.Data.Entity.Core.Common.DbProviderManifest providerManifest, DbCommandTree commandTree)
        {
            if (commandTree == null)
            {
                throw new ArgumentNullException("commandTree");
            }

            SqlGenerator generator = null;

            if (commandTree is DbQueryCommandTree)
            {
                generator = new SelectGenerator();
            }
            else if (commandTree is DbInsertCommandTree)
            {
                generator = new InsertGenerator();
            }
            else if (commandTree is DbUpdateCommandTree)
            {
                generator = new UpdateGenerator();
            }
            else if (commandTree is DbDeleteCommandTree)
            {
                generator = new DeleteGenerator();
            }
            else if (commandTree is DbFunctionCommandTree)
            {
                generator = new FunctionGenerator();
            }

            string sql = generator.GenerateSQL(commandTree);

            EFMySqlCommand cmd = new EFMySqlCommand();

            cmd.CommandText = sql;
            if (generator is FunctionGenerator)
            {
                cmd.CommandType = (generator as FunctionGenerator).CommandType;
            }

            SetExpectedTypes(commandTree, cmd);

            EdmFunction function = null;

            if (commandTree is DbFunctionCommandTree)
            {
                function = (commandTree as DbFunctionCommandTree).EdmFunction;
            }

            // Now make sure we populate the command's parameters from the CQT's parameters:
            foreach (KeyValuePair <string, TypeUsage> queryParameter in commandTree.Parameters)
            {
                DbParameter parameter = cmd.CreateParameter();
                parameter.ParameterName = queryParameter.Key;
                parameter.Direction     = ParameterDirection.Input;
                parameter.DbType        = Metadata.GetDbType(queryParameter.Value);

#if NET_45_OR_GREATER
                if (queryParameter.Value.EdmType is PrimitiveType &&
                    ((PrimitiveType)queryParameter.Value.EdmType).PrimitiveTypeKind == PrimitiveTypeKind.Geometry)
                {
                    ((MySqlParameter)parameter).MySqlDbType = MySqlDbType.Geometry;
                }
#endif

                FunctionParameter funcParam;
                if (function != null &&
                    function.Parameters.TryGetValue(queryParameter.Key, false, out funcParam))
                {
                    parameter.ParameterName = funcParam.Name;
                    parameter.Direction     = Metadata.ModeToDirection(funcParam.Mode);
                    parameter.DbType        = Metadata.GetDbType(funcParam.TypeUsage);
                }
                cmd.Parameters.Add(parameter);
            }

            // Now add parameters added as part of SQL gen
            foreach (DbParameter p in generator.Parameters)
            {
                cmd.Parameters.Add(p);
            }

            return(CreateCommandDefinition(cmd));
        }
示例#23
0
        private void SaveItems(Dictionary <string, int> ci)
        {
            if (!fileAdded)
            {
                return;
            }

            Progress.Caption = "Guardando ítems";

            //Trae todos los items de la geografía padre para asociar.
            current.GeographyItems.Clear();
            Progress.Total = 0;
            var features = ShapeFile.ReadShapefile(Basename + ".shp");

            if (dbfMissingFilename != null)
            {
                var featuresMissing = ShapeFile.ReadDbasefile(dbfMissingFilename);
                features.AddRange(featuresMissing);
            }
            Progress.Total = features.Count;
            Dictionary <string, bool> done = new Dictionary <string, bool>();

            int n = 0;
            List <GeographyItem> l = new List <GeographyItem>();

            foreach (var feature in features)
            {
                GeographyItem item = new GeographyItem();
                if (iHousehold != "")
                {
                    item.Households = ParseOrZero(iHousehold, feature);
                }
                if (iChildren != "")
                {
                    item.Children = ParseOrZero(iChildren, feature);
                }
                if (iPopulation != "")
                {
                    item.Population = ParseOrZero(iPopulation, feature);
                }
                if (iUrbanity != "")
                {
                    item.Urbanity = UrbanityEnumFromInt(ParseOrZero(iUrbanity, feature));
                }
                else
                {
                    item.Urbanity = UrbanityEnum.None;
                }
                item.Code = feature.Attributes[iCode].ToString();
                if (iCaption != "")
                {
                    item.Caption = feature.Attributes[iCaption].ToString();
                }

                if (ci != null)
                {
                    var parent = feature.Attributes[iParent].ToString();
                    item.Parent = new GeographyItem(ci[parent]);
                }

                item.Geometry = (Geometry)feature.Geometry;
                if (feature.Geometry != null)
                {
                    item.AreaM2   = Projections.CalculateM2Area(feature.Geometry);
                    item.Centroid = (Point)feature.Geometry.Centroid;

                    Simplifications.FillSimplifiedGeometries(item.Geometry, item);
                }
                else
                {
                    throw new Exception("La geometría no puede ser nula.");
                }

                item.Geography = current;
                if (done.ContainsKey(item.Code) == false)
                {
                    l.Add(item);
                    done[item.Code] = true;
                    if (n % 100 == 99)
                    {
                        string sql = InsertGenerator.FromList(l);
                        context.Data.Session.SqlActions.ExecuteNonQuery(sql);
                        l.Clear();
                    }
                    n++;
                }
                Progress.Increment();
            }
            if (l.Count > 0)
            {
                string sql = InsertGenerator.FromList(l);
                context.Data.Session.SqlActions.ExecuteNonQuery(sql);
            }
            string updateAverage = "UPDATE `geography` SET geo_area_avg_m2=(select avg(gei_area_m2) from "
                                   + "geography_item where gei_geography_id = geo_id) WHERE geo_id = " + current.Id.Value.ToString();

            context.Data.Session.SqlActions.ExecuteNonQuery(updateAverage);
            // esta formula es cualquier cosa, que fitea más o menos 6 como maxzoom de provincias y 11 como maxzoom de departamentos.
            //string updateMaxZoom = "update geography set geo_max_zoom = truncate (16-(power(geo_area_avg_m2, .25) / 60),0) "
            //		+ "WHERE geo_id = " + current.Id.Value.ToString();
            //context.Data.Session.SqlActions.ExecuteNonQuery(updateAverage);
        }
示例#24
0
        public void Insert_Composite()
        {
            var generator = new InsertGenerator <CompositeIdSample>();

            Assert.AreEqual("INSERT INTO `composite_id_table`(`Id1`, `Id2`, `SomeValue`, `SomeDate`) VALUES (?p0, ?p1, ?p2, ?p3);", generator.GetSql());
        }