Пример #1
0
        public void MaxBatchSize_is_optional()
        {
            var optionsBuilder = new DbContextOptionsBuilder();

            optionsBuilder.UseNpgsql("Database=Crunchie");

            var typeMapper = new NpgsqlTypeMappingSource(
                new TypeMappingSourceDependencies(
                    new ValueConverterSelector(new ValueConverterSelectorDependencies())
                    ),
                new RelationalTypeMappingSourceDependencies(),
                new NpgsqlOptions()
                );
            var factory = new NpgsqlModificationCommandBatchFactory(
                new RelationalCommandBuilderFactory(
                    new FakeDiagnosticsLogger <DbLoggerCategory.Database.Command>(),
                    typeMapper),
                new RelationalSqlGenerationHelper(
                    new RelationalSqlGenerationHelperDependencies()),
                new NpgsqlUpdateSqlGenerator(
                    new UpdateSqlGeneratorDependencies(
                        new RelationalSqlGenerationHelper(
                            new RelationalSqlGenerationHelperDependencies()),
                        typeMapper)),
                new TypedRelationalValueBufferFactoryFactory(
                    new RelationalValueBufferFactoryDependencies(typeMapper)),
                optionsBuilder.Options);

            var batch = factory.Create();

            Assert.True(batch.AddCommand(new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, false, null)));
            Assert.True(batch.AddCommand(new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, false, null)));
        }
        public override void AddMappings(NpgsqlTypeMappingSource typeMappingSource)
        {
            typeMappingSource.ClrTypeMappings[typeof(Instant)]       = _timestampInstant;
            typeMappingSource.ClrTypeMappings[typeof(LocalDateTime)] = _timestampLocalDateTime;

            typeMappingSource.StoreTypeMappings["timestamp"] =
                typeMappingSource.StoreTypeMappings["timestamp without time zone"] =
                    new RelationalTypeMapping[] { _timestampInstant, _timestampLocalDateTime };

            typeMappingSource.ClrTypeMappings[typeof(ZonedDateTime)]  = _timestamptzZonedDateTime;
            typeMappingSource.ClrTypeMappings[typeof(OffsetDateTime)] = _timestamptzOffsetDateTime;

            typeMappingSource.StoreTypeMappings["timestamptz"] =
                typeMappingSource.StoreTypeMappings["timestamp with time zone"] =
                    new RelationalTypeMapping[] { _timestamptzInstant, _timestamptzOffsetDateTime, _timestamptzZonedDateTime };

            typeMappingSource.ClrTypeMappings[typeof(LocalDate)] = _date;
            typeMappingSource.StoreTypeMappings["date"]          = new RelationalTypeMapping[] { _date };

            typeMappingSource.ClrTypeMappings[typeof(LocalTime)] = _time;
            typeMappingSource.StoreTypeMappings["time"]          = new RelationalTypeMapping[] { _time };

            typeMappingSource.ClrTypeMappings[typeof(OffsetTime)] = _timetz;
            typeMappingSource.StoreTypeMappings["timetz"]         = new RelationalTypeMapping[] { _timetz };

            typeMappingSource.ClrTypeMappings[typeof(Period)] = _period;
            typeMappingSource.StoreTypeMappings["interval"]   = new RelationalTypeMapping[] { _period };
        }
    public void AddCommand_returns_false_when_max_batch_size_is_reached()
    {
        var typeMapper = new NpgsqlTypeMappingSource(
            TestServiceFactory.Instance.Create <TypeMappingSourceDependencies>(),
            TestServiceFactory.Instance.Create <RelationalTypeMappingSourceDependencies>(),
            new NpgsqlSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies()),
            new NpgsqlSingletonOptions());

        var logger = new FakeRelationalCommandDiagnosticsLogger();

        var batch = new NpgsqlModificationCommandBatch(
            new ModificationCommandBatchFactoryDependencies(
                new RelationalCommandBuilderFactory(
                    new RelationalCommandBuilderDependencies(
                        typeMapper,
                        new ExceptionDetector())),
                new NpgsqlSqlGenerationHelper(
                    new RelationalSqlGenerationHelperDependencies()),
                new NpgsqlUpdateSqlGenerator(
                    new UpdateSqlGeneratorDependencies(
                        new NpgsqlSqlGenerationHelper(
                            new RelationalSqlGenerationHelperDependencies()),
                        typeMapper)),
                new CurrentDbContext(new FakeDbContext()),
                logger),
            maxBatchSize: 1);

        Assert.True(
            batch.TryAddCommand(
                CreateModificationCommand("T1", null, false)));
        Assert.False(
            batch.TryAddCommand(
                CreateModificationCommand("T1", null, false)));
    }
Пример #4
0
        public void AddCommand_returns_false_when_max_batch_size_is_reached()
        {
            var typeMapper = new NpgsqlTypeMappingSource(
                new TypeMappingSourceDependencies(
                    new ValueConverterSelector(new ValueConverterSelectorDependencies())
                    ),
                new RelationalTypeMappingSourceDependencies(),
                new NpgsqlOptions()
                );

            var batch = new NpgsqlModificationCommandBatch(
                new RelationalCommandBuilderFactory(
                    new FakeDiagnosticsLogger <DbLoggerCategory.Database.Command>(),
                    typeMapper),
                new RelationalSqlGenerationHelper(
                    new RelationalSqlGenerationHelperDependencies()),
                new NpgsqlUpdateSqlGenerator(
                    new UpdateSqlGeneratorDependencies(
                        new RelationalSqlGenerationHelper(
                            new RelationalSqlGenerationHelperDependencies()),
                        typeMapper)),
                new TypedRelationalValueBufferFactoryFactory(
                    new RelationalValueBufferFactoryDependencies(typeMapper)),
                1);

            Assert.True(
                batch.AddCommand(
                    new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, false, null)));
            Assert.False(
                batch.AddCommand(
                    new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, false, null)));
        }
 public NpgsqlSqlExpressionFactory(SqlExpressionFactoryDependencies dependencies)
     : base(dependencies)
 {
     _typeMappingSource = (NpgsqlTypeMappingSource)dependencies.TypeMappingSource;
     _boolTypeMapping   = (RelationalTypeMapping)_typeMappingSource.FindMapping(typeof(bool), dependencies.Model) !;
     _doubleTypeMapping = (RelationalTypeMapping)_typeMappingSource.FindMapping(typeof(double), dependencies.Model) !;
 }
Пример #6
0
 public NpgsqlMigrationsSqlGenerator(
     [NotNull] MigrationsSqlGeneratorDependencies dependencies,
     [NotNull] INpgsqlOptions npgsqlOptions)
     : base(dependencies)
 {
     _sqlGenerationHelper = (NpgsqlSqlGenerationHelper)dependencies.SqlGenerationHelper;
     _typeMappingSource   = (NpgsqlTypeMappingSource)dependencies.TypeMappingSource;
     _postgresVersion     = npgsqlOptions.PostgresVersion;
 }
Пример #7
0
 public NpgsqlStringMethodTranslator(
     [NotNull] NpgsqlTypeMappingSource typeMappingSource,
     [NotNull] ISqlExpressionFactory sqlExpressionFactory)
 {
     _sqlExpressionFactory = sqlExpressionFactory;
     _whitespace           = _sqlExpressionFactory.Constant(
         @" \t\n\r",  // TODO: Complete this
         typeMappingSource.EStringTypeMapping);
     _textTypeMapping = (RelationalTypeMapping)typeMappingSource.FindMapping(typeof(string));
 }
 public NpgsqlStringMethodTranslator(
     NpgsqlTypeMappingSource typeMappingSource,
     ISqlExpressionFactory sqlExpressionFactory,
     IModel model)
 {
     _sqlExpressionFactory = sqlExpressionFactory;
     _whitespace           = _sqlExpressionFactory.Constant(
         @" \t\n\r",  // TODO: Complete this
         typeMappingSource.EStringTypeMapping);
     _textTypeMapping = typeMappingSource.FindMapping(typeof(string), model) !;
 }
Пример #9
0
        static NpgsqlNodaTimeTypeMappingTest()
        {
            var optionsBuilder = new DbContextOptionsBuilder();
            var npgsqlBuilder  = new NpgsqlDbContextOptionsBuilder(optionsBuilder).UseNodaTime();
            var options        = new NpgsqlOptions();

            options.Initialize(optionsBuilder.Options);

            Mapper = new NpgsqlTypeMappingSource(
                new TypeMappingSourceDependencies(
                    new ValueConverterSelector(new ValueConverterSelectorDependencies())
                    ),
                new RelationalTypeMappingSourceDependencies(),
                options
                );
        }
        public NpgsqlTypeMappingSourceTest()
        {
            var builder = new DbContextOptionsBuilder();

            new NpgsqlDbContextOptionsBuilder(builder).MapRange <float>("floatrange");
            new NpgsqlDbContextOptionsBuilder(builder).MapRange <DummyType>("dummyrange", subtypeName: "dummy");
            var options = new NpgsqlOptions();

            options.Initialize(builder.Options);

            Source = new NpgsqlTypeMappingSource(
                new TypeMappingSourceDependencies(
                    new ValueConverterSelector(new ValueConverterSelectorDependencies()),
                    Array.Empty <ITypeMappingSourcePlugin>()),
                new RelationalTypeMappingSourceDependencies(
                    new[] { new DummyTypeMappingSourcePlugin() }),
                new NpgsqlSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies()),
                options);
        }
Пример #11
0
        public override void AddMappings(NpgsqlTypeMappingSource typeMappingSource)
        {
            typeMappingSource.ClrTypeMappings[typeof(Geometry)]           = _geometry;
            typeMappingSource.ClrTypeMappings[typeof(Point)]              = _point;
            typeMappingSource.ClrTypeMappings[typeof(LineString)]         = _lineString;
            typeMappingSource.ClrTypeMappings[typeof(Polygon)]            = _polygon;
            typeMappingSource.ClrTypeMappings[typeof(MultiPoint)]         = _multiPoint;
            typeMappingSource.ClrTypeMappings[typeof(MultiLineString)]    = _multiLineString;
            typeMappingSource.ClrTypeMappings[typeof(MultiPolygon)]       = _multiPolygon;
            typeMappingSource.ClrTypeMappings[typeof(GeometryCollection)] = _collection;

            typeMappingSource.StoreTypeMappings["geometry"] = new RelationalTypeMapping[]
            {
                _geometry, _point, _lineString, _polygon, _multiPoint, _multiLineString, _multiPolygon, _collection
            };
            typeMappingSource.StoreTypeMappings["geography"] = new RelationalTypeMapping[]
            {
                _geography, _geogPoint, _geogLineString, _geogPolygon, _geogMultiPoint, _geogMultiLineString, _geogMultiPolygon, _geogCollection
            };
        }
    public void MaxBatchSize_is_optional()
    {
        var optionsBuilder = new DbContextOptionsBuilder();

        optionsBuilder.UseNpgsql("Database=Crunchie");

        var typeMapper = new NpgsqlTypeMappingSource(
            TestServiceFactory.Instance.Create <TypeMappingSourceDependencies>(),
            TestServiceFactory.Instance.Create <RelationalTypeMappingSourceDependencies>(),
            new NpgsqlSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies()),
            new NpgsqlOptions());

        var logger = new FakeRelationalCommandDiagnosticsLogger();

        var factory = new NpgsqlModificationCommandBatchFactory(
            new ModificationCommandBatchFactoryDependencies(
                new RelationalCommandBuilderFactory(
                    new RelationalCommandBuilderDependencies(
                        typeMapper,
                        new ExceptionDetector())),
                new NpgsqlSqlGenerationHelper(
                    new RelationalSqlGenerationHelperDependencies()),
                new NpgsqlUpdateSqlGenerator(
                    new UpdateSqlGeneratorDependencies(
                        new NpgsqlSqlGenerationHelper(
                            new RelationalSqlGenerationHelperDependencies()),
                        typeMapper)),
                new TypedRelationalValueBufferFactoryFactory(
                    new RelationalValueBufferFactoryDependencies(
                        typeMapper, new CoreSingletonOptions())),
                new CurrentDbContext(new FakeDbContext()),
                logger),
            optionsBuilder.Options);

        var batch = factory.Create();

        Assert.True(batch.AddCommand(CreateModificationCommand("T1", null, false)));
        Assert.True(batch.AddCommand(CreateModificationCommand("T1", null, false)));
    }
Пример #13
0
        public void Uses_MaxBatchSize_specified_in_NpgsqlOptionsExtension()
        {
            var optionsBuilder = new DbContextOptionsBuilder();

            optionsBuilder.UseNpgsql("Database=Crunchie", b => b.MaxBatchSize(1));

            var typeMapper = new NpgsqlTypeMappingSource(
                TestServiceFactory.Instance.Create <TypeMappingSourceDependencies>(),
                TestServiceFactory.Instance.Create <RelationalTypeMappingSourceDependencies>(),
                new NpgsqlSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies()),
                new NpgsqlOptions());

            var logger = new FakeRelationalCommandDiagnosticsLogger();

            var factory = new NpgsqlModificationCommandBatchFactory(
                new ModificationCommandBatchFactoryDependencies(
                    new RelationalCommandBuilderFactory(
                        new RelationalCommandBuilderDependencies(
                            typeMapper)),
                    new NpgsqlSqlGenerationHelper(
                        new RelationalSqlGenerationHelperDependencies()),
                    new NpgsqlUpdateSqlGenerator(
                        new UpdateSqlGeneratorDependencies(
                            new NpgsqlSqlGenerationHelper(
                                new RelationalSqlGenerationHelperDependencies()),
                            typeMapper)),
                    new TypedRelationalValueBufferFactoryFactory(
                        new RelationalValueBufferFactoryDependencies(
                            typeMapper, new CoreSingletonOptions())),
                    new CurrentDbContext(new FakeDbContext()),
                    logger),
                optionsBuilder.Options);

            var batch = factory.Create();

            Assert.True(batch.AddCommand(new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, false, null)));
            Assert.False(batch.AddCommand(new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, false, null)));
        }
        public void Uses_MaxBatchSize_specified_in_NpgsqlOptionsExtension()
        {
            var optionsBuilder = new DbContextOptionsBuilder();

            optionsBuilder.UseNpgsql("Database=Crunchie", b => b.MaxBatchSize(1));

            var typeMapper = new NpgsqlTypeMappingSource(
                new TypeMappingSourceDependencies(
                    new ValueConverterSelector(new ValueConverterSelectorDependencies()),
                    Array.Empty <ITypeMappingSourcePlugin>()
                    ),
                new RelationalTypeMappingSourceDependencies(Array.Empty <IRelationalTypeMappingSourcePlugin>()),
                new NpgsqlSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies()),
                new NpgsqlOptions()
                );
            var factory = new NpgsqlModificationCommandBatchFactory(
                new RelationalCommandBuilderFactory(
                    new FakeDiagnosticsLogger <DbLoggerCategory.Database.Command>(),
                    typeMapper),
                new RelationalSqlGenerationHelper(
                    new RelationalSqlGenerationHelperDependencies()),
                new NpgsqlUpdateSqlGenerator(
                    new UpdateSqlGeneratorDependencies(
                        new RelationalSqlGenerationHelper(
                            new RelationalSqlGenerationHelperDependencies()),
                        typeMapper)),
                new TypedRelationalValueBufferFactoryFactory(
                    new RelationalValueBufferFactoryDependencies(
                        typeMapper, new CoreSingletonOptions())),
                optionsBuilder.Options);

            var batch = factory.Create();

            Assert.True(batch.AddCommand(new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, false, null)));
            Assert.False(batch.AddCommand(new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, false, null)));
        }
Пример #15
0
        public void AddCommand_returns_false_when_max_batch_size_is_reached()
        {
            var typeMapper = new NpgsqlTypeMappingSource(
                TestServiceFactory.Instance.Create <TypeMappingSourceDependencies>(),
                TestServiceFactory.Instance.Create <RelationalTypeMappingSourceDependencies>(),
                new NpgsqlSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies()),
                new NpgsqlOptions());

            var logger = new FakeDiagnosticsLogger <DbLoggerCategory.Database.Command>();

            var batch = new NpgsqlModificationCommandBatch(
                new ModificationCommandBatchFactoryDependencies(
                    new RelationalCommandBuilderFactory(
                        new RelationalCommandBuilderDependencies(
                            typeMapper)),
                    new NpgsqlSqlGenerationHelper(
                        new RelationalSqlGenerationHelperDependencies()),
                    new NpgsqlUpdateSqlGenerator(
                        new UpdateSqlGeneratorDependencies(
                            new NpgsqlSqlGenerationHelper(
                                new RelationalSqlGenerationHelperDependencies()),
                            typeMapper)),
                    new TypedRelationalValueBufferFactoryFactory(
                        new RelationalValueBufferFactoryDependencies(
                            typeMapper, new CoreSingletonOptions())),
                    new CurrentDbContext(new FakeDbContext()),
                    logger),
                1);

            Assert.True(
                batch.AddCommand(
                    new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, false, null)));
            Assert.False(
                batch.AddCommand(
                    new ModificationCommand("T1", null, new ParameterNameGenerator().GenerateNext, false, null)));
        }
 public virtual void AddMappings(NpgsqlTypeMappingSource typeMappingSource)
 {
 }
        /// <summary>
        /// Inserts multiple records
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="dbContext"></param>
        /// <param name="entities"></param>
        public static int Execute <TEntity>(DbContext dbContext, IEnumerable <TEntity> entities)
        {
            /* Check dbContext against null */
            if (dbContext == null)
            {
                throw new ArgumentNullException(nameof(dbContext));
            }

            /* Check entities against null */
            if (entities == null)
            {
                throw new ArgumentNullException(nameof(entities));
            }

            /* NoOp */
            if (entities.Count() == 0)
            {
                return(0);
            }

            /* Get the underlying ADO.NET DbConnection for this DbContext */
            var connection = dbContext.Database.GetDbConnection();

            /* Open a database connection, if not done already */
            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }

            /* Get the type of the entity */
            var classType = typeof(TEntity);

            /* Gets the type of the entity that maps the given entity class */
            var entityType = dbContext.Model.FindEntityType(classType);

            /* Gets the relational database specific metadata for the specified entity */
            var tableMetadata = entityType.Relational();

            /* Type mapper */
            var typeMappingSource = new NpgsqlTypeMappingSource(
                new TypeMappingSourceDependencies(new ValueConverterSelector(new ValueConverterSelectorDependencies()),
                                                  Array.Empty <ITypeMappingSourcePlugin>()),
                new RelationalTypeMappingSourceDependencies(Array.Empty <IRelationalTypeMappingSourcePlugin>()),
                new NpgsqlSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies()),
                null
                );

            /* Get column info  */
            var properties = entityType.GetProperties()
                             .Where(x => !x.IsPrimaryKey())
                             .Select(x =>
            {
                /* Gets the relational database specific metadata for the current property */
                var propertyMetadata = x.Relational();
                return(new
                {
                    PropertyName = x.Name,
                    PropertyType = x.ClrType,
                    PropertyInfo = classType.GetProperty(x.Name),
                    propertyMetadata.ColumnName,
                    NpgsqlType = (typeMappingSource.FindMapping(x.ClrType) as NpgsqlTypeMapping)?.NpgsqlDbType,
                    propertyMetadata.ColumnType,
                    x.IsNullable
                });
            })
                             .ToList();

            /* Build the COPY command */
            var command = string.Format(
                @"COPY {0}""{1}"" ({2}) FROM STDIN BINARY;",
                string.IsNullOrWhiteSpace(tableMetadata.Schema) ? string.Empty : $"{tableMetadata.Schema}.",
                tableMetadata.TableName,
                properties.Select(x => $@"""{x.ColumnName}""").Aggregate((c, n) => $"{c}, {n}")
                );

            /* Begin a binary COPY FROM STDIN operation */
            using (var writer = (connection as NpgsqlConnection).BeginBinaryImport(command))
            {
                foreach (var entity in entities)
                {
                    if (entity == null)
                    {
                        continue;
                    }

                    /* Start writing a single row */
                    writer.StartRow();

                    foreach (var property in properties)
                    {
                        /* Get property value */
                        var value = property.PropertyInfo.GetValue(entity, null);

                        /* Write null */
                        if (value == null)
                        {
                            writer.WriteNull();
                            continue;
                        }

                        if (property.NpgsqlType != null)
                        {
                            writer.Write(value, property.NpgsqlType.Value);
                        }
                        else
                        {
                            writer.Write(value is Enum ? (int)value : value, property.ColumnType);
                        }
                    }
                }

                /* Complete the import operation */
                writer.Complete();
            }

            return(entities.Count());
        }
Пример #18
0
 public NpgsqlMigrationsSqlGenerator([NotNull] MigrationsSqlGeneratorDependencies dependencies)
     : base(dependencies)
 {
     _sqlGenerationHelper = (NpgsqlSqlGenerationHelper)dependencies.SqlGenerationHelper;
     _typeMappingSource   = (NpgsqlTypeMappingSource)dependencies.TypeMappingSource;
 }
 public NpgsqlStringMethodTranslator(ISqlExpressionFactory sqlExpressionFactory, NpgsqlTypeMappingSource npgsqlTypeMappingSource)
 {
     _sqlExpressionFactory = sqlExpressionFactory;
     _whitespace           = _sqlExpressionFactory.Constant(
         @" \t\n\r",  // TODO: Complete this
         npgsqlTypeMappingSource.EStringTypeMapping);
     _textTypeMapping = _sqlExpressionFactory.FindMapping(typeof(string));
 }