diff --git a/.github/workflows/build-documentation.yml b/.github/workflows/build-documentation.yml index 700a2c4e..704f70fc 100644 --- a/.github/workflows/build-documentation.yml +++ b/.github/workflows/build-documentation.yml @@ -9,22 +9,46 @@ on: # Allows you to run this workflow manually from the Actions tab workflow_dispatch: + # Triggered by the Npgsql and EFCore.PG repos when their docs change + repository_dispatch: + types: [docs-changed] + + # Nightly rebuild to pick up API changes + schedule: + - cron: "0 3 * * *" + concurrency: - group: "pages" - cancel-in-progress: false + group: pages-${{ github.ref }} + # Don't cancel in-progress deployments; pending runs are still superseded by the latest one. + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: build: runs-on: ubuntu-24.04 + permissions: + contents: read + packages: read env: - # Build pinned source snapshots for API docs, not dependency auditing. + # Build source snapshots for API docs, not dependency auditing. NuGetAudit: "false" steps: - name: Checkout repo uses: actions/checkout@v7 + + - name: Checkout Npgsql + uses: actions/checkout@v7 with: - submodules: true + repository: npgsql/npgsql + ref: main + path: Npgsql + + - name: Checkout EFCore.PG + uses: actions/checkout@v7 + with: + repository: npgsql/efcore.pg + ref: main + path: EFCore.PG - name: Use Node.js uses: actions/setup-node@v7.0.0 @@ -56,8 +80,13 @@ jobs: shell: bash working-directory: EFCore.PG + # Released docfx (2.81.0) bundles an older Roslyn than Npgsql's source generator requires; use the nightly + # until a release with Roslyn 5.12+ ships. - name: Get docfx - run: dotnet tool install --version 2.81.0 -g docfx + run: | + dotnet nuget add source https://nuget.pkg.github.com/dotnet/index.json -n docfx-nightly \ + -u ${{ github.actor }} -p ${{ secrets.GITHUB_TOKEN }} --store-password-in-clear-text + dotnet tool install -g docfx --prerelease - name: Build docs run: docfx --warningsAsErrors @@ -70,7 +99,7 @@ jobs: deploy: needs: build runs-on: ubuntu-latest - if: github.event_name == 'push' && github.ref_name == 'main' + if: github.event_name != 'pull_request' && github.ref_name == 'main' permissions: contents: read pages: write diff --git a/.gitignore b/.gitignore index d069b0a5..8e5fae2b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ obj +/Npgsql +/EFCore.PG /_site /_exported_templates diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 79b5f1c3..00000000 --- a/.gitmodules +++ /dev/null @@ -1,6 +0,0 @@ -[submodule "Npgsql"] - path = Npgsql - url = https://github.com/npgsql/npgsql.git -[submodule "EFCore.PG"] - path = EFCore.PG - url = https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL.git diff --git a/EFCore.PG b/EFCore.PG deleted file mode 160000 index 2679a9d7..00000000 --- a/EFCore.PG +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 2679a9d768d14f34d077e037311f80acb6f6b3b4 diff --git a/Npgsql b/Npgsql deleted file mode 160000 index 4d174200..00000000 --- a/Npgsql +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 4d174200ed48e3e3ab16419dbf84dd655da59de6 diff --git a/README.md b/README.md index 16027fe1..fb725d67 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ This is the documentation repo for Npgsql. -It contains conceptual documentation articles for Npgsql, Npgsql.EntityFrameworkCore.PostgreSQL (AKA EFCore.PG) and EntityFramework6.Npgsql (AKA EF6.PG). +It contains the site shell and the conceptual documentation for EntityFramework6.Npgsql (AKA EF6.PG). The conceptual documentation for Npgsql and Npgsql.EntityFrameworkCore.PostgreSQL (AKA EFCore.PG) lives in the `docs` directory of their respective repos ([npgsql/npgsql](https://github.com/npgsql/npgsql), [npgsql/efcore.pg](https://github.com/npgsql/efcore.pg)). -Note that to properly work, docfx expects to also find the Npgsql and EFCore.PG repos cloned in the repo root - it extracts API documentation from them. +To build locally, clone the Npgsql and EFCore.PG repos into `Npgsql` and `EFCore.PG` in the repo root - docfx takes the conceptual docs from their `docs` directories, and extracts API documentation from their sources. -A Github Actions workflow automatically clones the appropriate repository, rebuilds the entire documentation and pushes the results to live. +A GitHub Actions workflow clones the latest `main` of both repos, rebuilds the entire documentation and pushes the results to live. It runs on pushes to this repo, when the Npgsql or EFCore.PG repos signal a docs change (via `repository_dispatch`), and nightly. diff --git a/conceptual/EFCore.PG/index.md b/conceptual/EFCore.PG/index.md deleted file mode 100644 index 359b9a6c..00000000 --- a/conceptual/EFCore.PG/index.md +++ /dev/null @@ -1,168 +0,0 @@ -# Npgsql Entity Framework Core Provider - -[![stable](https://img.shields.io/nuget/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=stable)](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL/) -[![next patch](https://img.shields.io/myget/npgsql/v/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=next%20patch)](https://www.myget.org/feed/npgsql/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) -[![vnext](https://img.shields.io/myget/npgsql-vnext/vpre/Npgsql.EntityFrameworkCore.PostgreSQL.svg?label=vnext)](https://www.myget.org/feed/npgsql-vnext/package/nuget/Npgsql.EntityFrameworkCore.PostgreSQL) -[![build](https://img.shields.io/github/actions/workflow/status/npgsql/efcore.pg/build.yml?branch=main)](https://github.com/npgsql/efcore.pg/actions) - -Npgsql has an Entity Framework (EF) Core provider. It behaves like other EF Core providers (e.g. SQL Server), so the [general EF Core docs](https://docs.microsoft.com/ef/core/index) apply here as well. If you're just getting started with EF Core, those docs are the best place to start. - -Development happens in the [Npgsql.EntityFrameworkCore.PostgreSQL](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL) repository, all issues should be reported there. - -## Configuring the project file - -To use the Npgsql EF Core provider, add a dependency on `Npgsql.EntityFrameworkCore.PostgreSQL`. You can follow the instructions in the general [EF Core Getting Started docs](https://docs.microsoft.com/ef/core/get-started/). - -Below is a `.csproj` file for a console application that uses the Npgsql EF Core provider: - -```xml - - - net8.0 - - - - - -``` - -## Defining a model and a `DbContext` - -Let's say you want to store blogs and their posts in their database; you can model these as .NET types as follows: - -```csharp -public class Blog -{ - public int BlogId { get; set; } - public string Url { get; set; } - - public List Posts { get; set; } -} - -public class Post -{ - public int PostId { get; set; } - public string Title { get; set; } - public string Content { get; set; } - - public int BlogId { get; set; } - public Blog Blog { get; set; } -} -``` - -You then define a `DbContext` type which you'll use to interact with the database: - -### [OnConfiguring](#tab/onconfiguring) - -Using `OnConfiguring()` to configure your context is the easiest way to get started, but is discouraged for most production applications: - -```csharp -public class BloggingContext : DbContext -{ - public DbSet Blogs { get; set; } - public DbSet Posts { get; set; } - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseNpgsql(""); -} - -// At the point where you need to perform a database operation: -using var context = new BloggingContext(); -// Use the context... -``` - -### [DbContext pooling](#tab/context-pooling) - -```csharp -var dbContextFactory = new PooledDbContextFactory( - new DbContextOptionsBuilder() - .UseNpgsql("") - .Options); - -// At the point where you need to perform a database operation: -using var context = dbContextFactory.CreateDbContext(); -// Use the context... -``` - -### [ASP.NET / DI](#tab/aspnet) - -When using ASP.NET - or any application with dependency injection - the context instance will be injected into your code. Use the following to configure EF with your DI container: - -```csharp -var builder = WebApplication.CreateBuilder(args); - -builder.Services.AddDbContextPool(opt => - opt.UseNpgsql(builder.Configuration.GetConnectionString("BloggingContext"))); - -public class BloggingContext(DbContextOptions options) : DbContext(options) -{ - public DbSet Blogs { get; set; } - public DbSet Posts { get; set; } -} -``` - -*** - -For more information on getting started with EF, consult the [EF getting started documentation](https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app?tabs=netcore-cli). - -## Additional Npgsql configuration - -The Npgsql EF provider is built on top of the lower-level Npgsql ADO.NET provider ([docs](https://www.npgsql.org/doc/index.html)); these two separate components support various options you may want to configure. - -If you're using EF 9.0 or above, the `UseNpgsql()` is a single point where you can configure everything related to Npgsql. For example: - -```csharp -builder.Services.AddDbContextPool(opt => - opt.UseNpgsql( - builder.Configuration.GetConnectionString("BloggingContext"), - o => o - .SetPostgresVersion(13, 0) - .UseNodaTime() - .MapEnum("mood"))); -``` - -The above configures the EF provider to produce SQL for PostgreSQL version 13 (avoiding newer incompatible features), adds a plugin allowing use of NodaTime for date/time type mapping, and maps a .NET enum type. Note that the last two also require configuration at the lower-level ADO.NET layer, which the code above does for you automatically. - -If you need to configure something at the lower-level ADO.NET layer, use `ConfigureDataSource()` as follows: - -```csharp -builder.Services.AddDbContextPool(opt => - opt.UseNpgsql( - builder.Configuration.GetConnectionString("BloggingContext"), - o => o.ConfigureDataSource(dataSourceBuilder => dataSourceBuilder.UseClientCertificate(certificate)))); -``` - -`ConfigureDataSource()` provides access to a lower-level [`NpgsqlDataSourceBuilder`](../Npgsql/basic-usage.md#data-source) which you can use to configure all aspects of the Npgsql ADO.NET provider. - -> [!WARNING] -> The EF provider internally creates an NpgsqlDataSource and uses that; for most configuration (e.g. connection string), the provider knows to switch between NpgsqlDataSources automatically. -> However, it's not possible to detect configuration differences within the `ConfigureDataSource()`; as a result, avoid performing varying configuration inside `ConfigureDataSource()`, since you may -> get the wrong NpgsqlDataSource. If you find yourself needing to vary Npgsql ADO.NET configuration, create an external NpgsqlDataSource yourself with the desired configuration and pass that to -> `UseNpgsql()` as described below. - -### Using an external NpgsqlDataSource - -If you're using a version of EF prior to 9.0, the above configuration methods aren't available. You can still create an NpgsqlDataSource yourself, and then pass it to EF's `UseNpgsql()`: - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder(builder.Configuration.GetConnectionString("BloggingContext")); -dataSourceBuilder.MapEnum(); -dataSourceBuilder.UseNodaTime(); -var dataSource = dataSourceBuilder.Build(); - -builder.Services.AddDbContextPool(opt => opt - .UseNpgsql(dataSource, o => o - .SetPostgresVersion(13, 0) - .UseNodaTime() - .MapEnum("mood"))); -``` - -Note that when using an external NpgsqlDataSource, you need to configure mappings and plugins at both levels yourself - both on the NpgsqlDataSource and at the EF provider level. - -## Using an Existing Database (Database-First) - -The Npgsql EF Core provider also supports reverse-engineering a code model from an existing PostgreSQL database ("database-first"). To do so, use dotnet CLI to execute the following: - -```bash -dotnet ef dbcontext scaffold "Host=my_host;Database=my_db;Username=my_user;Password=my_pw" Npgsql.EntityFrameworkCore.PostgreSQL -``` diff --git a/conceptual/EFCore.PG/mapping/array.md b/conceptual/EFCore.PG/mapping/array.md deleted file mode 100644 index 15b72215..00000000 --- a/conceptual/EFCore.PG/mapping/array.md +++ /dev/null @@ -1,54 +0,0 @@ -# Array Type Mapping - -PostgreSQL has the unique feature of supporting [*array data types*](https://www.postgresql.org/docs/current/static/arrays.html). This allow you to conveniently and efficiently store several values in a single column, where in other database you'd typically resort to concatenating the values in a string or defining another table with a one-to-many relationship. - -> [!NOTE] -> Although PostgreSQL supports multidimensional arrays, these aren't yet supported by the EF Core provider. - -## Mapping arrays - -Simply define a regular .NET array or `List<>` property: - -```csharp -public class Post -{ - public int Id { get; set; } - public string Name { get; set; } - public string[] Tags { get; set; } - public List AlternativeTags { get; set; } -} -``` - -The provider will create `text[]` columns for the above two properties, and will properly detect changes in them - if you load an array and change one of its elements, calling `SaveChanges` will automatically update the row in the database accordingly. - -## Operation translation - -The provider can also translate CLR array operations to the corresponding SQL operation; this allows you to efficiently work with arrays by evaluating operations in the database and avoids pulling all the data. The following table lists the range operations that currently get translated; all these translations work both for .NET arrays (`int[]`) and for generic Lists (`List`). If you run into a missing operation, please open an issue. - -.NET | SQL | Notes ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---- -array[0] | [array\[1\]](https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING) | -array.Length / list.Count | [cardinality(array)](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) | -array.Skip(2) | [array\[3,\]](https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING) | Added in 8.0 -array.Take(2) | [array\[,2\]](https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING) | Added in 8.0 -array.Skip(1).Take(2) | [array\[2,3\]](https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING) | Added in 8.0 -array1 == array2 | [array1 = array2](https://www.postgresql.org/docs/current/static/arrays.html) | -array1.SequenceEqual(array2) | [array1 = array2](https://www.postgresql.org/docs/current/static/arrays.html) | -array1.Take(2).SequenceEqual(array2) | [array1\[:2\] = array2](https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING) | Added in 11.0; also supports Skip() and Skip().Take() -arrayNonColumn.Contains(element) | [element = ANY(arrayNonColumn)](https://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN21104) | Can use regular index -arrayColumn.Contains(element) | [arrayColumn @> ARRAY\[element\]](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) | Can use GIN index -array.Append(element) | [array_append(array, element)](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 -array.Where(i => i != 8) | [array_remove(array, value)](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 9.0 -array1.Concat(array2) | [array1 \|\| array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 -array.IndexOf(element) | [array_position(array, element) - 1](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 -array.IndexOf(element, startIndex) | [array_position(array, element, startIndex + 1) - 1](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 -String.Join(separator, array) | [array_to_string(array, separator, '')](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) | Added in 6.0 -array.Any() | [cardinality(array) > 0](https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) | -array1.Intersect(array2).Any() | [array1 && array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) | Added in 8.0 -array1.Any(i => array2.Contains(i)) | [array1 && array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) | -array1.All(i => array2.Contains(i)) | [array1 <@ array2](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE) | -array.Any(s => EF.Functions.Like(string, s)) | [string LIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | -array.Any(s => EF.Functions.ILike(string, s)) | [string ILIKE ANY (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | -array.All(s => EF.Functions.Like(string, s)) | [string LIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | -array.All(s => EF.Functions.ILike(string, s)) | [string ILIKE ALL (array)](https://www.postgresql.org/docs/current/functions-comparisons.html#id-1.5.8.30.16) | -EF.Functions.ArrayAgg(values) | [array_agg(values)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | Added in 7.0, See [Aggregate functions](translations.md#aggregate-functions). diff --git a/conceptual/EFCore.PG/mapping/enum.md b/conceptual/EFCore.PG/mapping/enum.md deleted file mode 100644 index 301e77df..00000000 --- a/conceptual/EFCore.PG/mapping/enum.md +++ /dev/null @@ -1,126 +0,0 @@ -# Enum Type Mapping - -By default, any enum properties in your model will be mapped to database integers. EF Core 2.1 also allows you to map these to strings in the database with value converters. - -However, the Npgsql provider also allows you to map your CLR enums to [database enum types](https://www.postgresql.org/docs/current/static/datatype-enum.html). This option, unique to PostgreSQL, provides the best of both worlds: the enum is internally stored in the database as a number (minimal storage), but is handled like a string (more usable, no need to remember numeric values) and has type safety. - -## Setting up your enum with EF - -> [!NOTE] -> Enum mapping has changed considerably in EF 9.0. - -If you're using EF 9.0 or above, simply call `MapEnum` inside your `UseNpgsql` invocation. - -### [With a connection string](#tab/with-connection-string) - -If you're passing a connection string to `UseNpgsql`, simply add the `MapEnum` call as follows: - -```csharp -builder.Services.AddDbContext(options => options.UseNpgsql( - "", - o => o.MapEnum("mood"))); -``` - -This configures all aspects of Npgsql to use your `Mood` enum - both at the EF and the lower-level Npgsql layer - and ensures that the enum is created in the database in EF migrations. - -### [With an external NpgsqlDataSource](#tab/with-external-datasource) - -If you're creating an external NpgsqlDataSource and passing it to `UseNpgsql`, you must make sure to map your enum on that data independently of the EF-level setup: - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder(""); -dataSourceBuilder.MapEnum(); -var dataSource = dataSourceBuilder.Build(); - -builder.Services.AddDbContext(options => options.UseNpgsql( - dataSource, - o => o.MapEnum("mood"))); -``` - -*** - -### Older EF versions - -On versions of EF prior to 9.0, enum setup is more involved and consists of several steps; enum mapping has to be done at the lower-level Npgsql layer, and also requires explicit configuration in the EF model for creation in the database via migrations. - -#### Creating your database enum - -First, you must specify the PostgreSQL enum type on your model, just like you would with tables, sequences or other databases objects: - -```csharp -protected override void OnModelCreating(ModelBuilder builder) - => builder.HasPostgresEnum(); -``` - -This causes the EF Core provider to create your enum type, `mood`, with two labels: `happy` and `sad`. This will cause the appropriate migration to be created. - -#### Mapping your enum - -Even if your database enum is created, Npgsql has to know about it, and especially about your CLR enum type that should be mapped to it: - -##### [NpgsqlDataSource](#tab/with-datasource) - -Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. When using NpgsqlDataSource, map your enum when building your data source: - -```csharp -// Call MapEnum() when building your data source: -var dataSourceBuilder = new NpgsqlDataSourceBuilder(/* connection string */); -dataSourceBuilder.MapEnum(); -var dataSource = dataSourceBuilder.Build(); - -builder.Services.AddDbContext(options => options.UseNpgsql(dataSource)); -``` - -##### [Without NpgsqlDatasource](#tab/without-datasource) - -Since version 7.0, NpgsqlDataSource is the recommended way to use Npgsql. However, if you're not yet using NpgsqlDataSource, map enums by adding the following code, *before* any EF Core operations take place. An appropriate place for this is in the static constructor on your DbContext class: - -```csharp -static MyDbContext() - => NpgsqlConnection.GlobalTypeMapper.MapEnum(); -``` - -> [!NOTE] -> If you have multiple context types, all `MapEnum` invocations must be done before *any* of them is used; this means that the code cannot be in your static constructors, but must be moved to the program start. - -*** - -This code lets Npgsql know that your CLR enum type, `Mood`, should be mapped to a database enum called `mood`. Note that if your enum is in a custom schema (not `public`), you must specify that schema in the call to `MapEnum`. - -## Using enum properties - -Once your enum is properly set up with EF, you can use your CLR enum type just like any other property: - -```csharp -public class Blog -{ - public int Id { get; set; } - public Mood Mood { get; set; } -} - -using (var ctx = new MyDbContext()) -{ - // Insert - ctx.Blogs.Add(new Blog { Mood = Mood.Happy }); - ctx.Blogs.SaveChanges(); - - // Query - var blog = ctx.Blogs.Single(b => b.Mood == Mood.Happy); -} -``` - -## Altering enum definitions - -The Npgsql provider only allow adding new values to existing enums, and the appropriate migrations will be automatically created as you add values to your CLR enum type. However, PostgreSQL itself doesn't support removing enum values (since these may be in use), and while renaming values is supported, it isn't automatically done by the provider to avoid using unreliable detection heuristics. Renaming an enum value can be done by including [raw SQL](https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/managing?tabs=dotnet-core-cli#arbitrary-changes-via-raw-sql) in your migrations as follows: - -```csharp -migrationBuilder.Sql("ALTER TYPE mood RENAME VALUE 'happy' TO 'thrilled';"); -``` - -As always, test your migrations carefully before running them on production databases. - -## Scaffolding from an existing database - -If you're creating your model from an existing database, the provider will recognize enums in your database, and scaffold the appropriate `HasPostgresEnum()` lines in your model. However, the scaffolding process has no knowledge of your CLR type, and will therefore skip your enum columns (warnings will be logged). You will have to create the CLR type and perform the proper setup as described above. - -In the future it may be possible to scaffold the actual enum type (and with it the properties), but this isn't supported at the moment. diff --git a/conceptual/EFCore.PG/mapping/full-text-search.md b/conceptual/EFCore.PG/mapping/full-text-search.md deleted file mode 100644 index 890573fc..00000000 --- a/conceptual/EFCore.PG/mapping/full-text-search.md +++ /dev/null @@ -1,133 +0,0 @@ -# Full Text Search - -PostgreSQL has [built-in support for full-text search](https://www.postgresql.org/docs/current/static/textsearch.html), which allows you to conveniently and efficiently query natural language documents. - -## Mapping - -PostgreSQL full text search types are mapped onto .NET types built-in to Npgsql. The `tsvector` type is mapped to `NpgsqlTsVector` and `tsquery` is mapped to `NpgsqlTsQuery`. This means you can use properties of type `NpgsqlTsVector` directly in your model to create `tsvector` columns. The `NpgsqlTsQuery` type on the other hand, is used in LINQ queries. - -```csharp -public class Product -{ - public int Id { get; set; } - public string Title { get; set; } - public string Description { get; set; } - public NpgsqlTsVector SearchVector { get; set; } -} -``` - -## Setting up and querying a full text search index on an entity - -[As the PostgreSQL documentation explains](https://www.postgresql.org/docs/current/static/textsearch-tables.html), full-text search requires an index to run efficiently. This section will show two ways to do this, each having its benefits and drawbacks. Please read the PostgreSQL docs for more information on the two different approaches. - -### Method 1: tsvector column - -This method adds a `tsvector` column to your table, that is automatically updated when the row is modified. First, add an `NpgsqlTsVector` property to your entity: - -```csharp -public class Product -{ - public int Id { get; set; } - public string Name { get; set; } - public string Description { get; set; } - public NpgsqlTsVector SearchVector { get; set; } -} -``` - -Then, configure the property to be a [stored generated column](../modeling/generated-properties.md#computed-generated-columns): the provider has an API for setting that up: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity() - .HasGeneratedTsVectorColumn( - p => p.SearchVector, - "english", // Text search config - p => new { p.Name, p.Description }) // Included properties - .HasIndex(p => p.SearchVector) - .HasMethod("GIN"); // Index method on the search vector (GIN or GIST) -} -``` - -Note that `HasGeneratedTsVectorColumn()` is simply a bit of sugar of EF's standard `HasComputedColumnSql()`; if there's anything you need which isn't covered by `HasGeneratedTsVectorColumn()`, simply use `HasComputedColumnSql()`. - -Once your generated `tsvector` column is set up, any inserts or updates on the `Products` table will update the `SearchVector` column and maintain it automatically. You can query it as follows: - -```csharp -var context = new ProductDbContext(); -var npgsql = context.Products - .Where(p => p.SearchVector.Matches("Npgsql")) - .ToList(); -``` - -### Method 2: Expression index - -If you prefer to have an expression index rather than a generated column, use the following API to do so: - -```csharp -modelBuilder.Entity() - .HasIndex(b => new { b.Title, b.Description }) - .HasMethod("GIN") - .IsTsVectorExpressionIndex("english"); -``` - -Once the index is created on the `Title` and `Description` columns, you can query as follows: - -```csharp -var context = new ProductDbContext(); -var npgsql = context.Products - .Where(p => EF.Functions.ToTsVector("english", p.Title + " " + p.Description) - .Matches("Npgsql")) - .ToList(); -``` - -## Computed column over JSON columns - -The provider can also create computed `tsvector` columns over JSON columns. Simply use `HasGeneratedTsVectorColumn()` as shown above, and when applied to JSON columns, the provider will automatically generate [`json_to_tsvector/jsonb_to_tsvector`](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) as appropriate. - -Note that this will pass the filter `all` to these functions, meaning that all values in the JSON document will be included. To customize the filter - or to create the computed column on older versions of the provider - simply specify the function yourself via [`HasComputedColumnSql`](https://docs.microsoft.com/ef/core/modeling/generated-properties?tabs=data-annotations#computed-generated-columns). - -## Operation translation - -Almost all PostgreSQL full text search functions can be called through LINQ queries. All supported EF Core LINQ methods are defined in extension classes in the `Microsoft.EntityFrameworkCore` namespace, so simply referencing the Npgsql provider will light up these methods. The following table lists all supported operations; if an operation you need is missing, please open an issue to request for it. - -.NET | SQL -----------------------------------------------------------------------------|----- -EF.Functions.ToTsVector(string) | [to_tsvector(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) -EF.Functions.ToTsVector("english", string) | [to_tsvector('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-DOCUMENTS) -EF.Functions.ToTsQuery(string) | [to_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.ToTsQuery("english", string ) | [to_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.PlainToTsQuery(string) | [plainto_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.PlainToTsQuery("english", string) | [plainto_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.PhraseToTsQuery(string) | [phraseto_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.PhraseToTsQuery("english", string) | [phraseto_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.WebSearchToTsQuery(string) | [websearch_to_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.WebSearchToTsQuery("english", string) | [websearch_to_tsquery('english'::regconfig, string)](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -EF.Functions.ArrayToTsVector(new[] { "a", "b" }) | [array_to_tsvector(ARRAY\['a', 'b'\])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) -NpgsqlTsVector.Parse(string) | [CAST(string AS tsvector)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) -NpgsqlTsQuery.Parse(string) | [CAST(queryString AS tsquery)](https://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS) -tsvector.Matches(string) | [tsvector @@ plainto_tsquery(string)](https://www.postgresql.org/docs/current/static/textsearch-intro.html#TEXTSEARCH-MATCHING) -tsvector.Matches(tsquery) | [tsvector @@ tsquery](https://www.postgresql.org/docs/current/static/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES) -tsquery1.And(tsquery2) | [tsquery1 && tsquery2](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) -tsquery1.Or(tsquery2) | [tsquery1 \|\| tsquery2](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) -tsquery.ToNegative() | [!! tsquery](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) -tsquery1.Contains(tsquery2) | [tsquery1 @> tsquery2](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) -tsquery1.IscontainedIn(tsquery2) | [tsquery1 <@ tsquery2](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) -tsquery.GetNodeCount() | [numnode(query)](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) -tsquery.GetQueryTree() | [querytree(query)](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSQUERY) -tsquery.GetResultHeadline("a b c") | [ts_headline('a b c', query)](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-HEADLINE) -tsquery.GetResultHeadline("a b c", "MinWords=1, MaxWords=2") | [ts_headline('a b c', query, 'MinWords=1, MaxWords=2')](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-HEADLINE) -tsquery.Rewrite(targetQuery, substituteQuery) | [ts_rewrite(to_tsquery(tsquery), to_tsquery(targetQuery), to_tsquery(substituteQuery))](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) -tsquery1.ToPhrase(tsquery2) | [tsquery_phrase(tsquery1, tsquery2)](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) -tsquery1.ToPhrase(tsquery2, distance) | [tsquery_phrase(tsquery1, tsquery2, distance)](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) -tsvector1.Concat(tsvector2) | [tsvector1 \|\| tsvector2](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-OPERATORS-TABLE) -tsvector.Delete("x") | [ts_delete(tsvector, 'x')](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) -tsvector.Delete(new[] { "x", "y" }) | [ts_delete(tsvector, ARRAY\['x', 'y'\])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) -tsvector.Filter(new[] { "x", "y" }) | [ts_filter(tsvector, ARRAY\['x', 'y'\])](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) -tsvector.GetLength() | [length(tsvector)](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) -tsvector.Rank(tsquery) | [ts_rank(tsvector, tsquery)](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING) -tsvector.RankCoverDensity(tsquery) | [ts_rank_cd(tsvector, tsquery)](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING) -tsvector.SetWeight(NpgsqlTsVector.Lexeme.Weight.A) | [setweight(tsvector, 'A')](https://www.postgresql.org/docs/current/static/textsearch-features.html#TEXTSEARCH-MANIPULATE-TSVECTOR) -tsvector.ToStripped() | [strip(tsvector)](https://www.postgresql.org/docs/current/functions-textsearch.html#TEXTSEARCH-FUNCTIONS-TABLE) -EF.Functions.Unaccent(string) | [unaccent(string)](https://www.postgresql.org/docs/current/unaccent.html) -EF.Functions.Unaccent(regdictionary, string) | [unaccent(regdictionary, string)](https://www.postgresql.org/docs/current/unaccent.html) diff --git a/conceptual/EFCore.PG/mapping/general.md b/conceptual/EFCore.PG/mapping/general.md deleted file mode 100644 index 7734fe39..00000000 --- a/conceptual/EFCore.PG/mapping/general.md +++ /dev/null @@ -1,41 +0,0 @@ -# Type mapping - -The EF Core provider transparently maps the types supported by Npgsql at the ADO.NET level - see [the Npgsql ADO type mapping page](/doc/types/basic.html). - -This means that you can use PostgreSQL-specific types, such as `inet` or `circle`, directly in your entities. Simply define your properties just as if they were a simple type, such as a `string`: - -```csharp -public class MyEntity -{ - public int Id { get; set; } - public string Name { get; set; } - public IPAddress IPAddress { get; set; } - public NpgsqlCircle Circle { get; set; } - public int[] SomeInts { get; set; } -} -``` - -Special types such as [arrays](array.md) and [enums](enum.md) have their own documentation pages with more details. - -[PostgreSQL composite types](https://www.postgresql.org/docs/current/static/rowtypes.html), while supported at the ADO.NET level, aren't yet supported in the EF Core provider. This is tracked by [#22](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/22). - -## Explicitly specifying data types - -In some cases, your .NET property type can be mapped to several PostgreSQL data types; a good example is a `string`, which will be mapped to `text` by default, but can also be mapped to `jsonb`. You can use either Data Annotation attributes or the Fluent API to configure the PostgreSQL data type: - -## [Data Annotations](#tab/data-annotations) - -```csharp -[Column(TypeName="jsonb")] -public string SomeStringProperty { get; set; } -``` - -## [Fluent API](#tab/fluent-api) - -```csharp -builder.Entity() - .Property(b => b.SomeStringProperty) - .HasColumnType("jsonb"); -``` - -*** diff --git a/conceptual/EFCore.PG/mapping/json.md b/conceptual/EFCore.PG/mapping/json.md deleted file mode 100644 index 09df8eef..00000000 --- a/conceptual/EFCore.PG/mapping/json.md +++ /dev/null @@ -1,340 +0,0 @@ -# JSON Mapping - -> [!NOTE] -> Version 8.0 of the Npgsql provider introduced support for EF's [JSON columns](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#json-columns), using `ToJson()`. That is the recommended way to map POCOs going forward. - -PostgreSQL has rich, built-in support for storing JSON columns and efficiently performing complex queries operations on them. Newcomers can read more about the PostgreSQL support on [the JSON types page](https://www.postgresql.org/docs/current/datatype-json.html), and on the [functions and operators page](https://www.postgresql.org/docs/current/functions-json.html). Note that the below mapping mechanisms support both the `jsonb` and `json` types, although the former is almost always preferred for efficiency reasons. - -The Npgsql EF Core provider allows you to map PostgreSQL JSON columns in three different ways: - -1. As simple strings -2. As EF owned entities -3. As System.Text.Json DOM types (JsonDocument or JsonElement, [see docs](https://learn.microsoft.com/dotnet/standard/serialization/system-text-json/use-dom#use-jsondocument)) -4. As strongly-typed user-defined types (POCOs) (deprecated) - -## String mapping - -The simplest form of mapping to JSON is via a regular string property, just like an ordinary text column: - -### [Data Annotations](#tab/data-annotations) - -```csharp -public class SomeEntity -{ - public int Id { get; set; } - [Column(TypeName = "jsonb")] - public string Customer { get; set; } -} -``` - -### [Fluent API](#tab/fluent-api) - -```csharp -class MyContext : DbContext -{ - public DbSet SomeEntities { get; set; } - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity() - .Property(b => b.Customer) - .HasColumnType("jsonb"); - } -} - -public class SomeEntity -{ - public int Id { get; set; } - public string Customer { get; set; } -} -``` - -*** - -With string mapping, the EF Core provider will save and load properties to database JSON columns, but will not do any further serialization or parsing - it's the developer's responsibility to handle the JSON contents, possibly using System.Text.Json to parse them. This mapping approach is more limited compared to the others. - -## POCO mapping - -If your column JSON contains documents with a stable schema, you can map them to your own .NET types (or POCOs); EF will use System.Text.Json APIs under the hood to serialize instances of your types to JSON documents before sending them to the database, and to deserialize documents coming back from the database. This effectively allows mapping an arbitrary .NET type - or object graph - to a single column in the database. - -As of EF 10, the recommended way to map .NET types to JSON in the database is via complex types ([see EF release notes](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-10.0/whatsnew#json)). In this mode, EF is fully aware of the structure of your JSON document - just like it's aware of your tables and columns - and provides powerful, rich querying and updating capabilities. Prior to EF 10, similar modeling was available via the "owned entity" concept, but this modeling created several issues ([see here for more details](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-10.0/whatsnew#json)). If you're using EF 10 or above, complex types are the recommended way to map .NET types. - -As an 3rd alternative, prior to version 8.0, the Npgsql EF provider has supported JSON POCO mapping by simply delegating serialization/deserialization to System.Text.Json; in this mode, EF itself is oblivious to the contents of the JSON document, and cannot take that structure into account for queries and updates. This approach can now be considered deprecated as it allows for less powerful mapping and supports less query types; using complex types with `ToJson()` is now the recommended way to map POCOs to JSON. - -### EF modeling with ToJson (recommended) - -Npgsql's support for `ToJson()` is fully aligned with the general EF support; see the [EF documentation for more information](https://learn.microsoft.com/ef/core/what-is-new/ef-core-10.0/whatsnew#json). - -To get you started quickly, assume that we have the following Customer type, with a Details property that we want to map to a single JSON column in the database: - -```csharp -public class Customer -{ - public int Id { get; set; } - public CustomerDetails Details { get; set; } -} - -public class CustomerDetails // Map to a JSON column in the table -{ - public string Name { get; set; } - public int Age { get; set; } - public List Orders { get; set; } -} - -public class Order // Part of the JSON column -{ - public decimal Price { get; set; } - public string ShippingAddress { get; set; } -} -``` - -To instruct EF to map CustomerDetails - and within it, Order - to a JSON column, configure it as follows: - -#### [Complex types (EF10+)](#tab/complex-types) - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity() - .ComplexProperty(c => c.Details, d => d.ToJson()); -} -``` - -#### [Owned entities](#tab/owned-entities) - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity() - .OwnsOne(c => c.Details, d => - { - d.ToJson(); - d.OwnsMany(d => d.Orders); - }); -} -``` - -*** - -At this point you can interact with the Customer just like you would normally, and EF will seamlessly serialize and deserialize it to a JSON column in the database. You can also perform LINQ queries which reference properties inside the JSON document, and these will get translated to SQL. - -### Legacy POCO mapping (deprecated) - -Before version 8.0 introduced support for EF's ToJson (owned entity mapping), the provider had its own support for JSON POCO mapping, by simply delegating serialization/deserialization to System.Text.Json; in this model, EF itself model the contents of the JSON document, and cannot take that structure into account for queries and updates. This approach can now be considered deprecated as it allows for less powerful mapping and supports less query types; using ToJson() is now the recommended way to map POCOs to JSON. - -To use legacy POCO mapping, configure a property a mapping to map to a `jsonb` column as follows: - -#### [Data Annotations](#tab/data-annotations) - -```csharp -public class Customer -{ - public int Id { get; set; } - [Column(TypeName = "jsonb")] - public CustomerDetails Details { get; set; } -} - -public class CustomerDetails // Mapped to a JSON column in the table -{ - public string Name { get; set; } - public int Age { get; set; } - public Order[] Orders { get; set; } -} - -public class Order // Part of the JSON column -{ - public decimal Price { get; set; } - public string ShippingAddress { get; set; } -} -``` - -#### [Fluent API](#tab/fluent-api) - -```csharp -class MyContext : DbContext -{ - public DbSet SomeEntities { get; set; } - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity() - .Property(b => b.Customer) - .HasColumnType("jsonb"); - } -} - -public class SomeEntity // Mapped to a database table -{ - public int Id { get; set; } - public Customer Customer { get; set; } -} - -public class Customer // Mapped to a JSON column in the table -{ - public string Name { get; set; } - public int Age { get; set; } - public Order[] Orders { get; set; } -} - -public class Order // Part of the JSON column -{ - [JsonPropertyName("OrderPrice")] // Controls the JSON property name - public decimal Price { get; set; } - public string ShippingAddress { get; set; } -} -``` - -Note that when using this mapping, only limited forms of LINQ querying is supported; it's recommended to switch to ToJson() for full LINQ querying capabilities. The querying supported by traditional POCO mapping is documented [below](#querying-traditional-and-dom). - -*** - -## JsonDocument DOM mapping - -If your column JSON schema isn't stable, a strongly-typed POCO mapping may not be appropriate. The Npgsql provider also allows you to map the DOM document type provided by [System.Text.Json APIs](https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/). - -```csharp -public class SomeEntity : IDisposable -{ - public int Id { get; set; } - public JsonDocument Customer { get; set; } - - public void Dispose() => Customer?.Dispose(); -} -``` - -Note that neither a data annotation nor the fluent API are required, as [JsonDocument](https://docs.microsoft.com/dotnet/api/system.text.json.jsondocument) is automatically recognized and mapped to `jsonb`. Note also that `JsonDocument` is disposable, so the entity type is made disposable as well; not dispose the `JsonDocument` will result in the memory not being returned to the pool, which will increase GC impact across various parts of the framework. - -Once a document is loaded from the database, you can traverse it: - -```csharp -var someEntity = context.Entities.First(); -Console.WriteLine(someEntity.Customer.RootElement.GetProperty("Orders")[0].GetProperty("Price").GetInt32()); -``` - -Note that when using this mapping, only limited forms of LINQ querying is supported; [see below](#querying-traditional-and-dom) for more details. - -## Querying JSON columns (DOM and legacy POCO) - -> [!NOTE] -> The below does not apply if you are using ToJson (owned entity mapping). ToJson mapping supports far more querying patterns than both legacy POCO and DOM and should be preferred. - -Saving and loading documents these documents wouldn't be much use without the ability to query them. You can express your queries via the same LINQ constructs you are already using in EF Core: - -### [JsonDocument Mapping](#tab/jsondocument) - -```csharp -var joes = context.CustomerEntries - .Where(e => e.Customer.RootElement.GetProperty("Name").GetString() == "Joe") - .ToList(); -``` - -### [Legacy POCO Mapping](#tab/poco) - -```csharp -var joes = context.CustomerEntries - .Where(e => e.Customer.Name == "Joe") - .ToList(); -``` - -*** - -The provider will recognize the traversal of a JSON document, and translate it to the correspond PostgreSQL JSON traversal operator, producing the following PostgreSQL-specific SQL: - -```sql -SELECT c.""Id"", c.""Customer"" -FROM ""CustomerEntries"" AS c -WHERE c.""Customer""->>'Name' = 'Joe' -``` - -[If indexes are set up properly](#indexing-json-columns), this can result in very efficient, server evaluation of searches with database JSON documents. - -The following expression types and functions are translated: - -### [JsonDocument Mapping](#tab/jsondocument) - -.NET | SQL -------------------------------------------------------------------------------------- | ---- -customer.RootElement.GetProperty("Name").GetString() | [customer->>'Name' = 'Joe'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.RootElement.GetProperty("Orders")[1].GetProperty("Price").GetInt32() | [CAST(customer #>> '{Orders,1,Price}' AS integer) = 8](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.RootElement.GetProperty("Orders").GetArrayLength() | [jsonb_array_length(customer->'Orders'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) -EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}")1 | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", customer)1 | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExists(customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistAny(customer, "Age", "Address") | [customer ?\| ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistAll(customer, "Age", "Address") | [customer ?& ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonTypeof(customer.GetProperty("Age")) == "number" | [jsonb_typeof(customer->'Age') = 'number'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) - -### [Legacy POCO Mapping](#tab/poco) - -.NET | SQL ---------------------------------------------------------------------------------------- | ---- -customer.Name | [customer->>'Name'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.Orders[1].Price | [customer#>>'{Orders,0,Price}'\[1\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE) -customer.Orders.Length (or Count) | [jsonb_array_length(customer->'Orders')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) -EF.Functions.JsonContains(customer, @"{""Name"": ""Joe"", ""Age"": 25}")1 | [customer @> '{"Name": "Joe", "Age": 25}'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer)1 | ['{"Name": "Joe", "Age": 25}' <@ customer](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExists(e.Customer, "Age") | [customer ? 'Age'](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistAny(e.Customer, "Age", "Address") | [customer ?\| ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonExistAll(e.Customer, "Age", "Address") | [customer ?& ARRAY\['Age','Address'\]](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) -EF.Functions.JsonTypeof(e.Customer.Age) | [jsonb_typeof(customer->'Age')](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) - -*** - -1 JSON functions which accept a .NET object will not accept .NET scalar values. For example, to pass a scalar to `JsonContains` wrap it in a `JsonElement` or alternatively wrap it in a string. Note: a root level JSON string value requires quotes and escaping `@"""Joe"""`, just as any nested JSON string value would. - -## Indexing JSON columns - -Choose an index based on the operators used by your queries: targeted B-tree expression indexes support comparisons on extracted scalar values, while GIN indexes support matching containment, key-existence and JSON-path predicates over `jsonb` values. - -### Indexing members with ToJson - -> [!NOTE] -> Indexing JSON members was introduced in EF 11. - -You can use the existing `HasIndex` APIs to index members of complex types mapped with `ToJson()`. Using the Customer model above: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity(b => - { - b.ComplexProperty(c => c.Details, d => d.ToJson()); - - b.HasIndex(c => c.Details.Name).IsUnique(); - b.HasIndex(c => new { c.Details.Name, c.Details.Age }); - b.HasIndex(c => c.Details.Orders[0].Price); - }); -} -``` - -By default, these produce B-tree expression indexes over the selected members, not indexes over the entire JSON document. The expressions extract values with the same conversions as LINQ queries; for example, `Name` is extracted as text, while `Age` is cast to an integer. These indexes can support equality and range comparisons, ordering, and uniqueness where applicable. - -Nested paths, configured JSON property names, fixed collection positions (such as `Orders[0].Price`) and array values themselves are supported. Composite member indexes must refer to the same JSON column. Existing index options, such as sort order and the [PostgreSQL-specific index configuration](../modeling/indexes.md), also apply. - -The following limitations apply: - -* Wildcard traversal to descendants of all collection elements is not supported; selecting a fixed position does not index that member in every element. -* EF does not allow combining JSON member keys with regular column keys or members from multiple JSON columns, or creating unique indexes over entire JSON complex objects. -* Nested JSON member indexes cannot be combined with `IsTsVectorExpressionIndex`. -* PostgreSQL requires index expressions to be `IMMUTABLE`. Some native date/time and enum casts are not immutable, so PostgreSQL rejects indexes whose expressions require those casts. - -### GIN indexes - -Whole-document GIN indexes remain supported as before. You can also explicitly select GIN for an array or subdocument within a `jsonb` column: - -```csharp -modelBuilder.Entity() - .HasIndex(c => c.Details) - .HasMethod("gin"); - -modelBuilder.Entity() - .HasIndex(c => c.Details.Orders) - .HasMethod("gin") - .HasOperators("jsonb_path_ops"); -``` - -A whole-document GIN index can cover predicates on many properties, while a targeted index covers a selected expression. Queries must use matching expressions and operators: a GIN index on the document does not accelerate ordinary comparisons on extracted scalars, such as `c.Details.Age > 18`. Similarly, an index on `Details.Orders` serves supported predicates on that array, not arbitrary comparisons on each order's `Price`. - -The default `jsonb_ops` GIN operator class supports containment, key-existence and JSON-path operators. The alternative `jsonb_path_ops` supports containment and JSON-path operators, but not key-existence operators (`?`, `?|`, `?&`). A document-wide GIN index is not necessarily smaller or cheaper to maintain than targeted B-tree indexes; choose based on your queries and workload. - -See [PostgreSQL's JSON indexing documentation](https://www.postgresql.org/docs/current/datatype-json.html#JSON-INDEXING) for details on supported operators and index tradeoffs. diff --git a/conceptual/EFCore.PG/mapping/nodatime.md b/conceptual/EFCore.PG/mapping/nodatime.md deleted file mode 100644 index d17b8ef4..00000000 --- a/conceptual/EFCore.PG/mapping/nodatime.md +++ /dev/null @@ -1,140 +0,0 @@ -# Date/Time Mapping with NodaTime - -## What is NodaTime - -By default, [the PostgreSQL date/time types](https://www.postgresql.org/docs/current/static/datatype-datetime.html) are mapped to the built-in .NET types (`DateTime`, `TimeSpan`). Unfortunately, these built-in types are flawed in many ways. The [NodaTime library](http://nodatime.org/) was created to solve many of these problems, and if your application handles dates and times in anything but the most basic way, you should consider using it. To learn more [read this blog post by Jon Skeet](http://blog.nodatime.org/2011/08/what-wrong-with-datetime-anyway.html). - -Beyond NodaTime's general advantages, some specific advantages NodaTime for PostgreSQL date/time mapping include: - -* NodaTime defines some types which are missing from the BCL, such as `LocalDate`, `LocalTime`, and `OffsetTime`. These cleanly correspond to PostgreSQL `date`, `time` and `timetz`. -* `Period` is much more suitable for mapping PostgreSQL `interval` than `TimeSpan`. -* NodaTime types can fully represent PostgreSQL's microsecond precision, and can represent dates outside the BCL's date limit (1AD-9999AD). - -## Setup - -To set up the NodaTime plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime) to your project. Then, configure the NodaTime plugin as follows: - -### [EF 9.0, with a connection string](#tab/ef9-with-connection-string) - -If you're passing a connection string to `UseNpgsql`, simply add the `UseNodaTime` call as follows: - -```csharp -builder.Services.AddDbContext(options => options.UseNpgsql( - "", - o => o.UseNodaTime())); -``` - -This configures all aspects of Npgsql to use the NodaTime plugin - both at the EF and the lower-level Npgsql layer. - -### [With an external NpgsqlDataSource](#tab/with-datasource) - -If you're creating an external NpgsqlDataSource and passing it to `UseNpgsql`, you must call `UseNodaTime` on your NpgsqlDataSourceBuilder independently of the EF-level setup: - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder(""); -dataSourceBuilder.UseNodaTime(); -var dataSource = dataSourceBuilder.Build(); - -builder.Services.AddDbContext(options => options.UseNpgsql( - dataSource, - o => o.UseNodaTime())); -``` - -### [Older EF versions, with a connection string](#tab/legacy-with-connection-string) - -```csharp -// Configure UseNodaTime at the ADO.NET level. -// This code must be placed at the beginning of your application, before any other Npgsql API is called; an appropriate place for this is in the static constructor on your DbContext class: -static MyDbContext() - => NpgsqlConnection.GlobalTypeMapper.UseNodaTime(); - -// Then, when configuring EF Core with UseNpgsql(), call UseNodaTime(): -builder.Services.AddDbContext(options => - options.UseNpgsql("", o => o.UseNodaTime())); -``` - -*** - -The above sets up all the necessary mappings and operation translators. You can now use NodaTime types as regular properties in your entities, and even perform some operations: - -```csharp -public class Post -{ - public int Id { get; set; } - public string Name { get; set; } - public Instant CreationTime { get; set; } -} - -var recentPosts = context.Posts.Where(p => p.CreationTime > someInstant); -``` - -## Operation translation - -The provider knows how to translate many members and methods on mapped NodaTime types. For example, the following query will be translated to SQL and evaluated server-side: - -```csharp -// Get all events which occurred on a Monday -var mondayEvents = context.Events.Where(p => p.SomeDate.DayOfWeek == DayOfWeek.Monday); - -// Get all events which occurred before the year 2000 -var oldEvents = context.Events.Where(p => p.SomeDate.Year < 2000); -``` - -Following is the list of supported NodaTime translations; If an operation you need is missing, please open an issue to request for it. - -Starting with version 11.0, `EF.Functions.DateTrunc()` supports `LocalDateTime`, `Instant`, `ZonedDateTime`, `Period` and `Duration`. Its optional time zone argument is only supported for `Instant` and `ZonedDateTime` mapped to `timestamp with time zone`; without that argument, PostgreSQL uses the session time zone for these values. - -.NET | SQL | Notes --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ----------- -SystemClock.Instance.GetCurrentInstant() | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | -EF.Functions.DateTrunc("month", value) | [date_trunc('month', value)](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 11.0 -EF.Functions.DateTrunc("month", instant, "Europe/Berlin") | [date_trunc('month', instant, 'Europe/Berlin')](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 11.0 -LocalDateTime.Date | [date_trunc('day', timestamp)](https://www.postgresql.org/docs/current/functions-datetime.html) | -LocalDateTime.Second (also LocalTime, ZonedDateTime) | [date_part('second', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -LocalDateTime.Minute (also LocalTime, ZonedDateTime) | [date_part('minute', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -LocalDateTime.Hour (also LocalTime, ZonedDateTime) | [date_part('hour', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -LocalDateTime.Day, (also LocalDate, ZonedDateTime) | [date_part('day', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -LocalDateTime.Month (also LocalDate, ZonedDateTime) | [date_part('month', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -LocalDateTime.Year (also LocalDate, ZonedDateTime) | [date_part('year', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -LocalDateTime.DayOfWeek (also LocalDate, ZonedDateTime) | [floor(date_part('dow', timestamp))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -LocalDateTime.DayOfYear (also LocalDate, ZonedDateTime) | [date_part('doy', timestamp)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -LocalDate.At(time) | [date + time](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 10.0 -LocalDate.AtMidnight() | [date + '00:00:00'](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 10.0 -Period.Seconds (also Duration) | [date_part('second', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -Period.Minutes (also Duration) | [date_part('minute', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -Period.Hours (also Duration) | [date_part('hour', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -Period.Days (also Duration) | [date_part('day', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -Period.Months | [date_part('month', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -Period.Years | [date_part('year', interval)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -Period.FromSeconds | [make_interval(seconds => int)](https://www.postgresql.org/docs/current/functions-datetime.html) | -Period.FromMinutes | [make_interval(minutes => int)](https://www.postgresql.org/docs/current/functions-datetime.html) | -Period.FromHours | [make_interval(hours => int)](https://www.postgresql.org/docs/current/functions-datetime.html) | -Period.FromDays | [make_interval(days => int)](https://www.postgresql.org/docs/current/functions-datetime.html) | -Period.FromWeeks | [make_interval(weeks => int)](https://www.postgresql.org/docs/current/functions-datetime.html) | -Period.FromMonths | [make_interval(months => int)](https://www.postgresql.org/docs/current/functions-datetime.html) | -Period.FromYears | [make_interval(years => int)](https://www.postgresql.org/docs/current/functions-datetime.html) | -Duration.TotalMilliseconds | [date_part('epoch', interval) / 0.001](https://www.postgresql.org/docs/current/functions-datetime.html) | -Duration.TotalSeconds | [date_part('epoch', interval)](https://www.postgresql.org/docs/current/functions-datetime.html) | -Duration.TotalMinutes | [date_part('epoch', interval) / 60.0](https://www.postgresql.org/docs/current/functions-datetime.html) | -Duration.TotalDays | [date_part('epoch', interval) / 86400.0](https://www.postgresql.org/docs/current/functions-datetime.html) | -Duration.TotalHours | [date_part('epoch', interval) / 3600.0](https://www.postgresql.org/docs/current/functions-datetime.html) | -ZonedDateTime.LocalDateTime | [timestamptz AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | -DateInterval.Length | [upper(daterange) - lower(daterange)](https://www.postgresql.org/docs/current/functions-range.html) | -DateInterval.Start | [lower(daterange)](https://www.postgresql.org/docs/current/functions-range.html) | -DateInterval.End | [upper(daterange) - INTERVAL 'P1D'](https://www.postgresql.org/docs/current/functions-range.html) | -DateInterval.Contains(LocalDate) | [daterange @> date](https://www.postgresql.org/docs/current/functions-range.html) | -DateInterval.Contains(DateInterval) | [daterange @> daterange](https://www.postgresql.org/docs/current/functions-range.html) | -DateInterval.Intersection(DateInterval) | [daterange * daterange](https://www.postgresql.org/docs/current/functions-range.html) | -DateInterval.Union(DateInterval) | [daterange + daterange](https://www.postgresql.org/docs/current/functions-range.html) | -Instant.InZone(DateTimeZoneProviders.Tzdb["Europe/Berlin"]).LocalDateTime | [timestamptz AT TIME ZONE 'Europe/Berlin'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | -LocalDateTime.InZoneLeniently(DateTimeZoneProviders.Tzdb["Europe/Berlin"]).ToInstant() | [timestamp AT TIME ZONE 'Europe/Berlin'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | -ZonedDateTime.ToInstant | No PG operation (.NET-side conversion from ZonedDateTime to Instant only) | -Instant.InUtc | No PG operation (.NET-side conversion from Instant to ZonedDateTime only) | -Instant.ToDateTimeUtc | No PG operation (.NET-side conversion from Instant to UTC DateTime only) | -LocalDateTime.ToDateTimeUnspecified() | No PG operation (timestamp without time zone is unchanged) | Added in 11.0 -EF.Functions.Sum(periods) | [sum(periods)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](translations.md#aggregate-functions). -EF.Functions.Sum(durations) | [sum(durations)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](translations.md#aggregate-functions). -EF.Functions.Average(periods) | [avg(durations)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](translations.md#aggregate-functions). -EF.Functions.Average(durations) | [avg(durations)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](translations.md#aggregate-functions). - -In addition to the above, most arithmetic operators are also translated (e.g. LocalDate + Period). diff --git a/conceptual/EFCore.PG/mapping/nts.md b/conceptual/EFCore.PG/mapping/nts.md deleted file mode 100644 index 57401136..00000000 --- a/conceptual/EFCore.PG/mapping/nts.md +++ /dev/null @@ -1,194 +0,0 @@ -# Spatial Mapping with NetTopologySuite - -> [!NOTE] -> It's recommended that you start by reading the general [Entity Framework Core docs on spatial support](https://docs.microsoft.com/ef/core/modeling/spatial). - -PostgreSQL supports spatial data and operations via [the PostGIS extension](https://postgis.net/), which is a mature and feature-rich database spatial implementation. .NET doesn't provide a standard spatial library, but [NetTopologySuite](https://github.com/NetTopologySuite/NetTopologySuite) is a leading spatial library. The Npgsql EF Core provider has a plugin which allows you to map the NTS types to PostGIS columns, allowing seamless reading and writing. This is the recommended way to interact with spatial types in Npgsql. - -Note that the EF Core NetTopologySuite plugin depends on [the Npgsql ADO.NET NetTopology plugin](http://www.npgsql.org/doc/types/nts.html), which provides NetTopologySuite support at the lower level. - -## Setup - -To use the NetTopologySuite plugin, add the [Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite nuget](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite) to your project. Then, configure the NetTopologySuite plugin as follows: - -### [EF 9.0, with a connection string](#tab/ef9-with-connection-string) - -If you're passing a connection string to `UseNpgsql`, simply add the `UseNetTopologySuite` call as follows: - -```csharp -builder.Services.AddDbContext(options => options.UseNpgsql( - "", - o => o.UseNetTopologySuite())); -``` - -This configures all aspects of Npgsql to use the NetTopologySuite plugin - both at the EF and the lower-level Npgsql layer. - -### [With an external NpgsqlDataSource](#tab/with-datasource) - -If you're creating an external NpgsqlDataSource and passing it to `UseNpgsql`, you must call `UseNetTopologySuite` on your NpgsqlDataSourceBuilder independently of the EF-level setup: - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder(""); -dataSourceBuilder.UseNetTopologySuite(); -var dataSource = dataSourceBuilder.Build(); - -builder.Services.AddDbContext(options => options.UseNpgsql( - dataSource, - o => o.UseNetTopologySuite())); -``` - -### [Older EF versions, with a connection string](#tab/legacy-with-connection-string) - -```csharp -// Configure NetTopologySuite at the ADO.NET level. -// This code must be placed at the beginning of your application, before any other Npgsql API is called; an appropriate place for this is in the static constructor on your DbContext class: -static MyDbContext() - => NpgsqlConnection.GlobalTypeMapper.UseNetTopologySuite(); - -// Then, when configuring EF Core with UseNpgsql(), call UseNetTopologySuite(): -builder.Services.AddDbContext(options => - options.UseNpgsql("", o => o.UseNetTopologySuite())); -``` - -*** - -The above sets up all the necessary EF mappings and operation translators. If you're using EF 6.0, you also need to make sure that the PostGIS extension is installed in your database (later versions do this automatically). Add the following to your DbContext: - -```csharp -protected override void OnModelCreating(ModelBuilder builder) -{ - builder.HasPostgresExtension("postgis"); -} -``` - -At this point spatial support is set up. You can now use NetTopologySuite types as regular properties in your entities, and even perform some operations: - -```csharp -public class City -{ - public int Id { get; set; } - public string Name { get; set; } - public Point Location { get; set; } -} - -var nearbyCities = context.Cities.Where(c => c.Location.Distance(somePoint) < 100); -``` - -## Constraining your type names - -With the code above, the provider will create a database column of type `geometry`. This is perfectly fine, but be aware that this type accepts any geometry type (point, polygon...), with any coordinate system (XY, XYZ...). It's good practice to constrain the column to the exact type of data you will be storing, but unfortunately the provider isn't aware of your required coordinate system and therefore can't do that for you. Consider explicitly specifying your column types on your properties as follows: - -```csharp -[Column(TypeName="geometry (point)")] -public Point Location { get; set; } -``` - -This will constrain your column to XY points only. The same can be done via the fluent API with `HasColumnType()`. - -## Geography (geodetic) support - -PostGIS has two types: `geometry` (for Cartesian coordinates) and `geography` (for geodetic or spherical coordinates). You can read about the geometry/geography distinction [in the PostGIS docs](https://postgis.net/docs/manual-2.4/using_postgis_dbmanagement.html#PostGIS_Geography) or in [this blog post](http://workshops.boundlessgeo.com/postgis-intro/geography.html). In a nutshell, `geography` is much more accurate when doing calculations over long distances, but is more expensive computationally and supports only a small subset of the spatial operations supported by `geometry`. - -The Npgsql provider will be default map all NetTopologySuite types to PostGIS `geometry`. However, you can instruct it to map certain properties to `geography` instead: - -```csharp -protected override void OnModelCreating(ModelBuilder builder) -{ - builder.Entity().Property(b => b.Location).HasColumnType("geography (point)"); -} -``` - -or via an attribute: - -```csharp -public class City -{ - public int Id { get; set; } - public string Name { get; set; } - [Column(TypeName="geography")] - public Point Location { get; set; } -} -``` - -Once you do this, your column will be created as `geography`, and spatial operations will behave as expected. - -## Operation translation - -The following table lists NetTopologySuite operations which are translated to PostGIS SQL operations. This allows you to use these NetTopologySuite methods and members efficiently - evaluation will happen on the server side. Since evaluation happens at the server, table data doesn't need to be transferred to the client (saving bandwidth), and in some cases indexes can be used to speed things up. - -Note that the plugin is far from covering all spatial operations. If an operation you need is missing, please open an issue to request for it. - -.NET | SQL | Notes ----------------------------------------------------------------- |------------------------------------------------------------------------------------- | ----- -geom.Area() | [ST_Area(geom)](https://postgis.net/docs/ST_Area.html) -geom.AsBinary() | [ST_AsBinary(geom)](https://postgis.net/docs/ST_AsBinary.html) -geom.AsText() | [ST_AsText(geom)](https://postgis.net/docs/ST_AsText.html) -geom.Boundary | [ST_Boundary(geom)](https://postgis.net/docs/ST_Boundary.html) -geom.Buffer(d) | [ST_Buffer(geom,d)](https://postgis.net/docs/ST_Buffer.html) -geom.Centroid | [ST_Centroid(geom)](https://postgis.net/docs/ST_Centroid.html) -geom1.Contains(geom2) | [ST_Contains(geom1, geom2)](https://postgis.net/docs/ST_Contains.html) -geomCollection.Count | [ST_NumGeometries(geom1)](https://postgis.net/docs/ST_NumGeometries.html) -linestring.Count | [ST_NumPoints(linestring)](https://postgis.net/docs/ST_NumPoints.html) -geom1.ConvexHull() | [ST_ConvexHull(geom1)](https://postgis.net/docs/ST_ConvexHull.html) -geom1.Covers(geom2) | [ST_Covers(geom1, geom2)](https://postgis.net/docs/ST_Covers.html) -geom1.CoveredBy(geom2) | [ST_CoveredBy(geom1, geom2)](https://postgis.net/docs/ST_CoveredBy.html) -geom1.Crosses(geom2) | [ST_Crosses(geom1, geom2)](https://postgis.net/docs/ST_Crosses.html) -geom1.Difference(geom2) | [ST_Difference(geom1, geom2)](https://postgis.net/docs/ST_Difference.html) -geom1.Dimension | [ST_Dimension(geom1)](https://postgis.net/docs/ST_Dimension.html) -geom1.Disjoint(geom2) | [ST_Disjoint(geom1, geom2)](https://postgis.net/docs/ST_Disjoint.html) -geom1.Distance(geom2) | [ST_Distance(geom1, geom2)](https://postgis.net/docs/ST_Distance.html) -EF.Functions.DistanceKnn(geom1, geom2) | [geom1 <-> geom2](https://postgis.net/docs/geometry_distance_knn.html) -EF.Functions.Distance(geom1, geom2, useSpheriod) | [ST_Distance(geom1, geom2, useSpheriod)](https://postgis.net/docs/ST_Distance.html) -geom1.Envelope | [ST_Envelope(geom1)](https://postgis.net/docs/ST_Envelope.html) -geom1.ExactEquals(geom2) | [ST_OrderingEquals(geom1, geom2)](https://postgis.net/docs/ST_OrderingEquals.html) -lineString.EndPoint | [ST_EndPoint(lineString)](https://postgis.net/docs/ST_EndPoint.html) -polygon.ExteriorRing | [ST_ExteriorRing(polygon)](https://postgis.net/docs/ST_ExteriorRing.html) -geom1.Equals(geom2) | [geom1 = geom2](https://postgis.net/docs/ST_Geometry_EQ.html) -geom1.Polygon.EqualsExact(geom2) | [geom1 = geom2](https://postgis.net/docs/ST_Geometry_EQ.html) -geom1.EqualsTopologically(geom2) | [ST_Equals(geom1, geom2)](https://postgis.net/docs/ST_Equals.html) -EF.Functions.Force2D | [ST_Force2D(geom)](https://postgis.net/docs/ST_Force2D.html) -geom.GeometryType | [GeometryType(geom)](https://postgis.net/docs/GeometryType.html) -geomCollection.GetGeometryN(i) | [ST_GeometryN(geomCollection, i)](https://postgis.net/docs/ST_GeometryN.html) -linestring.GetPointN(i) | [ST_PointN(linestring, i)](https://postgis.net/docs/ST_PointN.html) -geom1.Intersection(geom2) | [ST_Intersection(geom1, geom2)](https://postgis.net/docs/ST_Intersection.html) -geom1.Intersects(geom2) | [ST_Intersects(geom1, geom2)](https://postgis.net/docs/ST_Intersects.html) -EF.Functions.IntersectsBbox(geom1, geom2) | [geom1 && geom2](https://postgis.net/docs/geometry_overlaps.html) | Added in 11.0 -geom.InteriorPoint | [ST_PointOnSurface(geom)](https://postgis.net/docs/ST_PointOnSurface.html) -lineString.IsClosed() | [ST_IsClosed(lineString)](https://postgis.net/docs/ST_IsClosed.html) -geomCollection.IsEmpty() | [ST_IsEmpty(geomCollection)](https://postgis.net/docs/ST_IsEmpty.html) -linestring.IsRing | [ST_IsRing(linestring)](https://postgis.net/docs/ST_IsRing.html) -geom.IsWithinDistance(geom2,d) | [ST_DWithin(geom1, geom2, d)](https://postgis.net/docs/ST_DWithin.html) -EF.Functions.IsWithinDistance(geom1, geom2, d, useSpheriod) | [ST_DWithin(geom1, geom2, d, useSpheriod)](https://postgis.net/docs/ST_DWithin.html) -geom.IsSimple() | [ST_IsSimple(geom)](https://postgis.net/docs/ST_IsSimple.html) -geom.IsValid() | [ST_IsValid(geom)](https://postgis.net/docs/ST_IsValid.html) -lineString.Length | [ST_Length(lineString)](https://postgis.net/docs/ST_Length.html) -EF.Functions.LineInterpolatePoint(lineString, fraction) | [ST_LineInterpolatePoint(lineString, fraction)](https://postgis.net/docs/ST_LineInterpolatePoint.html) | Added in 11.0 -EF.Functions.LineMerge(geom) | [ST_LineMerge(geom)](https://postgis.net/docs/ST_LineMerge.html) | Added in 11.0 -geom.Normalized | [ST_Normalize(geom)](https://postgis.net/docs/ST_Normalize.html) -geomCollection.NumGeometries | [ST_NumGeometries(geomCollection)](https://postgis.net/docs/ST_NumGeometries.html) -polygon.NumInteriorRings | [ST_NumInteriorRings(polygon)](https://postgis.net/docs/ST_NumInteriorRings.html) -lineString.NumPoints | [ST_NumPoints(lineString)](https://postgis.net/docs/ST_NumPoints.html) -geom1.Overlaps(geom2) | [ST_Overlaps(geom1, geom2)](https://postgis.net/docs/ST_Overlaps.html) -geom.PointOnSurface | [ST_PointOnSurface(geom)](https://postgis.net/docs/ST_PointOnSurface.html) -geom1.Relate(geom2) | [ST_Relate(geom1, geom2)](https://postgis.net/docs/ST_Relate.html) -geom.Reverse() | [ST_Reverse(geom)](https://postgis.net/docs/ST_Reverse.html) -EF.Functions.Scale(geom, xFactor, yFactor) | [ST_Scale(geom, xFactor, yFactor)](https://postgis.net/docs/ST_Scale.html) | Added in 11.0 -EF.Functions.Scale(geom, xFactor, yFactor, zFactor) | [ST_Scale(geom, xFactor, yFactor, zFactor)](https://postgis.net/docs/ST_Scale.html) | Added in 11.0 -EF.Functions.SetSrid(geom, srid) | [ST_SetSRID(geom, srid)](https://postgis.net/docs/ST_SetSRID.html) | Added in 11.0 -geom1.SRID | [ST_SRID(geom1)](https://postgis.net/docs/ST_SRID.html) -lineString.StartPoint | [ST_StartPoint(lineString)](https://postgis.net/docs/ST_StartPoint.html) -geom1.SymmetricDifference(geom2) | [ST_SymDifference(geom1, geom2)](https://postgis.net/docs/ST_SymDifference.html) -geom.ToBinary() | [ST_AsBinary(geom)](https://postgis.net/docs/ST_AsBinary.html) -geom.ToText() | [ST_AsText(geom)](https://postgis.net/docs/ST_AsText.html) -geom1.Touches(geom2) | [ST_Touches(geom1, geom2)](https://postgis.net/docs/ST_Touches.html) -EF.Functions.Transform(geom, srid) | [ST_Transform(geom, srid)](https://postgis.net/docs/ST_Transform.html) -geom1.Union(geom2) | [ST_Union(geom1, geom2)](https://postgis.net/docs/ST_Union.html) -geom1.Within(geom2) | [ST_Within(geom1, geom2)](https://postgis.net/docs/ST_Within.html) -point.M | [ST_M(point)](https://postgis.net/docs/ST_M.html) -point.X | [ST_X(point)](https://postgis.net/docs/ST_X.html) -point.Y | [ST_Y(point)](https://postgis.net/docs/ST_Y.html) -point.Z | [ST_Z(point)](https://postgis.net/docs/ST_Z.html) -UnaryUnionOp.Union(geometries) | [ST_Union(geometries)](https://postgis.net/docs/ST_Union.html) | See [Aggregate functions](translations.md#aggregate-functions). -GeometryCombiner.Combine(geometries) | [ST_Collect(geometries)](https://postgis.net/docs/ST_Collect.html) | See [Aggregate functions](translations.md#aggregate-functions). -EnvelopeCombiner.CombineAsGeometry(geometries) | [ST_Extent(geometries)::geometry](https://postgis.net/docs/ST_Extent.html) | See [Aggregate functions](translations.md#aggregate-functions). -ConvexHull.Create(geometries) | [ST_ConvexHull(geometries)](https://postgis.net/docs/ST_ConvexHull.html) | See [Aggregate functions](translations.md#aggregate-functions). diff --git a/conceptual/EFCore.PG/mapping/range.md b/conceptual/EFCore.PG/mapping/range.md deleted file mode 100644 index 80393c91..00000000 --- a/conceptual/EFCore.PG/mapping/range.md +++ /dev/null @@ -1,99 +0,0 @@ -# Ranges and Multiranges - -PostgreSQL has the unique feature of supporting [*range data types*](https://www.postgresql.org/docs/current/static/rangetypes.html). Ranges represent a range of numbers, dates or other data types, and allow you to easily query ranges which contain a value, perform set operations (e.g. query ranges which contain other ranges), and other similar operations. The range operations supported by PostgreSQL are listed [in this page](https://www.postgresql.org/docs/current/static/functions-range.html). The Npgsql EF Core provider allows you to seamlessly map PostgreSQL ranges, and even perform operations on them that get translated to SQL for server evaluation. - -In addition, PostgreSQL 14 introduced *multiranges*, which are basically sorted arrays of non-overlapping ranges with set-theoretic operations defined over them. Most range operators also work on multiranges, and they have a few functions of their own. - -## Ranges - -Npgsql maps PostgreSQL ranges to the generic CLR type `NpgsqlRange`: - -```csharp -public class Event -{ - public int Id { get; set; } - public string Name { get; set; } - public NpgsqlRange Duration { get; set; } -} -``` - -This will create a column of type `daterange` in your database. You can similarly have properties of type `NpgsqlRange`, `NpgsqlRange`, etc. - -## User-defined ranges - -PostgreSQL comes with 6 built-in ranges: `int4range`, `int8range`, `numrange`, `tsrange`, `tstzrange`, `daterange`; these can be used simply by adding the appropriate `NpgsqlRange` property in your entities as shown above. You can also define your own range types over arbitrary types, and use those in EF Core as well. - -To make the EF Core type mapper aware of your user-defined range, call the `MapRange()` method in your context's `OnConfiguring()` method as follows: - -```csharp -protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseNpgsql( - "", - options => options.MapRange("floatrange")); -``` - -This allows you to have properties of type `NpgsqlRange`, which will be mapped to PostgreSQL `floatrange`. - -The above does *not* create the `floatrange` type for you. In order to do that, include the following in your context's `OnModelCreating()`: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.HasPostgresRange("floatrange", "real"); -``` - -This will cause the appropriate [`CREATE TYPE ... AS RANGE`](https://www.postgresql.org/docs/current/static/sql-createtype.html) statement to be generated in your migrations, ensuring that your range is created and ready for use. Note that `HasPostgresRange()` supports additional parameters as supported by PostgreSQL `CREATE TYPE`. - -## Multiranges - -Npgsql maps arrays or lists of `NpgsqlRange` to PostgreSQL multiranges: - -```csharp -public class Store -{ - public int Id { get; set; } - public string Name { get; set; } - public NpgsqlRange[] OpeningTimes { get; set; } -} -``` - -## Operation translation - -Ranges can be queried via extensions methods on `NpgsqlRange`: - -```csharp -var events = context.Events.Where(p => p.Duration.Contains(someDate)); -``` - -This will translate to an SQL operation using the PostgreSQL `@>` operator, evaluating at the server and saving you from transferring the entire `Events` table to the client. Note that you can (and probably should) create indexes to make this operation more efficient, see the PostgreSQL docs for more info. - -The following table lists the range operations that currently get translated. Most operations work on both ranges and multiranges (starting with version 6.0.0); the multirange version is omitted for brevity. - -If you run into a missing operation, please open an issue. - -.NET | SQL ---------------------------------------|----- -range.LowerBound | [lower(range)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) -range.UpperBound | [upper(range)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) -range.LowerBoundIsInclusive | [lower_inc(range)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) -range.UpperBoundIsInclusive | [upper_inc(range)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) -range.LowerBoundIsInfinite | [lower_inf(range)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) -range.UpperBoundIsInfinite | [upper_inf(range)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) -range.IsEmpty | [isempty(range)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) -multirange.Any() | [NOT is_empty(multirange)](https://www.postgresql.org/docs/current/functions-range.html#MULTIRANGE-FUNCTIONS-TABLE) -range.Contains(i) | [range @> i](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -range1.Contains(range2) | [range @> range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -range1.ContainedBy(range2) | [range1 <@ range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -range1.Overlaps(range2) | [range1 && range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -range1.IsStrictlyLeftOf(range2) | [range1 << range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -range1.IsStrictlyRightOf(range2) | [range1 >> range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -range1.DoesNotExtendLeftOf(range2) | [range1 &> range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -range1.DoesNotExtendRightOf(range2) | [range1 <& range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -range1.IsAdjacentTo(range2) | [range1 -\|- range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -range1.Union(range2) | [range1 + range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -range1.Intersect(range2) | [range1 * range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -range1.Except(range2) | [range1 - range2](https://www.postgresql.org/docs/current/static/functions-range.html#RANGE-OPERATORS-TABLE) -range1.Merge(range2) | [range_merge(range1, range2)](https://www.postgresql.org/docs/current/functions-range.html#RANGE-FUNCTIONS-TABLE) -multirange.Merge() | [range_merge(multirange)](https://www.postgresql.org/docs/current/functions-range.html#MULTIRANGE-FUNCTIONS-TABLE) -ranges.RangeAgg() | [range_agg(ranges)](https://www.postgresql.org/docs/current/functions-aggregate.html) -ranges.RangeIntersectAgg() | [range_intersect_agg(ranges)](https://www.postgresql.org/docs/current/functions-aggregate.html) -multiranges.RangeIntersectAgg() | [range_intersect_agg(multiranges)](https://www.postgresql.org/docs/current/functions-aggregate.html) | See [Aggregate functions](translations.md#aggregate-functions). diff --git a/conceptual/EFCore.PG/mapping/translations.md b/conceptual/EFCore.PG/mapping/translations.md deleted file mode 100644 index f37f8d25..00000000 --- a/conceptual/EFCore.PG/mapping/translations.md +++ /dev/null @@ -1,430 +0,0 @@ -# Translations - -Entity Framework Core allows providers to translate query expressions to SQL for database evaluation. For example, PostgreSQL supports [regular expression operations](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP), and the Npgsql EF Core provider automatically translates .NET's [`Regex.IsMatch`](https://docs.microsoft.com/dotnet/api/system.text.regularexpressions.regex.ismatch) to use this feature. Since evaluation happens at the server, table data doesn't need to be transferred to the client (saving bandwidth), and in some cases indexes can be used to speed things up. The same C# code on other providers will trigger client evaluation. - -The Npgsql-specific translations are listed below. Some areas, such as [full-text search](full-text-search.md), have their own pages in this section which list additional translations. - -## String functions - -.NET | SQL | Notes -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------- -EF.Functions.Collate(operand, collation) | operand COLLATE collation -EF.Functions.Like(matchExpression, pattern) | matchExpression LIKE pattern -EF.Functions.Like(matchExpression, pattern, escapeCharacter) | matchExpression LIKE pattern ESCAPE escapeCharacter -EF.Functions.ILike(matchExpression, pattern) | [matchExpression ILIKE pattern](../misc/collations-and-case-sensitivity.md) -EF.Functions.ILike(matchExpression, pattern, escapeCharacter) | [matchExpression ILIKE pattern ESCAPE escapeCharacter](../misc/collations-and-case-sensitivity.md) -string.Compare(strA, strB) | CASE WHEN strA = strB THEN 0 ... END -string.Concat(str0, str1) | str0 \|\| str1 -string.IsNullOrEmpty(value) | value IS NULL OR value = '' -string.IsNullOrWhiteSpace(value) | value IS NULL OR btrim(value, E' \t\n\r') = '' -stringValue.CompareTo(strB) | CASE WHEN stringValue = strB THEN 0 ... END -stringValue.Contains(value) | stringValue LIKE %value% | char overload added in 11.0 -stringValue.EndsWith(value) | stringValue LIKE '%' \|\| value | char overload added in 11.0 -stringValue.FirstOrDefault() | substr(stringValue, 1, 1) -stringValue.IndexOf(value) | strpos(stringValue, value) - 1 | char overload added in 11.0 -stringValue.LastOrDefault() | substr(stringValue, length(stringValue), 1) -stringValue.Length | length(stringValue) -stringValue.PadLeft(length) | CASE WHEN length(stringValue) >= length THEN stringValue ELSE lpad(stringValue, length) END -stringValue.PadLeft(length, char) | CASE WHEN length(stringValue) >= length THEN stringValue ELSE lpad(stringValue, length, char) END -stringValue.PadRight(length) | CASE WHEN length(stringValue) >= length THEN stringValue ELSE rpad(stringValue, length) END -stringValue.PadRight(length, char) | CASE WHEN length(stringValue) >= length THEN stringValue ELSE rpad(stringValue, length, char) END -stringValue.Replace(oldValue, newValue) | replace(stringValue, oldValue, newValue) | char overload added in 11.0 -stringValue.StartsWith(value) | stringValue LIKE value \|\| '%' | char overload added in 11.0 -stringValue.Substring(startIndex, length) | substr(stringValue, startIndex + 1, @length) -stringValue.ToLower() | lower(stringValue) -stringValue.ToString() | stringValue | Null values remain null -stringValue.ToUpper() | upper(stringValue) -stringValue.Trim() | btrim(stringValue) -stringValue.Trim(trimChar) | btrim(stringValue, trimChar) -stringValue.TrimEnd() | rtrim(stringValue) -stringValue.TrimEnd(trimChar) | rtrim(stringValue, trimChar) -stringValue.TrimStart() | ltrim(stringValue) -stringValue.TrimStart(trimChar) | ltrim(stringValue, trimChar) -EF.Functions.Reverse(value) | reverse(value) -Regex.IsMatch(stringValue, "^A+") | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) | [1](#regex-note) -Regex.IsMatch(stringValue, "^A+", regexOptions) | [stringValue ~ '^A+'](http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP) (with options) | [1](#regex-note) -Regex.Replace(stringValue, pattern, replacement) | [regexp_replace(stringValue, pattern, replacement, 'pg')](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP) | [1](#regex-note) -Regex.Replace(stringValue, pattern, replacement, regexOptions) | [regexp_replace(stringValue, pattern, replacement, flags)](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP) | [1](#regex-note) -Regex.Count(stringValue, pattern) | [regexp_count(stringValue, pattern, 1, 'p')](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP) | [1](#regex-note) Requires PostgreSQL 15+ -Regex.Count(stringValue, pattern, regexOptions) | [regexp_count(stringValue, pattern, 1, flags)](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP) | [1](#regex-note) Requires PostgreSQL 15+ -string.Join(", ", a, b) | [concat_ws(', ', a, b)](https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER) -string.Join(", ", array) | [array_to_string(array, ', ', '')](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) -string.Join(", ", agg_strings) | [string_agg(agg_strings, ', ')](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](#aggregate-functions). -EF.Functions.StringToArray(s, "\|") | [string_agg(s, '\|')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) -EF.Functions.StringToArray(s, "\|", "FOO") | [string_agg(s, '\|', 'FOO')](https://www.postgresql.org/docs/current/functions-string.html#FUNCTION-STRING-TO-ARRAY) - -1 These translations use [PostgreSQL's regular expression syntax and semantics](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP), not .NET's. In particular, unless `RegexOptions.Singleline` is specified, negated character classes such as `[^x]` do not match LF (`\n`), unlike in .NET: `a[^x]b` matches `"a\nb"` in .NET but not in PostgreSQL. Use client-side evaluation when exact .NET semantics are required. - -`RegexOptions` arguments must be constant, and `RightToLeft` and `ECMAScript` are not supported. Only `IgnoreCase`, `Multiline`, `Singleline` and `IgnorePatternWhitespace` affect the generated SQL. Only the listed static overloads are translated; instance methods, overloads accepting a match timeout or `MatchEvaluator`, and other `Regex` methods are not translated. - -## Date and time functions - -> [!NOTE] -> Some of the operations below depend on the concept of a "local time zone" (e.g. `DateTime.Today`). While in .NET this is the machine time zone where .NET is running, the corresponding PostgreSQL translations use the [`TimeZone`](https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-TIMEZONE) connection parameter as the local time zone. -> -> Many of the below DateTime translations are also supported on `DateTimeOffset`. -> -> See also Npgsql's [NodaTime support](/efcore/mapping/nodatime.html), which is a better and safer way of interacting with date/time data. - -Starting with version 11.0, `EF.Functions.DateTrunc()` supports `DateTime`, `DateTimeOffset` and `TimeSpan`. The optional time zone argument is only supported for values mapped to `timestamp with time zone`; when omitted for such values, PostgreSQL uses the session time zone. - -.NET | SQL | Notes ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | -------- -DateTime.UtcNow (6.0+) | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | -DateTime.Now (6.0+) | [now()::timestamp](https://www.postgresql.org/docs/current/functions-datetime.html) | -DateTime.Today (6.0+) | [date_trunc('day', now()::timestamp)](https://www.postgresql.org/docs/current/functions-datetime.html) | -DateTime.UtcNow (legacy) | [now() AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html) | -DateTime.Now (legacy) | [now()](https://www.postgresql.org/docs/current/functions-datetime.html) | -DateTime.Today (legacy) | [date_trunc('day', now())](https://www.postgresql.org/docs/current/functions-datetime.html) | -EF.Functions.DateTrunc("month", value) | [date_trunc('month', value)](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 11.0 -EF.Functions.DateTrunc("month", utcDateTime, "Europe/Berlin") | [date_trunc('month', utcDateTime, 'Europe/Berlin')](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 11.0; timestamp with time zone only -dateTime.AddDays(1) | [dateTime + INTERVAL '1 days'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -dateTime.AddHours(value) | [dateTime + INTERVAL '1 hours'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -dateTime.AddMilliseconds(value) (also DateTimeOffset) | [dateTime + value * INTERVAL '1 milliseconds'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | Added in 11.0 -dateTime.AddMicroseconds(value) (also DateTimeOffset) | [dateTime + value * INTERVAL '1 microseconds'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | Added in 11.0 -dateTime.AddMinutes(1) | [dateTime + INTERVAL '1 minutes'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -dateTime.AddMonths(1) | [dateTime + INTERVAL '1 months'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -dateTime.AddSeconds(1) | [dateTime + INTERVAL '1 seconds'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -dateTime.AddYears(1) | [dateTime + INTERVAL '1 years'](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -dateTime.Date | [date_trunc('day', dateTime)](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.Day | [date_part('day', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.DayOfWeek | [floor(date_part('dow', dateTime))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.DayOfYear | [date_part('doy', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.Hour | [date_part('hour', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.Millisecond (also DateTimeOffset, TimeOnly) | [floor(date_part('milliseconds', dateTime))::INT % 1000](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 11.0 -dateTime.Microsecond (also DateTimeOffset, TimeOnly) | [date_part('microseconds', dateTime)::INT % 1000](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 11.0 -dateTime.Minute | [date_part('minute', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.Month | [date_part('month', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.Second | [date_part('second', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.Year | [date_part('year', dateTime)::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime.ToUniversalTime | [dateTime::timestamptz](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | -dateTime.ToLocalTime | [dateTime::timestamp](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | -dateOnly.DayNumber | [dateOnly - DATE '0001-01-01'](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 9.0 -DateOnly.FromDayNumber(x) | [DATE '0001-01-01' + x](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 9.0 -dateOnly1.DayNumber - dateOnly2.DayNumber | [dateOnly1 - dateOnly2](https://www.postgresql.org/docs/current/functions-datetime.html) | Added in 9.0 -dateTimeOffset.DateTime | [dateTimeOffset AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | -dateTimeOffset.UtcDateTime | No PG operation (.NET-side conversion from DateTimeOffset to DateTime only) | -dateTimeOffset.LocalDateTime | [dateTimeOffset::timestamp](https://www.postgresql.org/docs/current/datatype-datetime.html#id-1.5.7.13.18.7) | -timeSpan.Days | [floor(date_part('day', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.Hours | [floor(date_part('hour', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.Minutes | [floor(date_part('minute', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.Seconds | [floor(date_part('second', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.Milliseconds | [floor(date_part('millisecond', timeSpan))::INT](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.TotalMilliseconds | [date_part('epoch', interval) / 0.001](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.TotalSeconds | [date_part('epoch', interval)](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.TotalMinutes | [date_part('epoch', interval) / 60.0](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.TotalDays | [date_part('epoch', interval) / 86400.0](https://www.postgresql.org/docs/current/functions-datetime.html) | -timeSpan.TotalHours | [date_part('epoch', interval) / 3600.0](https://www.postgresql.org/docs/current/functions-datetime.html) | -dateTime1 - dateTime2 | [dateTime1 - dateTime2](https://www.postgresql.org/docs/current/functions-datetime.html#OPERATORS-DATETIME-TABLE) | -TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcDateTime, timezone) | [utcDateTime AT TIME ZONE timezone](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Only for timestamptz columns -TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTime, sourceTimeZoneId, destinationTimeZoneId) | [(dateTime AT TIME ZONE sourceTimeZoneId) AT TIME ZONE destinationTimeZoneId](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Added in 11.0. Requires timestamp without time zone input; returns timestamp without time zone (`DateTimeKind.Unspecified`), even for UTC destinations. Not supported for `DateTimeOffset`. -TimeZoneInfo.ConvertTimeToUtc(nonUtcDateTime) | [nonUtcDateTime::timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html) | Only for timestamp columns -DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) | [utcDateTime AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Only for timestamptz columns -DateTime.SpecifyKind(nonUtcDateTime, DateTimeKind.Utc) | [nonUtcDateTime AT TIME ZONE 'UTC'](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT) | Only for timestamp columns -new DateTime(year, month, day) | [make_date(year, month, day)](https://www.postgresql.org/docs/current/functions-datetime.html) | -new DateTime(y, m, d, h, m, s) | [make_timestamp(y, m, d, h, m, s)](https://www.postgresql.org/docs/current/functions-datetime.html) | -new DateTime(y, m, d, h, m, s, kind) | [make_timestamp or make_timestamptz](https://www.postgresql.org/docs/current/functions-datetime.html), based on `kind` | -EF.Functions.Sum(timespans) | [sum(timespans)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](#aggregate-functions). -EF.Functions.Average(timespans) | [avg(timespans)](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) | See [Aggregate functions](#aggregate-functions). - -## JSON functions - -See [JSON mapping](json.md) for mapping options and [PostgreSQL's JSON functions and operators](https://www.postgresql.org/docs/current/functions-json.html) for operator semantics. JSON aggregate functions are listed under [Aggregate functions](#aggregate-functions). - -.NET | SQL | Notes ------------------------------------------------ | ------------------------------------ | ----- -EF.Functions.JsonContains(json, contained) | json @> contained | jsonb only -EF.Functions.JsonContained(contained, json) | contained <@ json | jsonb only -EF.Functions.JsonExists(json, key) | json ? key | jsonb only -EF.Functions.JsonExistAny(json, key1, key2) | json ?\| ARRAY[key1, key2] | jsonb only -EF.Functions.JsonExistAll(json, key1, key2) | json ?& ARRAY[key1, key2] | jsonb only -EF.Functions.JsonTypeof(json) | jsonb_typeof(json) or json_typeof(json) | Selected according to the mapped column type -EF.Functions.JsonPathExists(json, "$.Age") | JSON_EXISTS(json, '$.Age') | Added in 11.0; requires PostgreSQL 17 or above - -## Hstore translations - -The following operations are supported for `Dictionary` and `ImmutableDictionary` mapped to PostgreSQL [`hstore`](https://www.postgresql.org/docs/current/hstore.html). Operations shown with `immutableDictionary` apply only to `ImmutableDictionary`. - -| .NET | SQL | Notes | -| ---- | --- | ----- | -| dictionary[key] | dictionary -> key | Added in 11.0 | -| dictionary.GetValueOrDefault(key) | dictionary -> key | Added in 11.0 | -| dictionary.GetValueOrDefault(key, fallback) | CASE WHEN dictionary ? key THEN dictionary -> key ELSE fallback END | Added in 11.0 | -| dictionary.ContainsKey(key) | dictionary ? key | Added in 11.0 | -| dictionary.ContainsValue(value) | array_position(avals(dictionary), value) IS NOT NULL | Added in 11.0 | -| dictionary.Count | cardinality(akeys(dictionary)) | Added in 11.0 | -| immutableDictionary.IsEmpty | cardinality(akeys(immutableDictionary)) = 0 | Added in 11.0 | -| immutableDictionary.Remove(key) | immutableDictionary - key | Added in 11.0 | -| immutableDictionary.RemoveRange(keys) | immutableDictionary - keys | Added in 11.0 | -| immutableDictionary.SetItems(otherDictionary) | immutableDictionary \|\| otherDictionary | Added in 11.0 | -| keys.All(key => dictionary.ContainsKey(key)) | dictionary ?& keys | Added in 11.0 | -| keys.Any(key => dictionary.ContainsKey(key)) | dictionary ?\| keys | Added in 11.0 | - -Lookups return SQL `NULL` for missing keys, stored NULL values and NULL hstores, rather than throwing for a missing key. The explicit `GetValueOrDefault` fallback distinguishes a missing key from a key whose stored value is NULL. Key existence and counts include stored-NULL entries, and `ContainsValue(null)` finds stored NULL values. - -`SetItems` accepts another hstore-mapped mutable or immutable dictionary, not arbitrary sequences of key/value pairs. - -## Miscellaneous functions - -.NET | SQL | Notes ----------------------------------------- | -------------------- | ----- -collection.Contains(item) | item IN collection -enumValue.HasFlag(flag) | enumValue & flag = flag -Guid.CreateVersion7() | [uuidv7()](https://www.postgresql.org/docs/current/functions-uuid.html) (added in 10 when targeting PG18, client-evaluated otherwise) -Guid.NewGuid() | [gen_random_uuid()](https://www.postgresql.org/docs/current/functions-uuid.html), or [uuid_generate_v4()](https://www.postgresql.org/docs/current/uuid-ossp.html) from [`uuid-ossp`](https://www.postgresql.org/docs/current/uuid-ossp.html) when targeting pre-PG13 -nullable.GetValueOrDefault() | coalesce(nullable, 0) -nullable.GetValueOrDefault(defaultValue) | coalesce(nullable, defaultValue) -bool.Parse(stringValue) | CAST(stringValue AS boolean) | Added in 11.0 -byte.Parse(stringValue) | CAST(stringValue AS smallint) | Added in 11.0 -short.Parse(stringValue) | CAST(stringValue AS smallint) | Added in 11.0 -int.Parse(stringValue) | CAST(stringValue AS integer) | Added in 11.0 -long.Parse(stringValue) | CAST(stringValue AS bigint) | Added in 11.0 -float.Parse(stringValue) | CAST(stringValue AS real) | Added in 11.0 -double.Parse(stringValue) | CAST(stringValue AS double precision) | Added in 11.0 -decimal.Parse(stringValue) | CAST(stringValue AS numeric) | Added in 11.0 - -## Binary functions - -.NET | SQL | Notes ----------------------------- | ------------------------------- | -------- -bytes[i] | get_byte(bytes, i) | -bytes.Contains(value) | position(value IN bytes) > 0 | -bytes.Any() | length(bytes) > 0 | Added in 11.0 -bytes.Concat(bytes2) | bytes \|\| bytes2 | Added in 11.0 -bytes.Length | length(@bytes) | -bytes1.SequenceEqual(bytes2) | @bytes = @second | -bitArray.Get(index) | get_bit(bitArray, index) = 1 | Added in 11.0 -bitArray[index] | get_bit(bitArray, index) = 1 | Added in 11.0 - -## Math functions - -.NET | SQL | Notes ------------------------ | ------------------ | ----- -Math.Abs(value) | abs(value) | -Math.Acos(d) | acos(d) | -Math.Asin(d) | asin(d) | -Math.Atan(d) | atan(d) | -Math.Atan2(y, x) | atan2(y, x) | -Math.Ceiling(d) | ceiling(d) | -Math.Cos(d) | cos(d) | -Math.Exp(d) | exp(d) | -Math.Floor(d) | floor(d) | -Math.Log(d) | ln(d) | -Math.Log10(d) | log(d) | -Math.Max(x, y) | greatest(x, y) | -Math.Min(x, y) | least(x, y) | -Math.Pow(x, y) | power(x, y) | -Math.Round(d) | round(d) | -Math.Round(d, decimals) | round(d, decimals) | -Math.Sin(a) | sin(a) | -Math.Sign(value) | sign(value)::int | -Math.Sqrt(d) | sqrt(d) | -Math.Tan(a) | tan(a) | -Math.Truncate(d) | trunc(d) | -EF.Functions.Random() | random() | - -See also [Aggregate statistics functions](#aggregate-functions). - -## Row value comparisons - -The following allow expressing [comparisons over SQL row values](https://www.postgresql.org/docs/current/functions-comparisons.html#ROW-WISE-COMPARISON). This are particularly useful for implementing efficient pagination, see [the EF Core docs](https://docs.microsoft.com/ef/core/querying/pagination) for more information. - -.NET | SQL ---------------------------------------------------------------------------------- | ---------------- -EF.Functions.GreaterThan(ValueTuple.Create(a, b), ValueTuple.Create(c, d)) | (a, b) > (c, d) -EF.Functions.LessThan(ValueTuple.Create(a, b), ValueTuple.Create(c, d)) | (a, b) < (c, d) -EF.Functions.GreaterThanOrEqual(ValueTuple.Create(a, b), ValueTuple.Create(c, d)) | (a, b) >= (c, d) -EF.Functions.LessThanOrEqual(ValueTuple.Create(a, b), ValueTuple.Create(c, d)) | (a, b) <= (c, d) -ValueTuple.Create(a, b).Equals(ValueTuple.Create(c, d)) | (a, b) = (c, d) -!ValueTuple.Create(a, b).Equals(ValueTuple.Create(c, d)) | (a, b) <> (c, d) - -## Network functions - -.NET | SQL ------------------------------------------------- | --- -IPAddress.Parse(string) | [CAST(string AS inet)](https://www.postgresql.org/docs/current/datatype-net-types.html#DATATYPE-INET) -PhysicalAddress.Parse(string) | [CAST(string AS macaddr)](https://www.postgresql.org/docs/current/datatype-net-types.html#DATATYPE-MACADDR) -EF.Functions.LessThan(net1, net2) | [net1 < net2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.LessThanOrEqual(net1, net2) | [net1 <= net2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.GreaterThan(net1, net2) | [net1 > net2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.GreaterThanOrEqual(net1, net2) | [net1 >= net2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.ContainedBy(inet1, inet2) | [inet1 << inet2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.ContainedByOrEqual(inet1, inet2) | [inet1 <<= inet2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.Contains(inet1, inet2) | [inet1 >> inet2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.ContainsOrEqual(inet1, inet2) | [inet1 >>= inet2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.ContainsOrContainedBy(inet1, inet2) | [inet1 && inet2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.BitwiseNot(net) | [~net1](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.BitwiseAnd(net1, net2) | [net1 & net2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.BitwiseOr(net1, net2) | [net1 \| net2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.Add(inet, int) | [inet + int](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.Subtract(inet, int) | [inet - int](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.Subtract(inet1, inet2) | [inet1 - inet2](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-OPERATORS-TABLE) -EF.Functions.Abbreviate(inet) | [abbrev(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.Abbreviate(cidr) | [abbrev(cidr)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.Broadcast(inet) | [broadcast(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.Family(inet) | [family(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.Host(inet) | [host(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.HostMark(inet) | [hostmask(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.MaskLength(inet) | [masklen(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.Netmask(inet) | [netmask(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.Network(inet) | [network(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.SetMaskLength(inet) | [set_masklen(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.SetMaskLength(cidr) | [set_masklen(cidr)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.Text(inet) | [text(inet)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.SameFamily(inet1, inet2) | [inet_same_family(inet1, inet2)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.Merge(inet1, inet2) | [inet_merge(inet1, inet2)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.Truncate(macaddr) | [trunc(macaddr)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) -EF.Functions.Set7BitMac8(macaddr8) | [macaddr8_set7bit(macaddr8)](https://www.postgresql.org/docs/current/functions-net.html#CIDR-INET-FUNCTIONS-TABLE) - -## Trigram functions - -The below translations provide functionality for determining the similarity of alphanumeric text based on trigram matching, using the [`pg_trgm`](https://www.postgresql.org/docs/current/pgtrgm.html) extension which is bundled with standard PostgreSQL distributions. All the below parameters are strings. - -.NET | SQL ------------------------------------------------------------------ | -------------------- -EF.Functions.TrigramsShow(s) | show_trgm(s) -EF.Functions.TrigramsSimilarity(s1, s2) | similarity(s1, s2) -EF.Functions.TrigramsWordSimilarity(s1, s2) | word_similarity(s1, s2) -EF.Functions.TrigramsStrictWordSimilarity(s1, s2) | strict_word_similarity(s1, s2) -EF.Functions.TrigramsAreSimilar(s1, s2) | s1 % s2 -EF.Functions.TrigramsAreWordSimilar(s1, s2) | s1 <% s2 -EF.Functions.TrigramsAreNotWordSimilar(s1, s2) | s1 %> s2 -EF.Functions.TrigramsAreStrictWordSimilar(s1, s2) | s1 <<% s2 -EF.Functions.TrigramsAreNotStrictWordSimilar(s1, s2) | s1 %>> s2 -EF.Functions.TrigramsSimilarityDistance(s1, s2) | s1 <-> s2 -EF.Functions.TrigramsWordSimilarityDistance(s1, s2) | s1 <<-> s2 -EF.Functions.TrigramsWordSimilarityDistanceInverted(s1, s2) | s1 <->> s2 -EF.Functions.TrigramsStrictWordSimilarityDistance(s1, s2) | s1 <<<-> s2 -EF.Functions.TrigramsStrictWordSimilarityDistanceInverted(s1, s2) | s1 <->>> s2 - -## Fuzzy string match functions - -The below translations provide functionality for determining similarities and distance between strings, using the [`fuzzystrmatch`](https://www.postgresql.org/docs/current/fuzzystrmatch.html) extension which is bundled with standard PostgreSQL distributions. - -.NET | SQL | Notes ------------------------------------------------------------------------------------------------------- | -------------------- | ----- -EF.Functions.FuzzyStringMatchSoundex(text) | [soundex(text)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-SOUNDEX) -EF.Functions.FuzzyStringMatchDifference(source, target) | [difference(source, target)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-SOUNDEX) -EF.Functions.FuzzyStringMatchDaitchMokotoff(text) | [daitch_mokotoff(text)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-DAITCH-MOKOTOFF) | Added in 11.0. Requires PostgreSQL 16+ -EF.Functions.FuzzyStringMatchLevenshtein(source, target) | [levenshtein(source, target)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-LEVENSHTEIN) -EF.Functions.FuzzyStringMatchLevenshtein(source, target, ins_cost, del_cost, sub_cost) | [levenshtein(source, target, ins_cost, del_cost, sub_cost)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-LEVENSHTEIN) -EF.Functions.FuzzyStringMatchLevenshteinLessEqual(source, target, max_d) | [levenshtein(source, target, max_d)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-LEVENSHTEIN) -EF.Functions.FuzzyStringMatchLevenshteinLessEqual(source, target, ins_cost, del_cost, sub_cost, max_d) | [levenshtein(source, target, ins_cost, del_cost, sub_cost, max_d)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-LEVENSHTEIN) -EF.Functions.FuzzyStringMatchMetaphone(text, max_output_length) | [metaphone(text, max_output_length)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-METAPHONE) -EF.Functions.FuzzyStringMatchDoubleMetaphone(text) | [dmetaphone(text)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-METAPHONE) -EF.Functions.FuzzyStringMatchDoubleMetaphoneAlt(text) | [dmetaphone_alt(text)](https://www.postgresql.org/docs/current/fuzzystrmatch.html#FUZZYSTRMATCH-METAPHONE) - -`FuzzyStringMatchDaitchMokotoff` returns `string[]?`, with `null` possible for inputs without encodable characters, including empty strings. Projection and array indexing are supported, but composing `Contains`, `Any`, `Intersect(...).Any()`, or `.Length` on the result is not currently translated ([dotnet/efcore#35980](https://github.com/dotnet/efcore/issues/35980)). - -## LTree functions - -The below translations are for working with label trees from the PostgreSQL [`ltree`](https://www.postgresql.org/docs/current/ltree.html) extension. Use the type to represent ltree and invoke methods on it in EF Core LINQ queries. - -.NET | SQL ------------------------------------------------------------------ | -------------------- -ltree1.IsAncestorOf(ltree2) | ltree1 @> ltree2 -ltree1.IsDescendantOf(ltree2) | ltree1 <@ ltree2 -ltree.MatchesLQuery(lquery) | ltree ~ lquery -ltree.MatchesLTxtQuery(ltxtquery) | ltree @ ltxtquery -lqueries.Any(q => ltree.MatchesLQuery(q)) | ltree ? lqueries -ltrees.Any(t => t.IsAncestorOf(ltree)) | ltrees @> ltree -ltrees.Any(t => t.IsDescendantOf(ltree)) | ltrees <@ ltree -ltrees.Any(t => t.MatchesLQuery(lquery)) | ltrees ~ ltree -ltrees.Any(t => t.MatchesLTxtQuery(ltxtquery)) | ltrees @ ltxtquery -ltrees.Any(t => lqueries.Any(q => t.MatchesLQuery(q))) | ltrees ? lqueries -ltrees.FirstOrDefault(l => l.IsAncestorOf(ltree)) | ltrees ?@> ltree -ltrees.FirstOrDefault(l => l.IsDescendantOf(ltree)) | ltrees ?<@ ltree -ltrees.FirstOrDefault(l => l.MatchesLQuery(lquery)) | ltrees ?~ ltree -ltrees.FirstOrDefault(l => l.MatchesLTxtQuery(ltxtquery)) | ltrees ?@ ltree -ltree.Subtree(0, 1) | subltree(ltree, 0, 1) -ltree.Subpath(0, 1) | sublpath(ltree, 0, 1) -ltree.Subpath(2) | sublpath(ltree, 2) -ltree.NLevel | nlevel(ltree) -ltree.Index(subpath) | index(ltree, subpath) -ltree.Index(subpath, 2) | index(ltree, subpath, 2) -LTree.LongestCommonAncestor(ltree1, ltree2) | lca(index(ltree1, ltree2) - -## Cube functions - -The below translations are for working with cubes from the PostgreSQL [`cube`](https://www.postgresql.org/docs/current/cube.html) extension. Use the type to represent cube and invoke methods on it in EF Core LINQ queries. - -.NET | SQL ------------------------------------ | -------------------- -cube1.Overlaps(cube2) | [cube1 && cube2](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) -cube1.Contains(cube2) | [cube1 @> cube2](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) -cube1.ContainedBy(cube2) | [cube1 <@ cube2](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) -cube.NthCoordinate(n) | [cube -> n + 1](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) -cube.NthCoordinateKnn(n) | [cube ~> n + 1](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) -cube1.Distance(cube2) | [cube1 <-> cube2](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) -cube1.DistanceTaxicab(cube2) | [cube1 <#> cube2](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) -cube1.DistanceChebyshev(cube2) | [cube1 <=> cube2](https://www.postgresql.org/docs/current/cube.html#CUBE-OPERATORS-TABLE) -cube1.Union(cube2) | [cube_union(cube1, cube2)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) -cube1.Intersect(cube2) | [cube_inter(cube1, cube2)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) -cube.Enlarge(r, n) | [cube_enlarge(cube, r, n)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) -cube.Dimensions | [cube_dim(cube)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) -cube.IsPoint | [cube_is_point(cube)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) -cube.ToSubset(indexes) | [cube_subset(cube, indexes + 1)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) -cube.LowerLeft[n] | [cube_ll_coord(cube, n + 1)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) -cube.UpperRight[n] | [cube_ur_coord(cube, n + 1)](https://www.postgresql.org/docs/current/cube.html#CUBE-FUNCTIONS-TABLE) - -## Aggregate functions - -The PostgreSQL aggregate functions are documented [here](https://www.postgresql.org/docs/current/functions-aggregate.html). - -| .NET | SQL -| ---------------------------------------------------------------------------------- | -------------------- -| string.Join(", ", agg_strings) | string_agg(agg_strings, ', ') -| EF.Functions.ArrayAgg(values) | array_agg(values) -| EF.Functions.JsonbAgg(values) | jsonb_agg(values) -| EF.Functions.JsonAgg(values) | json_agg(values) -| EF.Functions.Sum(timespans) | sum(timespans) -| EF.Functions.Average(timespans) | avg(timespans) -| EF.Functions.JsonObjectAgg(tuple_of_2) | json_object_agg(tuple_of_2.first, tuple_of_2.second) -| EF.Functions.JsonbObjectAgg(tuple_of_2) | jsonb_object_agg(tuple_of_2.first, tuple_of_2.second) -| ranges.RangeAgg() | range_agg(ranges) -| ranges.RangeIntersectAgg() | range_intersect_agg(ranges) -| multiranges.RangeIntersectAgg() | range_intersect_agg(multiranges) -| | -| EF.Functions.StandardDeviationSample(values) | stddev_samp(values) -| EF.Functions.StandardDeviationPopulation(values) | stddev_pop(values) -| EF.Functions.VarianceSample(values) | var_samp(values) -| EF.Functions.VariancePopulation(values) | var_pop(values) -| | -| EF.Functions.Correlation(tuple) | corr(tuple_of_2.first, tuple_of_2.second) -| EF.Functions.CovariancePopulation(tuple) | covar_pop(tuple_of_2.first, tuple_of_2.second) -| EF.Functions.CovarianceSample(tuple) | covar_samp(tuple_of_2.first, tuple_of_2.second) -| EF.Functions.RegrAverageX(tuple) | regr_avgx(tuple_of_2.first, tuple_of_2.second) -| EF.Functions.RegrAverageY(tuple) | regr_avgy(tuple_of_2.first, tuple_of_2.second) -| EF.Functions.RegrCount(tuple) | regr_count(tuple_of_2.first, tuple_of_2.second) -| EF.Functions.RegrIntercept(tuple) | regr_intercept(tuple_of_2.first, tuple_of_2.second) -| EF.Functions.RegrR2(tuple) | regr_r2(tuple_of_2.first, tuple_of_2.second) -| EF.Functions.RegrSlope(tuple) | regr_slope(tuple_of_2.first, tuple_of_2.second) -| EF.Functions.RegrSXX(tuple) | regr_sxx(tuple_of_2.first, tuple_of_2.second) -| EF.Functions.RegrSXY(tuple) | regr_sxy(tuple_of_2.first, tuple_of_2.second) - -Aggregate functions can be used as follows: - -```csharp -var query = ctx.Set() - .GroupBy(c => c.City) - .Select( - g => new - { - City = g.Key, - Companies = EF.Functions.ArrayAgg(g.Select(c => c.ContactName)) - }); -``` - -To use functions accepting a tuple_of_2, project out from the group as follows: - -```csharp -var query = ctx.Set() - .GroupBy(c => c.City) - .Select( - g => new - { - City = g.Key, - Companies = EF.Functions.JsonObjectAgg(g.Select(c => ValueTuple.Create(c.CompanyName, c.ContactName))) - }); -``` diff --git a/conceptual/EFCore.PG/mapping/vector-search.md b/conceptual/EFCore.PG/mapping/vector-search.md deleted file mode 100644 index 7094fea7..00000000 --- a/conceptual/EFCore.PG/mapping/vector-search.md +++ /dev/null @@ -1,91 +0,0 @@ -# Vector Search - -Vector search finds items whose vectors are close to a query vector. For example, an embedding model can represent text or images as vectors, allowing a search to find semantically similar items rather than just matching keywords. The query vector and stored vectors must be produced by the same embedding model. - -PostgreSQL supports vector search through the [pgvector extension](https://github.com/pgvector/pgvector). The [pgvector .NET library](https://github.com/pgvector/pgvector-dotnet#entity-framework-core) provides EF Core integration, including vector types and distance functions. - -## Setup - -Install the [Pgvector.EntityFrameworkCore](https://www.nuget.org/packages/Pgvector.EntityFrameworkCore) package. Version 0.3.0 supports EF Core 9, 10 and 11. For EF Core 8, use version 0.2.2 and its [setup instructions](https://github.com/pgvector/pgvector-dotnet/blob/efcore-v0.2.2/README.md#entity-framework-core); the setup below is for version 0.3.0. - -Configure the plugin when configuring your context: - -```csharp -using Microsoft.EntityFrameworkCore; -using Pgvector.EntityFrameworkCore; - -optionsBuilder.UseNpgsql("", o => o.UseVector()); -``` - -If you use an [external NpgsqlDataSource](../index.md#using-an-external-npgsqldatasource), configure vector support on the data source as well: - -```csharp -using Npgsql; - -var dataSourceBuilder = new NpgsqlDataSourceBuilder(""); -dataSourceBuilder.UseVector(); -var dataSource = dataSourceBuilder.Build(); - -optionsBuilder.UseNpgsql(dataSource, o => o.UseVector()); -``` - -Install the pgvector extension on your PostgreSQL server. To have EF migrations enable it in your database, add the following to your context: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.HasPostgresExtension("vector"); -} -``` - -## Model and query - -Define a vector property with the number of dimensions used by your embedding model: - -```csharp -using System.ComponentModel.DataAnnotations.Schema; -using Pgvector; - -public class Item -{ - public int Id { get; set; } - public string Name { get; set; } = null!; - - [Column(TypeName = "vector(3)")] - public Vector? Embedding { get; set; } -} -``` - -The following query orders items by Euclidean (L2) distance to a query embedding and returns the five closest. The three-dimensional vector is only an example; use an embedding generated by your model in a real application. - -```csharp -using Pgvector.EntityFrameworkCore; - -var embedding = new Vector(new float[] { 1, 1, 1 }); -var items = await context.Set() - .OrderBy(i => i.Embedding!.L2Distance(embedding)) - .Take(5) - .Select(i => new { i.Id, i.Name }) - .ToListAsync(); -``` - -The distance is computed in PostgreSQL; the projection avoids retrieving the stored vectors. pgvector also supports other distance metrics and approximate nearest-neighbor indexes; see the [pgvector documentation](https://github.com/pgvector/pgvector) and [EF Core examples](https://github.com/pgvector/pgvector-dotnet#entity-framework-core). - -> [!WARNING] -> By default, EF loads vector properties when materializing entities, even if you only need the other properties. Embeddings can be large, so this can unnecessarily transfer and allocate substantial amounts of data. Disable automatic loading as shown [below](#avoiding-loading-vectors), or project only the properties you need. - -## Avoiding loading vectors - -Starting with EF Core 11, you can disable automatic loading of a vector property when entities are queried: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.HasPostgresExtension("vector"); - modelBuilder.Entity().Property(i => i.Embedding).Metadata.IsAutoLoaded = false; -} -``` - -The property can still be used in server-side queries, such as the distance calculation above. It is not populated on materialized entities, and an unloaded property is excluded from updates unless modified. To retrieve a vector, project it separately, for example `Select(i => new { i.Id, i.Embedding })`. Selecting it alongside an entity does not populate that entity's property, nor does returning its column from `FromSql` ([EF Core issue](https://github.com/dotnet/efcore/issues/39398)). - -In EF Core 8, 9 and 10, `IsAutoLoaded` is not available. Instead, use projections like the example above to retrieve only the properties you need; queries that materialize an entity still load its vector property. diff --git a/conceptual/EFCore.PG/misc/collations-and-case-sensitivity.md b/conceptual/EFCore.PG/misc/collations-and-case-sensitivity.md deleted file mode 100644 index dfc4508e..00000000 --- a/conceptual/EFCore.PG/misc/collations-and-case-sensitivity.md +++ /dev/null @@ -1,108 +0,0 @@ -# Collations and Case Sensitivity - -> It's recommended that you start by reading [the general Entity Framework Core docs on collations and case sensitivity](https://docs.microsoft.com/ef/core/miscellaneous/collations-and-case-sensitivity). - -PostgreSQL is a case-sensitive database by default, but provides various possibilities for performing case-insensitive operations and working with collations. Depending on your PostgreSQL version, full collation support may be somewhat incomplete, so you may need to carefully review your options below and pick the one which suits you. - -## PostgreSQL collations - -PostgreSQL has full support for managing collations, and this is the recommended way for managing textual comparisons and sorting. However, note that ; support for non-deterministic collations - coverting case-insensitivity - was relatively limited in some ways. While recent versions such as PostgreSQL 18 support case-insensitive collations quite well, previous versions did not (for example, it was not possible perform pattern matching via LIKE on columns with a non-deterministic collation). Read more about PostgreSQL collation support [in the documentation](https://www.postgresql.org/docs/current/collation.html). - -### Creating a collation - -In PostgreSQL, collations are first-class, named database objects which can be created and dropped, just like tables. To create a collation, place the following in your context's `OnModelCreating`: - -```csharp -modelBuilder.HasCollation("my_collation", locale: "en-u-ks-primary", provider: "icu", deterministic: false); -``` - -This creates a collation with the name `my_collation`: this is an arbitrary name you can choose, which you will be specifying later when assigning the collation to columns. The rest of the parameters instruct PostgreSQL to create a non-deterministic, case-insensitive ICU collation. ICU collations are very powerful, and allow you to specify precise rules with regards to case, accents and other textual aspects. Consult [the ICU docs](https://unicode-org.github.io/icu/userguide/collation/) for more information on supported features and keywords. - -### Column collation - -Once a collation has been created in your database, you can specify it on columns: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.HasCollation("my_collation", locale: "en-u-ks-primary", provider: "icu", deterministic: false); - - modelBuilder.Entity().Property(c => c.Name) - .UseCollation("my_collation"); -} -``` - -This will cause all textual operators on this column to be case-insensitive. - -### Database collation - -PostgreSQL also allows you to specify collations at the database level, when it is created: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.UseCollation(""); -} -``` - -Unfortunately, the database collation is quite limited in PostgreSQL; it notably does not support non-deterministic collations (e.g. case-insensitive ones). To work around this limitation, you can use EF Core's [pre-convention model configuration](https://docs.microsoft.com/ef/core/modeling/bulk-configuration#pre-convention-configuration) feature: - -```csharp -protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) -{ - configurationBuilder.Properties().UseCollation("my_collation"); -} -``` - -All columns created with this configuration will automatically have their collation specified accordingly, and all existing columns will be altered. The end result of the above is very similar to specifying a database collation: instead of telling PostgreSQL to implicit apply a collation to all columns, EF Core will do the same for you in its migrations. - -## The citext type - -The older PostgreSQL method for performing case-insensitive text operations is the `citext` type; it is similar to the `text` type, but operators are functions between `citext` values are implicitly case-insensitive. Use this type only if case-insensitive collations (see above) are insufficient for your purposes. [The PostgreSQL docs](https://www.postgresql.org/docs/current/citext.html) provide more information on this type. - -`citext` is available in a PostgreSQL-bundled extension, so you'll first have to install it: - -```csharp -modelBuilder.HasPostgresExtension("citext"); -``` - -Specifying that a column should use `citext` is simply a matter of setting the column's type: - -### [Data Annotations](#tab/data-annotations) - -```csharp -public class Blog -{ - public int Id { get; set; } - [Column(TypeName = "citext")] - public string Name { get; set; } -} -``` - -### [Fluent API](#tab/fluent-api) - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity().Property(b => b.Name) - .HasColumnType("citext"); -} -``` - -*** - -Some limitations (others are listed in [the PostgreSQL docs](https://www.postgresql.org/docs/current/citext.html)): - -* While `citext` allows case-insensitive comparisons, it doesn't handle other aspects of collations, such as accents. -* Several PostgreSQL text functions are overloaded to work with `citext` as expected, but others aren't. Using a function that isn't overloaded will result in a regular, case-sensitive match. -* Unlike collations, `citext` does not allow the same column to be compared case-sensitively in some queries, and and insensitively in others. - -## ILIKE - -`ILIKE` is a PostgreSQL-specific operator that works just like `LIKE`, but is case-insensitive. If you only need to perform case-insensitive `LIKE` pattern matching, then this could be sufficient. The provider exposes this via `EF.Functions.ILike`: - -```csharp -var results = ctx.Blogs - .Where(b => EF.Functions.ILike(b.Name, "a%b")) - .ToList(); -``` diff --git a/conceptual/EFCore.PG/misc/database-creation.md b/conceptual/EFCore.PG/misc/database-creation.md deleted file mode 100644 index 8e5f9a6a..00000000 --- a/conceptual/EFCore.PG/misc/database-creation.md +++ /dev/null @@ -1,36 +0,0 @@ -# Database Creation - -## Specifying the administrative db - -When the Npgsql EF Core provider creates or deletes a database (`EnsureCreated()`, `EnsureDeleted()`), it must connect to an administrative database which already exists (with PostgreSQL you always have to be connected to some database, even when creating/deleting another database). Up to now the `postgres` database was used, which is supposed to always be present. - -However, there are some PostgreSQL-like databases where the `postgres` database is not available. For these cases you can specify the administrative database as follows: - -```csharp -protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseNpgsql( - "", - options => options.UseAdminDatabase("my_admin_db")); -``` - -## Using a database template - -When creating a new database, -[PostgreSQL allows specifying another "template database"](http://www.postgresql.org/docs/current/static/manage-ag-templatedbs.html) -which will be copied as the basis for the new one. This can be useful for including database entities which are not managed by Entity Framework Core. You can trigger this by using `HasDatabaseTemplate` in your context's `OnModelCreating`: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.UseDatabaseTemplate("my_template_db"); -``` - -## Setting a tablespace - -PostgreSQL allows you to locate your database in different parts of your filesystem, [via tablespaces](https://www.postgresql.org/docs/current/static/manage-ag-tablespaces.html). The Npgsql EF Core provider allows you to specify your database's namespace: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.UseTablespace("my_tablespace"); -``` - -You must have created your tablespace prior to this via the `CREATE TABLESPACE` command - the Npgsql EF Core provider does not do this for you. Note also that specifying a tablespace on specific tables is not supported. diff --git a/conceptual/EFCore.PG/misc/other.md b/conceptual/EFCore.PG/misc/other.md deleted file mode 100644 index e51fcb8d..00000000 --- a/conceptual/EFCore.PG/misc/other.md +++ /dev/null @@ -1,58 +0,0 @@ -# Other - -## PostgreSQL extensions - -The Npgsql EF Core provider allows you to specify PostgreSQL extensions that should be set up in your database. -Simply use `HasPostgresExtension` in your context's `OnModelCreating` method: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.HasPostgresExtension("hstore"); -``` - -## Execution Strategy - -The Npgsql EF Core provider provides a retrying execution strategy, which will attempt to detect most transient PostgreSQL/network errors and will automatically retry your operation. To enable, place the following code in your context's `OnModelConfiguring`: - -```csharp -protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseNpgsql( - "", - options => options.EnableRetryOnFailure()); -``` - -This strategy relies on the `IsTransient` property of `NpgsqlException`. - -## Certificate authentication - -The Npgsql allows you to provide a callback for verifying the server-provided certificates, and to provide a callback for providing certificates to the server. The latter, if properly set up on the PostgreSQL side, allows you to do client certificate authentication - see [the Npgsql docs](http://www.npgsql.org/doc/security.html#encryption-ssltls) and also [the PostgreSQL docs](https://www.postgresql.org/docs/current/static/ssl-tcp.html#SSL-CLIENT-CERTIFICATES) on setting this up. - -The Npgsql EF Core provider allows you to set these two callbacks on the `DbContextOptionsBuilder` as follows: - -```csharp -protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseNpgsql( - "", - options => - { - options.RemoteCertificateValidationCallback(MyCallback1); - options.ProvideClientCertificatesCallback(MyCallback2); - }); -``` - -You may also consider passing `Trust Server Certificate=true` in your connection string to make Npgsql accept whatever certificate your PostgreSQL provides (useful for self-signed certificates). - -> [!CAUTION] -> When specifying the options via `OnConfiguring`, make sure that the callbacks you pass in are static methods. Passing in instance methods causes EF Core to create a new service provider for each context instance, which can degrade performance in a significant way. - -## CockroachDB Interleave In Parent - -If you're using CockroachDB, the Npgsql EF Core provider exposes its ["interleave in parent" feature](https://www.cockroachlabs.com/docs/stable/interleave-in-parent.html). Use the following code: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity() - .UseCockroachDbInterleaveInParent( - typeof(ParentEntityType), - new List { "prefix_column_1", "prefix_column_2" }); -``` diff --git a/conceptual/EFCore.PG/misc/temporal-constraints.md b/conceptual/EFCore.PG/misc/temporal-constraints.md deleted file mode 100644 index 950961eb..00000000 --- a/conceptual/EFCore.PG/misc/temporal-constraints.md +++ /dev/null @@ -1,177 +0,0 @@ -# Temporal constraints - -> [!NOTE] -> Temporal constraints are only supported starting with version 11 of the EF provider, and require PostgreSQL 18. - -PostgreSQL 18 introduced temporal constraints, which allow you to enforce data integrity rules over time periods. These features are particularly valuable for applications that need to track the validity periods of data, such as employee records, pricing information, equipment assignments, or any scenario where you need to maintain a complete historical timeline without gaps or overlaps. - -Temporal constraints work with PostgreSQL's range types, such as `daterange`, `tstzrange` (timestamp with timezone range), and `tsrange` (timestamp range). - -## WITHOUT OVERLAPS - -The `WITHOUT OVERLAPS` clause can be added to primary and alternate keys to ensure that for any given set of scalar column values, the associated time ranges do not overlap. - -A temporal key combines regular columns with a range column. This allows multiple rows for the same entity (e.g., same employee ID) as long as their time periods don't overlap, enabling you to maintain a complete history of changes: - -```csharp -public class Employee -{ - public int EmployeeId { get; set; } - public string Name { get; set; } - public string Department { get; set; } - public decimal Salary { get; set; } - public NpgsqlRange ValidPeriod { get; set; } -} - -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity(b => - { - // Configure the range property with a default value - b.Property(e => e.ValidPeriod) - .HasDefaultValueSql("tstzrange(now(), 'infinity', '[)')"); - - // Configure the temporal primary key - b.HasKey(e => new { e.EmployeeId, e.ValidPeriod }) - .WithoutOverlaps(); - }); -} -``` - -This configuration creates the following table: - -```sql -CREATE TABLE employees ( - employee_id INTEGER, - name VARCHAR(100) NOT NULL, - department VARCHAR(50) NOT NULL, - salary DECIMAL(10,2) NOT NULL, - valid_period tstzrange NOT NULL DEFAULT tstzrange(now(), 'infinity', '[)'), - PRIMARY KEY (employee_id, valid_period WITHOUT OVERLAPS) -); -``` - -With this constraint, you can insert multiple records for the same employee as long as their time periods don't overlap: - -```sql --- Valid: Two records for the same employee with non-overlapping periods -INSERT INTO employees (employee_id, name, department, salary, valid_period) -VALUES - (1, 'Alice Johnson', 'Engineering', 75000, tstzrange('2024-01-01', '2025-01-01', '[)')), - (1, 'Alice Johnson', 'Engineering', 85000, tstzrange('2025-01-01', 'infinity', '[)')); - --- Invalid: This would fail because it overlaps with existing data -INSERT INTO employees (employee_id, name, department, salary, valid_period) -VALUES (1, 'Alice Johnson', 'Engineering', 95000, tstzrange('2024-06-01', '2025-06-01', '[)')); -``` - -> [!IMPORTANT] -> The range column with `WITHOUT OVERLAPS` must be the last column in the primary key definition. - -## PERIOD for temporal foreign keys - -PostgreSQL 18 also introduces temporal foreign keys using the `PERIOD` clause. These constraints ensure that foreign key relationships are maintained across time periods, checking for range containment rather than simple equality. - -A temporal foreign key ensures that the referenced row exists during the entire time period of the referencing row. This is particularly useful when you need to enforce that related temporal data is valid for the same time periods. - -```csharp -public class Employee -{ - public int EmployeeId { get; set; } - public string Name { get; set; } - public NpgsqlRange ValidPeriod { get; set; } -} - -public class ProjectAssignment -{ - public int AssignmentId { get; set; } - public int EmployeeId { get; set; } - public string ProjectName { get; set; } - public NpgsqlRange AssignmentPeriod { get; set; } -} - -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity(b => - { - b.Property(e => e.ValidPeriod) - .HasDefaultValueSql("tstzrange(now(), 'infinity', '[)')"); - - b.HasKey(e => new { e.EmployeeId, e.ValidPeriod }) - .WithoutOverlaps(); - }); - - modelBuilder.Entity(b => - { - b.HasOne() - .WithMany() - .HasForeignKey(e => new { e.EmployeeId, e.AssignmentPeriod }) - .HasPrincipalKey(e => new { e.EmployeeId, e.ValidPeriod }) - .WithPeriod(); - }); -} -``` - -This generates a foreign key constraint like: - -```sql -ALTER TABLE project_assignments -ADD CONSTRAINT fk_emp_temporal -FOREIGN KEY (employee_id, PERIOD assignment_period) -REFERENCES employees (employee_id, PERIOD valid_period); -``` - -With this constraint: - -```sql --- Valid: Assignment period falls within the employee's validity period -INSERT INTO project_assignments (employee_id, project_name, assignment_period) -VALUES (1, 'Website Redesign', tstzrange('2024-03-01', '2024-06-01', '[)')); - --- Invalid: Assignment period extends beyond the employee's validity period -INSERT INTO project_assignments (employee_id, project_name, assignment_period) -VALUES (1, 'Legacy Project', tstzrange('2022-01-01', '2022-06-01', '[)')); -``` - -## NodaTime ranges - -With the [NodaTime plugin](../mapping/nodatime.md) enabled, temporal constraints also support `Interval` (mapped to `tstzrange`) and `DateInterval` (mapped to `daterange`). For example, the employee's validity period can be declared as: - -```csharp -public Interval ValidPeriod { get; set; } -``` - -Configure the key with `.WithoutOverlaps()` and the foreign key with `.WithPeriod()` as above; both sides of the relationship must use compatible range mappings. The range property must be last in both keys. - -## Querying temporal data - -When querying temporal data, PostgreSQL's range operators are particularly useful. The containment operator (`@>`) checks if a range contains a specific point in time: - -```csharp -// Find employees who were active on a specific date -var activeEmployees = context.Employees - .Where(e => e.ValidPeriod.Contains(new DateTime(2024, 6, 15))) - .ToList(); - -// Find all historical records for a specific employee -var employeeHistory = context.Employees - .Where(e => e.EmployeeId == 1) - .OrderBy(e => e.ValidPeriod) - .ToList(); -``` - -These queries translate to efficient SQL that can leverage GiST indexes: - -```sql --- Active employees on a specific date -SELECT * FROM employees -WHERE valid_period @> '2024-06-15'::timestamptz; - --- Employee history -SELECT * FROM employees -WHERE employee_id = 1 -ORDER BY valid_period; -``` - -> [!NOTE] -> Temporal constraints require the `btree_gist` extension to be installed in your database. The EF provider automatically installs `btree_gist` when it detects a key with `WITHOUT OVERLAPS`. diff --git a/conceptual/EFCore.PG/modeling/concurrency.md b/conceptual/EFCore.PG/modeling/concurrency.md deleted file mode 100644 index 7129f07f..00000000 --- a/conceptual/EFCore.PG/modeling/concurrency.md +++ /dev/null @@ -1,54 +0,0 @@ -# Concurrency Tokens - -> [!NOTE] -> Please read the general [Entity Framework Core docs on concurrency tokens](https://docs.microsoft.com/en-us/ef/core/modeling/concurrency). - -Entity Framework Core supports the concept of optimistic concurrency - a property on your entity is designated as a concurrency token, and EF Core detects concurrent modifications by checking whether that token has changed since the entity was read. - -## The PostgreSQL xmin system column - -Although applications can update concurrency tokens themselves, we frequently rely on the database automatically updating a column on update - a "last modified" timestamp, an SQL Server `rowversion`, etc. Unfortunately PostgreSQL doesn't have such auto-updating columns - but there is one feature that can be used for concurrency token. All PostgreSQL tables have a set of [implicit and hidden system columns](https://www.postgresql.org/docs/current/ddl-system-columns.html), among which `xmin` holds the ID of the latest updating transaction. Since this value automatically gets updated every time the row is changed, it is ideal for use as a concurrency token. - -You can map a `uint` property to the PostgreSQL `xmin` system column using the standard EF Core mechanisms: - -### [Data Annotations](#tab/data-annotations) - -```csharp -public class SomeEntity -{ - public int Id { get; set; } - - [Timestamp] - public uint Version { get; set; } -} -``` - -### [Fluent API](#tab/fluent-api) - -```csharp -class MyContext : DbContext -{ - public DbSet SomeEntities { get; set; } - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity() - .Property(b => b.Version) - .IsRowVersion(); - } -} - -public class SomeEntity -{ - public int Id { get; set; } - public uint Version { get; set; } -} -``` - -*** - -## Database concurrency failures - -Starting with version 11.0, PostgreSQL serialization failures (`40001`) and deadlocks (`40P01`) during `SaveChanges()` or `SaveChangesAsync()` are reported as `DbUpdateConcurrencyException`, with the original `PostgresException` as the inner exception. This also covers failures during the automatic transaction commit performed by `SaveChanges`. An explicit application call to commit a transaction is not covered by this conversion. - -As with other concurrency failures, the application must decide whether and how to retry the operation. See the [EF Core concurrency documentation](https://learn.microsoft.com/ef/core/saving/concurrency#resolving-concurrency-conflicts) and [execution strategies](../misc/other.md#execution-strategy). diff --git a/conceptual/EFCore.PG/modeling/generated-properties.md b/conceptual/EFCore.PG/modeling/generated-properties.md deleted file mode 100644 index b480ebae..00000000 --- a/conceptual/EFCore.PG/modeling/generated-properties.md +++ /dev/null @@ -1,192 +0,0 @@ -# Value Generation - -> [!NOTE] -> It's recommended that you start by reading the general [Entity Framework Core docs on generated properties](https://docs.microsoft.com/en-us/ef/core/modeling/generated-properties). - -## Identity and serial columns (auto-increment) - -### Introduction - -The standard way to define auto-incrementing columns is "identity columns"; in older versions of PostgreSQL, "serial columns" were used, which are less SQL-compliant and generally more difficult to manage. For more information on these, [see this blog post](https://blog.2ndquadrant.com/postgresql-10-identity-columns/). - -The Npgsql EF Core provider allows you to choose which of the above you want on a property-by-property basis, or globally on your model. The following "value generation strategies" are available: - -* *Identity by default*: an identity column whose values are *by default* generated at the database, but you can still override this behavior by providing values from your application. This will generate the clause `GENERATED BY DEFAULT AS IDENTITY` on your column, and is the default value generation strategy. -* *Identity always*: an identity column whose values are *always* generated at the database - you cannot provide values from your application. This will generate the clause `GENERATED ALWAYS AS IDENTITY` on your column. -* *Serial*: the traditional PostgreSQL serial column. This will create the column with the `serial` datatype. Recommended only if you are using an older PostgreSQL version. -* *Sequence HiLo*: See below - -The default value generation strategy is "identity by default". In other words, when EF decides that an int property should be value generated (e.g. because it's named `Id`, or because you explicitly specified `ValueGeneratedOnAdd` on it), the Npgsql provider will automatically map it to an identity column. - -### Defining the default strategy for the entire model - -You can easily control the value generation strategy for the entire model. For example, to opt out of the change to identity columns, simply place the following in your context's `OnModelCreating()`: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.UseIdentityByDefaultColumns(); -``` - -Starting with version 11.0, you can disable the default PostgreSQL value generation strategy for the entire model: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.UseNoIdentityGeneration(); -``` - -Explicitly configured property strategies are unaffected. This does not disable EF value generation or remove database defaults or computed expressions; use `ValueGeneratedNever()` to disable value generation for an individual property. - -### Defining the strategy for a single property - -Regardless of the model default, you can define a value-generation strategy on a property-by-property basis: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity().Property(b => b.Id).UseIdentityAlwaysColumn(); -``` - -### Identity sequence options - -Identity columns have a standard sequence, managed behind the scenes by PostgreSQL; you can customize the sequence options for these. For example, the following makes the column values start at 100: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity().Property(b => b.Id) - .HasIdentityOptions(startValue: 100); -``` - -This can be especially useful when seeding data. Seeded data must explicitly specify all columns - including database-generated ones - but the backing sequence for identity columns isn't aware that the values are in use, and will generate conflicting values. This technique allows to start your identity sequence at a value higher than all seeded data values. Another strategy is to seed negative values only, allowing your identity column to start at 1. - -It is not possible to specify sequence options for serial columns, but you can set up a sequence separately and configure the column's default value (see [sequence-driven columns](#standard-sequence-driven-columns)). - -## Standard sequence-driven columns - -While identity and serial columns set up a sequence for you behind the scenes, sometimes you may want to manage sequence creation yourself. For example, you may want to have multiple columns drawing their default values from a single sequence. Adding a sequence to your model is described in [the general EF Core documentation](https://docs.microsoft.com/ef/core/modeling/relational/sequences); once the sequence is specified, you can simply set a column's default value to extract the next value from that sequence. Note that the SQL used to fetch the next value from a sequence differs across databases (see [the PostgreSQL docs](https://www.postgresql.org/docs/current/static/functions-sequence.html)). Your models' `OnModelCreating` should look like this: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.HasSequence("OrderNumbers") - .StartsAt(1000) - .IncrementsBy(5); - - modelBuilder.Entity() - .Property(o => o.OrderNo) - .HasDefaultValueSql("nextval('\"OrderNumbers\"')"); -} -``` - -## HiLo Autoincrement Generation - -One disadvantage of database-generated values is that these values must be read back from the database after a row is inserted. If you're saving multiple related entities, this means you must perform multiple round-trips as the first entity's generated key must be read before writing the second one. One solution to this problem is HiLo value generation: rather than relying on the database to generate each and every value, the application "allocates" a range of values, which it can then populate directly on new entities without any additional round-trips. When the range is exhausted, a new range is allocated. In practical terms, this uses a sequence that increments by some large value (100 by default), allowing the application to insert 100 rows autonomously. - -To use HiLo, specify `UseHiLo` on a property in your model's `OnModelCreating`: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity() - .Property(b => b.Id) - .UseHiLo(); -``` - -You can also make your model use HiLo everywhere: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.UseHiLo(); -``` - -## GUID/UUID Generation - -By default, for GUID key properties, a GUID is generated client-side by the EF provider and sent to the database. From version 9.0 and onwards, these GUIDs are sequential (version 7), which are more optimized for database indexes (before version 9.0, these GUIDs were random). - -To have the provider generate GUIDs client-side for **non-key** properties, configure them as follows: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder - .Entity() - .Property(b => b.SomeGuidProperty) - .HasValueGenerator(); -} -``` - -If you prefer to generate values in the database instead, you can do so by specifying `HasDefaultValueSql` on your property, and call the function to generate the value in the SQL expression. Starting with PostgreSQL 18, version 7 GUIDs can be generated, which are optimized for database indexes: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder - .Entity() - .Property(e => e.SomeGuidProperty) - .HasDefaultValueSql("uuidv7()"); -} -``` - -Prior to PostgreSQL 18, you can use an extension such as `pg_uuidv7` to generate version 7 GUIDs, or generate random version 7 GUIDs instead: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder - .Entity() - .Property(e => e.SomeGuidProperty) - .HasDefaultValueSql("uuid_generate_v4()"); -} -``` - -However, note that such version 4 GUIDs perform significantly worse with database indexes. - -See [the PostgreSQL docs on UUID for more details](https://www.postgresql.org/docs/current/static/datatype-uuid.html). - -> [!NOTE] -> Generating `Guid` values in the database causes an additional network roundtrip when a principal and a dependent are inserted in the same `SaveChanges`, as the principal's key needs to be fetched before inserting the dependent's. - -## Timestamp generation - -In many scenarios, it's useful to have a column containing the timestamp when the row was originally created. To do this, add a `DateTime` property to your entity type (or `Instant` if using NodaTime) , and configure its default with `HasDefaultValueSql` as follows: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder - .Entity() - .Property(e => e.SomeDateTimeProperty) - .HasDefaultValueSql("now()"); -} -``` - -In other scenarios, a "last updated" is needed, which is automatically updated every time is modified. Unfortunately, while PostgreSQL supports [generated columns](https://www.postgresql.org/docs/current/ddl-generated-columns.html), the use of functions such as `now()` isn't supported. It's still possible to use database trigger to set this up; triggers can be managed by [adding raw SQL to your migrations](https://docs.microsoft.com/ef/core/managing-schemas/migrations/managing#adding-raw-sql), as follows: - -```sql -CREATE FUNCTION "Blogs_Update_Timestamp_Function"() RETURNS TRIGGER LANGUAGE PLPGSQL AS $$ -BEGIN - NEW."Timestamp" := now(); - RETURN NEW; -END; -$$; - -CREATE TRIGGER "UpdateTimestamp" - BEFORE INSERT OR UPDATE - ON "Blogs" - FOR EACH ROW - EXECUTE FUNCTION "Blogs_Update_Timestamp_Function"(); -``` - -## Computed (generated) columns - -EF computed columns - or generated columns, as they're called in PostgreSQL - are fully supported: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity() - .Property(p => p.DisplayName) - .HasComputedColumnSql(@"""FirstName"" || ' ' || ""LastName""", stored: true); -} -``` - -The above creates a *stored* generated column, meaning that it's computed when a row is inserted or updated, and take up space on disk just like regular columns. PostgreSQL 18 introduced support for *virtual* generated columns, which are instead calculated when read, and take up no space on disk. Virtual generated columns are the default - simply omit `stored: true` above to create them. - -See the [EF documentation](https://learn.microsoft.com/ef/core/modeling/generated-properties#computed-columns) and the [PostgreSQL documentation](https://www.postgresql.org/docs/current/ddl-generated-columns.html) for more information. diff --git a/conceptual/EFCore.PG/modeling/indexes.md b/conceptual/EFCore.PG/modeling/indexes.md deleted file mode 100644 index 817ddad4..00000000 --- a/conceptual/EFCore.PG/modeling/indexes.md +++ /dev/null @@ -1,90 +0,0 @@ -# Indexes - -PostgreSQL and the Npgsql provider support the standard index modeling described in [the EF Core docs](https://docs.microsoft.com/ef/core/modeling/indexes). This page describes some supported PostgreSQL-specific features. - -## Covering indexes (INCLUDE) - -PostgreSQL supports [covering indexes](https://paquier.xyz/postgresql-2/postgres-11-covering-indexes), which allow you to include "non-key" columns in your indexes. This allows you to perform index-only scans and can provide a significant performance boost: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity() - .HasIndex(b => b.Id) - .IncludeProperties(b => b.Name); -``` - -This will create an index for searching on `Id`, but containing also the column `Name`, so that reading the latter will not involve accessing the table. The SQL generated is as follows: - -```sql -CREATE INDEX "IX_Blog_Id" ON blogs ("Id") INCLUDE ("Name"); -``` - -## Treating nulls as non-distinct - -By default, when you create a unique index, PostgreSQL treats null values as distinct; this means that a unique index can contain multiple null values in a column. When creating an index, you can also instruct PostgreSQL that nulls should be treated as *non-distinct*; this causes a unique constraint violation to be raised if a column contains multiple null values: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity() - .IsUnique() - .AreNullsDistinct(false); -``` - -## Index methods - -PostgreSQL supports a number of *index methods*, or *types*. These are specified at index creation time via the `USING ` clause, see the [PostgreSQL docs for `CREATE INDEX`](https://www.postgresql.org/docs/current/static/sql-createindex.html) and [this page](https://www.postgresql.org/docs/current/static/indexes-types.html) for information on the different types. - -The Npgsql EF Core provider allows you to specify the index method to be used by calling `HasMethod()` on your index in your context's `OnModelCreating` method: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity() - .HasIndex(b => b.Url) - .HasMethod("gin"); -``` - -## Index operator classes - -PostgreSQL allows you to specify [operator classes on your indexes](https://www.postgresql.org/docs/current/indexes-opclass.html), to allow tweaking how the index should work. Use the following code to specify an operator class: - -```csharp -protected override void OnConfiguring(DbContextOptionsBuilder builder) - => modelBuilder.Entity() - .HasIndex(b => new { b.Id, b.Name }) - .HasOperators(null, "text_pattern_ops"); -``` - -Note that each operator class is used for the corresponding index column, by order. In the example above, the `text_pattern_ops` class will be used for the `Name` column, while the `Id` column will use the default class (unspecified), producing the following SQL: - -```sql -CREATE INDEX "IX_blogs_Id_Name" ON blogs ("Id", "Name" text_pattern_ops); -``` - -## Storage parameters - -PostgreSQL allows configuring indexes with *storage parameters*, which can tweak their behaviors in various ways; which storage parameters are available depends on the chosen index method. [See the PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-STORAGE-PARAMETERS) for more information. - -To configure a storage parameter on an index, use the following code: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity() - .HasIndex(b => b.Url) - .HasStorageParameter("fillfactor", 70); -``` - -## Creating indexes concurrently - -Creating an index can interfere with regular operation of a database. Normally PostgreSQL locks the table to be indexed against writes and performs the entire index build with a single scan of the table. Other transactions can still read the table, but if they try to insert, update, or delete rows in the table they will block until the index build is finished. This could have a severe effect if the system is a live production database. Very large tables can take many hours to be indexed, and even for smaller tables, an index build can lock out writers for periods that are unacceptably long for a production system. - -The EF provider allows you to specify that an index should be created *concurrently*, partially mitigating the above issues: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity() - .HasIndex(b => b.Url) - .IsCreatedConcurrently(); -``` - -> [!CAUTION] -> Do not enable this feature before reading the [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY) and understanding the full implications of concurrent index creation. diff --git a/conceptual/EFCore.PG/modeling/tables.md b/conceptual/EFCore.PG/modeling/tables.md deleted file mode 100644 index 76a0ef1e..00000000 --- a/conceptual/EFCore.PG/modeling/tables.md +++ /dev/null @@ -1,47 +0,0 @@ -# Tables - -## Naming - -By default, EF Core will map to tables and columns named exactly after your .NET classes and properties, so an entity type named `BlogPost` will be mapped to a PostgreSQL table called `BlogPost`. While there's nothing wrong with that, the PostgreSQL world tends towards snake_case naming instead. In addition, any upper-case letters in unquoted identifiers are automatically converted to lower-case identifiers, so the Npgsql provider generates quotes around all such identifiers. - -The [EFCore.NamingConventions](https://github.com/efcore/EFCore.NamingConventions) plugin to automatically set all your table and column names to snake_case instead: - -```csharp -protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder - .UseNpgsql(...) - .UseSnakeCaseNamingConvention(); - -public class Customer { - public int Id { get; set; } - public string FullName { get; set; } -} -``` - -This will cause cleaner SQL such as the following to be generated: - -```sql -CREATE TABLE customers ( - id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY, - full_name text NULL, - CONSTRAINT "PK_customers" PRIMARY KEY (id); - -SELECT c.id, c.full_name - FROM customers AS c - WHERE c.full_name = 'John Doe'; -``` - -However, note that the EFCore.NamingConventions isn't an official part of EF (or of the PostgreSQL provider), and sometimes lags behind in terms of support. - -See the [plugin documentation](https://github.com/efcore/EFCore.NamingConventions) for more details, - -## Storage parameters - -PostgreSQL allows configuring tables with *storage parameters*, which can tweak storage behavior in various ways; [see the PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-STORAGE-PARAMETERS) for more information. - -To configure a storage parameter on a table, use the following code: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity().HasStorageParameter("fillfactor", 70); -``` diff --git a/conceptual/EFCore.PG/release-notes/1.1.md b/conceptual/EFCore.PG/release-notes/1.1.md deleted file mode 100644 index 39d0628e..00000000 --- a/conceptual/EFCore.PG/release-notes/1.1.md +++ /dev/null @@ -1,46 +0,0 @@ -# Migrating to 1.1 - -Version 1.1.0 of the Npgsql Entity Framework Core provider has been released and is available on nuget. This version works with [version 1.1.0 of Entity Framework Core](https://blogs.msdn.microsoft.com/dotnet/2016/10/25/announcing-entity-framework-core-1-1-preview-1/), and contains some new Npgsql features as well. Note that if you're using the command-line tools, you'll have to modify your tools section as described in the EF Core release post: - -```json -"tools": { - "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0-preview3-final" -}, -``` - -## New Features - -Aside from general EF Core features, version 1.1.0 of the Npgsql provider contains the following: - -* Hilo key generation ([#5](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/5)). This can be a much more efficient way to generate autoincrement key values. -* PostgreSQL array mapping ([#15](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/15)). This allows you to have plain CLR arrays on your entities, and have those arrays mapped to native [PostgreSQL array columns](https://www.postgresql.org/docs/current/static/arrays.html). -* Optimistic concurrency with PostgreSQL's xmin column ([#19](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/19)). Simply specify `.UseXminAsConcurrencyToken()` on an entity to start using this, see the [EF docs for more details](https://docs.efproject.net/en/latest/modeling/concurrency.html). -* Cleanup of how serial (autoincrement) and generated GUID/UUID columns are managed. - -Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/milestone/3?closed=1). Please report any problems to . - -## Upgrading from 1.0.x - -If you've used 1.0.x without migrations, you can simply upgrade and everything should just work. Unfortunately, if you already have migrations from 1.0.x you'll have to do some manual fixups because of some bad decisions that were previously made. If deleting your old migrations and starting over (e.g. non-production database) is an option, you may wish to do so. The following are instructions for fixing up 1.0.x migrations. - -First, Npgsql 1.0.x used a problematic method to identify serial (autoincrement) columns in migrations. If you look at your migration code you'll see `.Annotation("Npgsql:ValueGeneratedOnAdd", true)` on various columns. Unfortunately this annotation is also present on non-serial columns, e.g. columns with default values. This causes various issues and has been replaced in 1.1. However, you'll have to manually remove `.Annotation("Npgsql:ValueGeneratedOnAdd", true)`, and replace it with `.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)` but *only* on columns which should be serial (e.g. not on columns with defaults). If you attempt to run a migration that has the old annotation, Npgsql will throw an exception and refuse to run your migrations. - -Unfortunately, this change will cause some incorrect changes the first time you add a migration after the upgrade. To avoid this, simply add a dummy migration right after upgrading to 1.1 and then delete the two new files generated for the dummy migration, *but keep the changes made to your ModelSnapshot.cs*. From this point on everything should be fine. *Make sure you have no pending changes to your model before doing this!*. - -Apologies for this problematic upgrade procedure, it should at least keep things clean going forward. - -## Contributors - -Thank you very much to the following people who have contributed to the individual 1.1.x. releases. - -### [Milestone 1.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.1) - -Contributor | Assigned issues --------------------------------- | ---------------:| -[@roji](https://github.com/roji) | [8](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.1+is%3Aclosed+assignee%3Aroji) - -### [Milestone 1.1.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.0) - -Contributor | Assigned issues --------------------------------- | ---------------:| -[@roji](https://github.com/roji) | [11](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A1.1.0+is%3Aclosed+assignee%3Aroji) diff --git a/conceptual/EFCore.PG/release-notes/10.0.md b/conceptual/EFCore.PG/release-notes/10.0.md deleted file mode 100644 index 99324703..00000000 --- a/conceptual/EFCore.PG/release-notes/10.0.md +++ /dev/null @@ -1,189 +0,0 @@ -# 10.0 Release Notes - -Npgsql.EntityFrameworkCore.PostgreSQL version 10.0 is out and available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). - -## Full support for EF 10 JSON complex types - -EF 10 introduced support for mapping .NET types as JSON complex types, resolving several issues that existed with the previous JSON mapping via owned entities ([see release notes for more information](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-10.0/whatsnew#json)). The PG provider providers full support for this feature full support for this as well: - -```c# -modelBuilder.Entity(b => -{ - b.ComplexProperty(c => c.ShippingAddress, c => c.ToJson()); - b.ComplexProperty(c => c.BillingAddress, c => c.ToJson()); -}); -``` - -This configuration causes the following table to be created for your customers: - -```sql -CREATE TABLE "Customers" ( - "Id" integer GENERATED BY DEFAULT AS IDENTITY, - "Name" text, - "BillingAddress" jsonb NOT NULL, - "ShippingAddress" jsonb NOT NULL, - CONSTRAINT "PK_Customers" PRIMARY KEY ("Id") -); -``` - -This is now the preferred way to perform strongly-typed JSON mapping of arbitrary .NET types, and replaces owned entities and [legacy POCO mapping](../mapping/json.md?#legacy-poco-mapping-deprecated). - -The provider now also supports performing partial updates within JSON documents using `ExecuteUpdate`. For example, the following efficiently copies overwrites all Customers' shipping address streets with their billing address streets: - -```c# -await context.Customers.ExecuteUpdateAsync(s => - s.SetProperty(b => b.ShippingAddress.Street, b => b.BillingAddress.Street)); -``` - -This produces the following SQL: - -```sql -UPDATE "Customers" AS c -SET "ShippingAddress" = jsonb_set(c."ShippingAddress", '{Street}', c."BillingAddress" -> 'Street') -``` - -## Better support for JSON scalar (primitive) collections - -In most relational databases, scalar collections are mapped to a JSON column, the the collection is serialized to a JSON array in the database. PostgreSQL, however, is unique in providing a 1st-class array type, so the EF provider maps scalar collections to array instead. For example, given the following type: - -```c# -public class Customer -{ - public int Id { get; set; } - public string[] Tags { get; set; } -} -``` - -... the PostgreSQL provider will create the following table (note that `text[]` array column): - -```sql -CREATE TABLE "Customers" ( - "Id" integer GENERATED BY DEFAULT AS IDENTITY, - "Tags" text[] NOT NULL, - CONSTRAINT "PK_Customers" PRIMARY KEY ("Id") -); -``` - -However, when scalar collections are nested within a JSON document, they must be mapped to JSON arrays, as in other databases: - -```c# -public class Customer -{ - public int Id { get; set; } - public Address Address { get; set; } -} - -public class Address -{ - // ... - - public string[] Tags { get; set; } -} -``` - -Version 10 of the provider now produces much better SQL when querying such nested scalar collections. For example, when querying using Contains: - -```c# -var customers = await context.Customers.Where(b => b.ShippingAddress.Tags.Contains("foo")).ToListAsync(); -``` - -... previous versions of the provider generated the following complicated (and inefficient) SQL: - -```sql -SELECT c."Id", c."Name", c."ShippingAddress" -FROM "Customers" AS c -WHERE 'foo' = ANY ((ARRAY(SELECT CAST(element AS text) FROM jsonb_array_elements_text(c."ShippingAddress" -> 'Tags') WITH ORDINALITY AS t(element) ORDER BY ordinality))) -``` - -Version 10, in contrast, produces the following cleaner SQL, which can also benefit from indexes: - -```sql -SELECT c."Id", c."Name", c."ShippingAddress" -FROM "Customers" AS c -WHERE (c."ShippingAddress" -> 'Tags') @> to_jsonb('foo'::text) -``` - -Finally, version 10 of the provider also allows you to map a non-nested scalar collection to a JSON column, instead of to an array column, and provides fully querying capabilities: - -```c# -public class Customer -{ - // ... - - [Column(TypeName = "jsonb")] - public string[] Tags { get; set; } -} -``` - -## Support for PostgreSQL 18 virtual generated columns - -Before PostgreSQL 18, generated (or "computed") columns could only be stored, meaning they were computed when a row is inserted or updated, and take up space on disk just like regular columns. PostgreSQL 18 introduced support for *virtual* generated columns, which are instead calculated when read, and take up no space on disk. Virtual columns can be defined with version 10 of the PostgreSQL provider as follows: - -```c# -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity() - .Property(p => p.DisplayName) - .HasComputedColumnSql(@"""FirstName"" || ' ' || ""LastName"""); -} -``` - -Note that previously, `stored: true` had to be specified in the above code sample; starting with version 10, omitting it causes a virtual generated column to be created (supported on PostgreSQL 18 only). - -For more information, [see the documentation](../modeling/generated-properties.md#computed-generated-columns). - -## Support for UUIDv7 - -By default, EF generates GUID (or UUID) values locally in .NET, rather than relying on the database to generate them. Version 9 of the PG provider already switched to generating UUIDv7 values by default ([see release note](9.0.md#uuidv7-guids-are-generated-by-default)), which are significantly better for database indexes. PostgreSQL 18 also added the [`uuidv7()`](https://www.postgresql.org/docs/18/functions-uuid.html#FUNC_UUID_GEN_TABLE) built-in function, which allows database generation of UUIDv7 values. In EFCore.PG 10, if you configure the provider to target PG 18 (`.UseNpgsql("...", o => o.SetPostgresVersion(18, 0))`), the provider will also translate [`Guid.CreateVersion7()`](https://learn.microsoft.com/dotnet/api/system.guid.createversion7) to that function. - -## Support for the cube extension - -PostgreSQL bundles the [`cube`](https://www.postgresql.org/docs/current/cube.html) extension, which provides a multi-dimensional cube data type and associated operations. EFCore.PG 10 now fully supports the `cube` type out-of-the-box, simply add an `NpgsqlCube` property to your entity type: - -```c# -public class Blog -{ - ... - - public NpgsqlCube Cube { get; set; } -} -``` - -Most translations over the type are supported as well. Thanks to [@kirkbrauer](https://github.com/kirkbrauer) for contributing this feature! - -## Other new features - -* NodaTime `LocalDate.At()` and `LocalDate.AtMidnight()` are now translated. - -See the [10.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/68?closed=1) for the full list of Npgsql EF provider issues. - -## Breaking changes - -### Array `Contains` translation now defaults to `ANY` - -Translation for array `Contains` was changed in 10.0: `arrayColumn.Contains(element)` now defaults to `element = ANY(arrayColumn)` (instead of `arrayColumn @> ARRAY[element]`). This can impact performance depending on your indexes: `@>` can be much faster with a GIN index over the array column, while `ANY` can be better when that GIN index is missing. - -Previous SQL: - -```sql -WHERE array_column @> ARRAY[@__element_0]::text[] -``` - -New default SQL: - -```sql -WHERE @__element_0 = ANY (array_column) -``` - -To tell EF that a GIN index exists and revert to the previous `@>` translation, model that index: - -```csharp -modelBuilder.Entity() - .HasIndex(i => i.ArrayColumn) - .HasMethod("gin"); -``` - -### Other breaking changes - -* `EF.Functions.Network()` and `EF.Functions.Merge()` have been changed to return the new .NET [`IPNetwork`](https://learn.microsoft.com/dotnet/api/system.net.ipnetwork) instead of the obsolete `NpgsqlCidr`. The new `IPNetwork` type works with all other functions as well (but no breaking changes were necessary). -* The PostgreSQL network type `cidr` is now scaffolded to the new .NET [`IPNetwork`](https://learn.microsoft.com/dotnet/api/system.net.ipnetwork) type. The older Npgsql representation for `cidr` - the `NpgsqlCidr` type - has been obsoleted and will be removed in a future release. diff --git a/conceptual/EFCore.PG/release-notes/11.0.md b/conceptual/EFCore.PG/release-notes/11.0.md deleted file mode 100644 index 9ec1c68c..00000000 --- a/conceptual/EFCore.PG/release-notes/11.0.md +++ /dev/null @@ -1,195 +0,0 @@ -# 11.0 Release Notes - -Npgsql.EntityFrameworkCore.PostgreSQL 11.0.0 is available on [NuGet](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL/11.0.0). - -## Indexes over JSON members - -EF 11 complex types mapped with `ToJson()` now support indexing JSON members through the existing `HasIndex` APIs, including unique and composite indexes. By default, these create B-tree expression indexes over the selected values; explicit GIN indexes can target `jsonb` arrays and subdocuments. See [Indexing JSON columns](../mapping/json.md#indexing-json-columns) for examples and limitations. - -## PostgreSQL JSON functions with ToJson - -The existing PostgreSQL JSON functions, such as `EF.Functions.JsonContains()` and `EF.Functions.JsonExists()`, can now be used with complex types and owned entities mapped with `ToJson()`, including nested objects and collections: - -```csharp -var customers = await context.Customers - .Where(c => EF.Functions.JsonContains(c.Details, """{"Name": "Joe"}""")) - .ToListAsync(); -``` - -## Support for PostgreSQL 18 temporal constraints - -PostgreSQL 18 introduced powerful temporal constraints that allow enforcing data integrity over time periods directly at the database level. The EF Core provider now supports these features, allowing you to define temporal primary keys, unique constraints, and foreign keys. - -### WITHOUT OVERLAPS for keys - -Temporal primary and alternate keys use the `WITHOUT OVERLAPS` clause to ensure that for any given set of scalar column values, the associated time ranges do not overlap. This is useful for scenarios where you need to track historical data (e.g. employee records, pricing information, equipment assignments) while ensuring data integrity. - -For example, an employee can have multiple records in the database (reflecting changes over time), but their validity periods must never overlap: - -```csharp -public class Employee -{ - public int EmployeeId { get; set; } - public string Name { get; set; } - public string Department { get; set; } - public decimal Salary { get; set; } - public NpgsqlRange ValidPeriod { get; set; } -} - -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity(b => - { - b.Property(e => e.ValidPeriod) - .HasDefaultValueSql("tstzrange(now(), 'infinity', '[)')"); - - b.HasKey(e => new { e.EmployeeId, e.ValidPeriod }) - .WithoutOverlaps(); - }); -} -``` - -This generates the following SQL: - -```sql -CREATE TABLE employees ( - employee_id INTEGER, - name VARCHAR(100) NOT NULL, - department VARCHAR(50) NOT NULL, - salary DECIMAL(10,2) NOT NULL, - valid_period tstzrange NOT NULL DEFAULT tstzrange(now(), 'infinity', '[)'), - PRIMARY KEY (employee_id, valid_period WITHOUT OVERLAPS) -); -``` - -### PERIOD for temporal foreign keys - -Temporal foreign keys use the `PERIOD` clause to ensure that the referenced row exists during the entire time period of the referencing row. This maintains referential integrity across temporal relationships. - -For example, when assigning employees to projects, the assignment period must fall within the employee's validity period: - -```csharp -public class ProjectAssignment -{ - public int AssignmentId { get; set; } - public int EmployeeId { get; set; } - public string ProjectName { get; set; } - public NpgsqlRange AssignmentPeriod { get; set; } -} - -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity(b => - { - b.HasOne() - .WithMany() - .HasForeignKey(e => new { e.EmployeeId, e.AssignmentPeriod }) - .HasPrincipalKey(e => new { e.EmployeeId, e.ValidPeriod }) - .WithPeriod(); - }); -} -``` - -This generates the following SQL: - -```sql -ALTER TABLE project_assignments -ADD CONSTRAINT fk_emp_temporal -FOREIGN KEY (employee_id, PERIOD assignment_period) -REFERENCES employees (employee_id, PERIOD valid_period); -``` - -Temporal constraints also support NodaTime `Interval` and `DateInterval` properties when the NodaTime plugin is enabled. For more details, see the [temporal constraints documentation](../misc/temporal-constraints.md). - -## New translations - -EFCore.PG 11 brings many new query translations across the board: - -| .NET | SQL | Notes | -| ---- | --- | ----- | -| [EF.Functions.DateTrunc("month", value)](../mapping/translations.md#date-and-time-functions) | date_trunc('month', value) | Also supports [NodaTime types](../mapping/nodatime.md#operation-translation) and an optional time zone for timestamptz ([#3831](https://github.com/npgsql/efcore.pg/issues/3831)). | -| [EF.Functions.JsonPathExists(json, "$.Age")](../mapping/translations.md#json-functions) | JSON_EXISTS(json, '$.Age') | PostgreSQL 17+ ([#3733](https://github.com/npgsql/efcore.pg/issues/3733)). | -| [EF.Functions.FuzzyStringMatchDaitchMokotoff(text)](../mapping/translations.md#fuzzy-string-match-functions) | daitch_mokotoff(text) | Requires fuzzystrmatch on PostgreSQL 16+ ([#3524](https://github.com/npgsql/efcore.pg/issues/3524)). | -| [TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTime, sourceTimeZoneId, destinationTimeZoneId)](../mapping/translations.md#date-and-time-functions) | (dateTime AT TIME ZONE sourceTimeZoneId) AT TIME ZONE destinationTimeZoneId | timestamp without time zone ([#3938](https://github.com/npgsql/efcore.pg/issues/3938)). | -| [dateTime.Millisecond](../mapping/translations.md#date-and-time-functions) | floor(date_part('milliseconds', dateTime))::INT % 1000 | Also DateTimeOffset, TimeOnly ([#3406](https://github.com/npgsql/efcore.pg/issues/3406)). | -| [dateTime.Microsecond](../mapping/translations.md#date-and-time-functions) | date_part('microseconds', dateTime)::INT % 1000 | Also DateTimeOffset, TimeOnly ([#3406](https://github.com/npgsql/efcore.pg/issues/3406)). | -| [dateTime.AddMilliseconds(value)](../mapping/translations.md#date-and-time-functions) | dateTime + value * INTERVAL '1 milliseconds' | Also DateTimeOffset ([#3449](https://github.com/npgsql/efcore.pg/issues/3449)). | -| [dateTime.AddMicroseconds(value)](../mapping/translations.md#date-and-time-functions) | dateTime + value * INTERVAL '1 microseconds' | Also DateTimeOffset ([#3449](https://github.com/npgsql/efcore.pg/issues/3449)). | -| [LocalDateTime.ToDateTimeUnspecified()](../mapping/nodatime.md#operation-translation) | No PG operation | NodaTime ([#4048](https://github.com/npgsql/efcore.pg/issues/4048)). | -| stringValue.IndexOf(value) | strpos(stringValue, value) - 1 | char overload ([#3547](https://github.com/npgsql/efcore.pg/issues/3547)). | -| stringValue.Replace(oldValue, newValue) | replace(stringValue, oldValue, newValue) | char overload | -| stringValue.StartsWith(value) | stringValue LIKE value \|\| '%' | char overload | -| stringValue.EndsWith(value) | stringValue LIKE '%' \|\| value | char overload | -| stringValue.Contains(value) | stringValue LIKE %value% | char overload | -| int.Parse(stringValue) | CAST(stringValue AS integer) | Also bool, byte, short, long, float, double and decimal | -| [array1.Take(2).SequenceEqual(array2)](../mapping/array.md#operation-translation) | array1\[:2\] = array2 | Also Skip() and Skip().Take() ([#3633](https://github.com/npgsql/efcore.pg/issues/3633)). | -| [array1.Intersect(array2).Any()](../mapping/array.md#operation-translation) | array1 && array2 | Now supports static readonly collections with non-null elements ([#3638](https://github.com/npgsql/efcore.pg/issues/3638)). | -| [bytes.Any()](../mapping/translations.md#binary-functions) | length(bytes) > 0 | byte[] mapped to bytea | -| [bytes.Concat(bytes2)](../mapping/translations.md#binary-functions) | bytes \|\| bytes2 | byte[] columns mapped to bytea ([#2200](https://github.com/npgsql/efcore.pg/pull/2200)). | -| [bitArray.Get(index)](../mapping/translations.md#binary-functions) | get_bit(bitArray, index) = 1 | Also bitArray[index] ([#2836](https://github.com/npgsql/efcore.pg/issues/2836)). | -| [EF.Functions.IntersectsBbox(geom1, geom2)](../mapping/nts.md#operation-translation) | [geom1 && geom2](https://postgis.net/docs/geometry_overlaps.html) | Thanks to [@bjornharrtell](https://github.com/bjornharrtell)! | -| [EF.Functions.LineInterpolatePoint(lineString, fraction)](../mapping/nts.md#operation-translation) | [ST_LineInterpolatePoint(lineString, fraction)](https://postgis.net/docs/ST_LineInterpolatePoint.html) | [#2632](https://github.com/npgsql/efcore.pg/issues/2632) | -| [EF.Functions.LineMerge(geom)](../mapping/nts.md#operation-translation) | [ST_LineMerge(geom)](https://postgis.net/docs/ST_LineMerge.html) | [#2632](https://github.com/npgsql/efcore.pg/issues/2632) | -| [EF.Functions.Scale(geom, xFactor, yFactor)](../mapping/nts.md#operation-translation) | [ST_Scale(geom, xFactor, yFactor)](https://postgis.net/docs/ST_Scale.html) | Also supports a zFactor; scales relative to the coordinate origin ([#829](https://github.com/npgsql/efcore.pg/issues/829)). | -| [EF.Functions.SetSrid(geom, srid)](../mapping/nts.md#operation-translation) | [ST_SetSRID(geom, srid)](https://postgis.net/docs/ST_SetSRID.html) | Sets SRID metadata without changing coordinates; use Transform for reprojection ([#3245](https://github.com/npgsql/efcore.pg/issues/3245)). | - -The following [hstore translations](../mapping/translations.md#hstore-translations) are now supported for `Dictionary` and `ImmutableDictionary`, with additional operations specific to immutable dictionaries ([#4082](https://github.com/npgsql/efcore.pg/pull/4082)): - -| .NET | SQL | Notes | -| ---- | --- | ----- | -| dictionary[key] | dictionary -> key | Added in 11.0 | -| dictionary.GetValueOrDefault(key) | dictionary -> key | Added in 11.0 | -| dictionary.GetValueOrDefault(key, fallback) | CASE WHEN dictionary ? key THEN dictionary -> key ELSE fallback END | Added in 11.0 | -| dictionary.ContainsKey(key) | dictionary ? key | Added in 11.0 | -| dictionary.ContainsValue(value) | array_position(avals(dictionary), value) IS NOT NULL | Added in 11.0 | -| dictionary.Count | cardinality(akeys(dictionary)) | Added in 11.0 | -| immutableDictionary.IsEmpty | cardinality(akeys(immutableDictionary)) = 0 | Added in 11.0 | -| immutableDictionary.Remove(key) | immutableDictionary - key | Added in 11.0 | -| immutableDictionary.RemoveRange(keys) | immutableDictionary - keys | Added in 11.0 | -| immutableDictionary.SetItems(otherDictionary) | immutableDictionary \|\| otherDictionary | Added in 11.0 | -| keys.All(key => dictionary.ContainsKey(key)) | dictionary ?& keys | Added in 11.0 | -| keys.Any(key => dictionary.ContainsKey(key)) | dictionary ?\| keys | Added in 11.0 | - -## Other new features - -* [Generated `tsvector` columns and full-text expression indexes](../mapping/full-text-search.md#setting-up-and-querying-a-full-text-search-index-on-an-entity) now support integer and exact-numeric inputs by casting them to text ([#2615](https://github.com/npgsql/efcore.pg/issues/2615)). -* [`MapEnum`](../mapping/enum.md) now respects type-level `[PgName]` attributes when no PostgreSQL enum name is supplied ([#3379](https://github.com/npgsql/efcore.pg/issues/3379)). -* Added [`ModelBuilder.UseNoIdentityGeneration()`](../modeling/generated-properties.md#defining-the-default-strategy-for-the-entire-model) to disable the model's default PostgreSQL identity generation strategy ([#3723](https://github.com/npgsql/efcore.pg/issues/3723)). -* [Covering indexes](../modeling/indexes.md#covering-indexes-include) now support including properties nested within complex types mapped to regular columns. -* Indexes configured with [`IsCreatedConcurrently()`](../modeling/indexes.md#creating-indexes-concurrently) are now also dropped concurrently when removed by migrations ([#3901](https://github.com/npgsql/efcore.pg/issues/3901)). -* [Creating PostgreSQL extensions](../misc/other.md#postgresql-extensions) now uses `CASCADE` to install their dependencies automatically ([#3682](https://github.com/npgsql/efcore.pg/issues/3682)). -* Support specifying the encoding of newly created PostgreSQL databases with `ModelBuilder.UseDatabaseEncoding()` ([#3526](https://github.com/npgsql/efcore.pg/issues/3526)). -* Custom collation references now respect the model's default schema and correctly handle dots in collation and schema names across migrations, queries and scaffolding ([#4072](https://github.com/npgsql/efcore.pg/pull/4072)). - -See the [11.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/75?closed=1) for the full list of issues. - -## Breaking changes - -### The dependency injection extension class was renamed - -The provider's `NpgsqlServiceCollectionExtensions` class was renamed to `NpgsqlEntityFrameworkServiceCollectionExtensions` to avoid a name collision with the Npgsql driver. Extension-method calls such as `services.AddNpgsql(...)` and `services.AddEntityFrameworkNpgsql()` don't need source changes, but assemblies compiled against the old methods must be rebuilt. If your code references the class directly, update it to use the new name ([npgsql/efcore.pg#4139](https://github.com/npgsql/efcore.pg/pull/4139)). - -### PostgreSQL 16 is targeted by default - -The provider now assumes at least PostgreSQL 16 by default, taking advantage of newer features (previously, PostgreSQL 14 was targeted). You can configure the targeted PostgreSQL version when configuring your context: - -```c# -protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseNpgsql("", o => o.SetPostgresVersion(14, 0)); -``` - -### Changes to transient and concurrency exceptions - -The default, non-retrying execution strategy no longer wraps transient failures in an additional `InvalidOperationException`. Applications catching that wrapper should instead handle the underlying exception. - -In addition, PostgreSQL serialization failures (`40001`) and deadlocks (`40P01`) during `SaveChanges()` or `SaveChangesAsync()` now throw `DbUpdateConcurrencyException`, with the original `PostgresException` as the inner exception. This includes failures during an automatically committed transaction, but not a transaction committed explicitly by the application. Previously, these failures were generally exposed as `DbUpdateException` wrapped in `InvalidOperationException`. - -These changes do not enable automatic retries. See [execution strategies](../misc/other.md#execution-strategy) and [database concurrency failures](../modeling/concurrency.md#database-concurrency-failures) for details ([#3098](https://github.com/npgsql/efcore.pg/issues/3098)). - -### Initial migration rollback removes model-level objects - -Rolling back a newly scaffolded initial migration now drops enum, range and collation definitions that were previously left behind. If other applications use these objects, the rollback can fail due to their dependencies; remove the corresponding drop operations from `Down()` if the objects must be preserved ([#3604](https://github.com/npgsql/efcore.pg/issues/3604)). - -### Collation annotations containing literal double quotes - -Previously scaffolded snapshots and migrations with raw collation annotation keys containing literal double quotes in collation or schema names can be misinterpreted by the new identifier encoding. They may fail to decode or reference the wrong collation; update affected annotation keys manually before using them with 11.0 ([#4072](https://github.com/npgsql/efcore.pg/pull/4072)). diff --git a/conceptual/EFCore.PG/release-notes/2.0.md b/conceptual/EFCore.PG/release-notes/2.0.md deleted file mode 100644 index 12b70b01..00000000 --- a/conceptual/EFCore.PG/release-notes/2.0.md +++ /dev/null @@ -1,41 +0,0 @@ -# 2.0 Release Notes - -Version 2.0.0 of the Npgsql Entity Framework Core provider has been released and is available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). This version works with [version 2.0.0 of Entity Framework Core](https://blogs.msdn.microsoft.com/dotnet/2017/08/14/announcing-entity-framework-core-2-0/), and contains some new Npgsql features as well. - -## New Features - -Aside from general EF Core features new in 2.0.0, the Npgsql provider contains the following major new features: - -* PostgreSQL array operation translation ([#120](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/120)). While array properties have been supported since 1.1, operations on those arrays where client-evaluated. Version 2.0 will now translate array indexing, `.Contains()`, `.SequenceEquals()` and `.Length`. See the [array mapping docs](../mapping/array.md) for more details. -* A retrying execution strategy ([#155](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/155)), which will automatically retry operations on exceptions which are considered transient. -* PostgreSQL extensions are now included in scaffolded models ([#102](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/102)). -* More LINQ operations are translated to SQL, and more database scenarios are scaffolded correctly (see [the docs](http://www.npgsql.org/efcore/mapping-and-translation.html)). - -Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/milestone/6?closed=1). Please report any problems to . - -## Upgrading from 1.x - -* Previously an Npgsql.EntityFrameworkCore.PostgreSQL.Design nuget package existed alongside the main package. Its contents have been merged into the main Npgsql.EntityFrameworkCore.PostgreSQL and no new version has been released. -* Specifying versions when specifying PostgreSQL extensions on your model is no longer supported - this was a very rarely-used feature which interfered with extension scaffolding. - -## Contributors - -Thank you very much to the following people who have contributed to the individual 2.0.x. releases. - -### [Milestone 2.0.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.2) - -Contributor | Assigned issues --------------------------------- | ---------------:| -[@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.2+is%3Aclosed+assignee%3Aroji) - -### [Milestone 2.0.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.1) - -Contributor | Assigned issues --------------------------------- | ---------------:| -[@roji](https://github.com/roji) |[5](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.1+is%3Aclosed+assignee%3Aroji) - -### [Milestone 2.0.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.0) - -Contributor | Assigned issues --------------------------------- | ---------------:| -[@roji](https://github.com/roji) | [16](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.0.0+is%3Aclosed+assignee%3Aroji) diff --git a/conceptual/EFCore.PG/release-notes/2.1.md b/conceptual/EFCore.PG/release-notes/2.1.md deleted file mode 100644 index 4362191a..00000000 --- a/conceptual/EFCore.PG/release-notes/2.1.md +++ /dev/null @@ -1,119 +0,0 @@ -# 2.1 Release Notes - -Version 2.1.0 of the Npgsql Entity Framework Core provider has been released and is available on nuget. This version works with [version 2.1.0 of Entity Framework Core](https://docs.microsoft.com/ef/core/what-is-new/ef-core-2.1), and contains some new Npgsql features as well. - -Thanks to [@rwasef1830](https://github.com/rwasef1830) and [@austindrenski](https://github.com/austindrenski) for their valuable contributions. - -## New Features - -Aside from general EF Core features new in 2.1.0, the Npgsql provider contains the following major new features: - -### Improved Spatial Support (PostGIS) - -Previous versions have allowed basic usage of PostGIS's spatial types via built-in Npgsql types such as `NpgsqlPoint`, `NpgsqlLineString`, etc. These types were limited in many ways, and no operation translation was supported. If you want to calculate, say, the distance between two points, you had to drop down to raw SQL. - -No more! Thanks to a new plugin infrastructure, the EF Core provider now has full-class support for PostGIS. You can now use the [NetTopologySuite](https://github.com/NetTopologySuite/NetTopologySuite) spatial library to map PostGIS types - NetTopologySuite's types are more complete, and best of all, the provider knows how to translate its operations to SQL. This allows you to write the following code: - -```csharp -var nearbyCities = context.Cities.Where(c => c.Location.Distance(somePoint) < 100); -``` - -See [the full documentation for more information](../mapping/nts.md). - -Thanks to [@YohDeadfall](https://github.com/YohDeadfall) for implementing support for this at the ADO level. - -### Full text search - -PostgreSQL has a powerful feature for efficient natural-language search across multiple columns and tables, [see the PostgreSQL docs for more info](https://www.postgresql.org/docs/current/static/textsearch.html). The EF Core provider now supports full-text search, allowing you to use .NET functions in your LINQ queries which will get translated to efficient PostgreSQL natural-language search queries. - -Read [the full documentation for more information](../mapping/full-text-search.md). - -Many thanks to [@rwasef1830](https://github.com/rwasef1830) for contributing this feature. - -### NodaTime date/time support - -[NodaTime](https://nodatime.org) is a powerful alternative to .NET's built-in date/time types, such as `DateTime`. The built-in types are flawed in many ways: they have problematic support for timezones, don't have a date-only or time-only types, and promote problematic programming but not making the right distinctions. If your application handles dates and times in anything but the most basic way, you should seriously consider using NodaTime. To learn more read [this blog post by Jon Skeet](https://blog.nodatime.org/2011/08/what-wrong-with-datetime-anyway.html). - -Thanks to a new plugin infrastructure, it is now possible to set up the EF Core provider to use NodaTime's types instead of the built-in .NET ones; instead of having `DateTime` properties on your entities, you can now have [Instant](https://nodatime.org/2.2.x/userguide/core-types) properties instead. - -See [the full documentation for more information](../mapping/nodatime.md). - -### PostgreSQL 10 IDENTITY columns - -PostgreSQL 10 introduced a new IDENTITY column as an alternative to traditional SERIAL columns, and these are now supported by the EF Core provider. IDENTITY columns conform to the SQL standard and are in general safer than SERIAL columns, [read this blog post for more info](https://docs.microsoft.com/ef/core/what-is-new/ef-core-2.1). It's recommended that all new projects use IDENTITY, but Npgsql even provides seamless migration of your existing SERIAL-based model!. - -Read [the full documentation for more information](../modeling/generated-properties.md). - -### Enum support - -It is now possible to map your CLR enums to [native PostgreSQL enums](https://www.postgresql.org/docs/current/static/datatype-enum.html). This is a unique PostgreSQL feature that provides the best of both worlds: the enum is internally stored in the database as a number (minimal storage), but is handled like a string (more usable, no need to remember numeric values) and has type safety. - -See [the full documentation for more information](../mapping/enum.md). - -### Range support - -PostgreSQL supports [native range types](https://www.postgresql.org/docs/current/static/rangetypes.html), which allow you to represent ranges of dates, ints and other data types in a single column. You can then efficiently perform queries on these types from LINQ, e.g. select all rows where a given date falls in the row's date range. - -See [the full documentation for more information](../mapping/range.md). - -Many thanks to [@austindrenski](https://github.com/austindrenski) for contributing the operation translations. - -### Other notable features - -* Several improvements have been made to the way arrays are mapped. For example, you can now map `List` to PostgreSQL array (previously only `T[]` was supported) ([#392](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/392)). In addition, change tracking now works for arrays, so EF Core will automatically detect when you change an element's array and will update the corresponding database column when saving. -* PostgreSQL's built-in range types can now be mapped ([#63](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/63)), head over to the [PostgreSQL docs](https://www.postgresql.org/docs/current/static/rangetypes.html) to find out more about range types. Note that user-defined range types are *not* supported, if you're interested let us know at [#329](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/329). -* Properties of type `char` are now supported and will be mapped to `character(1)` in PostgreSQL ([#374](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/374)). -* Identifiers in generated SQL will only be quoted if needed ([#327](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/327)). This should make it much easier to read. -* You can now use client certificate authentication and provide a server certificate validation callback ([#270](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/270)). See [the doc for usage instructions](http://www.npgsql.org/efcore/misc.html#certificate-authentication). -* Added support for PostgreSQL 10 sequences with type `int` and `smallint` ([#301](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/301)). -* You can now specify the [tablespace](https://www.postgresql.org/docs/current/static/manage-ag-tablespaces.html) when creating your databases ([#332](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/332)). - -Here's the [full list of issues](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/milestone/8?closed=1). Please report any problems on . - -## Breaking changes - -> [!CAUTION] -> The provider's classes have been moved from the namespace `Microsoft.EntityFrameworkCore` to `Npgsql.EntityFrameworkCore.PostgreSQL`. As a result, any migrations already generated in your project (as well as the mode snapshot) will have to be manually updated to use the new namespace. You will need to add `using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata` to all the relevant files. - -* Columns of type `timestamp with time zone`/`timestamptz` will now be scaffolded as `DateTime` properties, and not `DateTimeOffset` properties. The general use of `timestamp with time zone`/`timestamptz` is discouraged (this type does *not* store the timezone in the database), consider using `timestamp without time zone`/`timestamp` instead. -* If you're specifying index methods with `ForNpgsqlHasMethod()`, then you will have to fix migrations which generate those indexes. In these migrations, you will find code such as `.Annotation("Npgsql:Npgsql:IndexMethod", "gin")`. You must remove the extra `Npgsql:`, leaving `.Annotation("Npgsql:IndexMethod", "gin")`. -* Specifying versions when specifying PostgreSQL extensions on your model is no longer supported - this was a very rarely-used feature which interfered with extension scaffolding. -* If you're still referencing the nuget package Npgsql.EntityFrameworkCore.PostgreSQL.Design, please remove it - it's no longer needed or up to date. - -## Contributors - -Thank you very much to the following people who have contributed to the individual 2.1.x. releases. - -### [Milestone 2.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2) - -Contributor | Assigned issues ----------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [6](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Aroji) -[@austindrenski](https://github.com/austindrenski) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Aaustindrenski) -[@rwasef1830](https://github.com/rwasef1830) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.2+is%3Aclosed+assignee%3Arwasef1830) - -### [Milestone 2.1.11](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.11) - -Contributor | Assigned issues ----------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.11+is%3Aclosed+assignee%3Aroji) - -### [Milestone 2.1.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1.1) - -Contributor | Assigned issues ----------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1.1+is%3Aclosed+assignee%3Aroji) - -### [Milestone 2.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1) - -Contributor | Assigned issues ----------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [9](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.1+is%3Aclosed+assignee%3Aroji) - -### [Milestone 2.1.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0) - -| Contributor | Assigned issues -| -------------------------------------------------- | ----------------:| -| [@roji](https://github.com/roji) | [24](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Aroji) -| [@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Aaustindrenski) -| [@rwasef1830](https://github.com/rwasef1830) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.1.0+is%3Aclosed+assignee%3Arwasef1830) diff --git a/conceptual/EFCore.PG/release-notes/2.2.md b/conceptual/EFCore.PG/release-notes/2.2.md deleted file mode 100644 index 89de0f84..00000000 --- a/conceptual/EFCore.PG/release-notes/2.2.md +++ /dev/null @@ -1,81 +0,0 @@ -# 2.2 Release Notes - -Version 2.2.0 of the Npgsql Entity Framework Core provider has been released and is available on nuget. This version works with [version 2.2.0 of Entity Framework Core](https://docs.microsoft.com/ef/core/what-is-new/ef-core-2.2), and contains some new Npgsql features as well. - -This release was result of hard work by [@roji](https://github.com/roji/), [@austindrenski](https://github.com/austindrenski), [@yohdeadfall](https://github.com/yohdeadfall) and [@khellang](https://github.com/khellang). - -## New Features - -Aside from general EF Core features new in 2.2.0, the Npgsql EF Core provider contains the following major new features: - -### PostgreSQL 11 covering indexes - -PostgreSQL 11 introduced [covering indexes feature](https://paquier.xyz/postgresql-2/postgres-11-covering-indexes), which allow you to include "non-key" columns in your indexes. This allows you to perform index-only scans and can provide a significant performance boost. Support has been added in ([#697](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/697)): - -```csharp -protected override void OnConfiguring(DbContextOptionsBuilder builder) - => modelBuilder.Entity() - .ForNpgsqlHasIndex(b => b.Id) - .ForNpgsqlInclude(b => b.Name); -``` - -This will create an index for searching on `Id`, but containing also the column `Name`, so that reading the latter will not involve accessing the table. [See the documentation for more details](../modeling/indexes.md). - -Thanks to [@khellang](https://github.com/khellang) for contributing this! - -### PostgreSQL user-defined ranges - -The provider already supported [PostgreSQL range types](https://www.postgresql.org/docs/current/rangetypes.html), but prior to 2.2 that support was limited to the built-in range types which come with PostgreSQL. [#329](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/329) extends that support to range types which you define: - -```csharp -protected override void OnConfiguring(DbContextOptionsBuilder builder) - => builder.UseNpgsql("...", b => b.MapRange("floatrange")); - -protected override void OnModelCreating(ModelBuilder builder) - => builder.ForNpgsqlHasRange("floatrange", "real"); -``` - -This will make the provider create a PostgreSQL range called `floatrange`, over the PostgreSQL type `real`. Any property with type `NpgsqlRange` will be seamlessly mapped to it. - -[See the documentation for more details](../mapping/range.md). - -### Seeding for Npgsql-specific types - -When using some Npgsql-specific types, it wasn't possible to seed values for those types. With EF Core support for seeding any type, [#667](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/667) allows seeding values for network, bit and range types (more are coming). - -### PostgreSQL index operator classes - -PostgreSQL allows you to specify [operator classes on your indexes](https://www.postgresql.org/docs/current/indexes-opclass.html), to allow tweaking how the index should work. [#481](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/481) adds support for managing these. [See the documentation for more details](../modeling/indexes.md). - -Thanks to [@khellang](https://github.com/khellang) for contributing this! - -### Other features - -* Various issues with enum and range types were fixed, including upper/lower case, quoting and schema management. -* Many new SQL translations were added, so more of your LINQ expressions can run in the database. We'll be working on our documentation to make these more discoverable. - -The full list of issues for this release is [available here](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues?q=milestone%3A2.2.0+is%3Aclosed&utf8=%E2%9C%93). - -## Contributors - -Thank you very much to the following people who have contributed to the individual 2.2.x. releases. - -### [Milestone 2.2.6](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.6) - -Contributor | Assigned issues ------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) |[5](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.6+is%3Aclosed+assignee%3Aroji) - -### [Milestone 2.2.4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4+is%3Aclosed+assignee%3Aroji) -[@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.4+is%3Aclosed+assignee%3Aaustindrenski) - -### [Milestone 2.2.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.0) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@austindrenski](https://github.com/austindrenski) | [15](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.0+is%3Aclosed+assignee%3Aaustindrenski) -[@roji](https://github.com/roji) | [8](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A2.2.0+is%3Aclosed+assignee%3Aroji) diff --git a/conceptual/EFCore.PG/release-notes/3.1.md b/conceptual/EFCore.PG/release-notes/3.1.md deleted file mode 100644 index 2c39309a..00000000 --- a/conceptual/EFCore.PG/release-notes/3.1.md +++ /dev/null @@ -1,125 +0,0 @@ -# 3.1 Release Notes - -Version 3.1 of the Npgsql Entity Framework Core provider has been released and is available on nuget. This version works with [version 3.1 of Entity Framework Core](https://docs.microsoft.com/ef/core/what-is-new/ef-core-3.x), and brings new Npgsql features in addition to the general EF Core changes. - -> [!CAUTION] -> Use these versions with care and do not deploy to production without thorough testing. Read the breaking changes section below. - -The full list of issues for this release is [available here](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/milestone/20?closed=1). - -## New Features - -Aside from general EF Core features new in 3.1, the Npgsql EF Core provider contains the following major new features: - -* It is now possible to map POCOs to JSON columns and query them, [see the docs for more info](../mapping/json.md) ([#981](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/981)) -* PostgreSQL identity columns are now the default - see breaking changes below) ([#804](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/804)) -* Sequence options can now be managed on identity columns ([#819](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/819)) -* Support has been added for the upcoming [PostgreSQL 12 generated columns feature](https://www.postgresql.org/docs/12/ddl-generated-columns.html) ([#939](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/939)) -* A plugin is now available to automatically make all your tables and columns be snake_case! See [EFCore.NamingConventions](https://github.com/efcore/EFCore.NamingConventions). -* Index sort options (ascending/descending, null sort order...) can now be specified ([#326](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/326)) -* Indexes can now be created concurrently ([#967](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/967)) -* Views are now reverse-engineered ([#878](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/878)) -* Array value converters help mapping with PostgreSQL arrays (e.g. map enum arrays to integer arrays) ([#1031](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/1031)). - -## Breaking changes - -### Default value generation strategy is now IDENTITY - -> [!CAUTION] -> This is a major change, and upgrading to 3.1 with an existing database will cause a non-trivial schema migration to be generated. Read the following carefully. - -The default value generation strategy has changed from the older SERIAL columns to the newer IDENTITY columns, introduced in PostgreSQL 10. - -When producing a migration with 3.1, the Npgsql provider will attempt to automatically generate SQL to alter your tables and convert serial columns to identity ones. This is a sensitive, one-time migration operation that should be done with care, and carefully tested before deployment to production. - -If you wish to opt out of using IDENTITY columns and continue using SERIAL columns, set the following on your model: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.UseSerialColumns(); -``` - -If you are using a PostgreSQL version older than 10, setting the compatibility mode is a better way to switch the default back to SERIAL columns: - -```csharp -protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseNpgsql("...", o => o.SetPostgresVersion(9, 6)); -``` - -More information is available in [the page about generated properties](../modeling/generated-properties.md). - -## Contributors - -Thank you very much to the following people who have contributed to the individual 3.x releases. - -### [Milestone 3.1.11](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A3.1.11) - -| Contributor | Assigned issues | -| -------------------------------- | -----------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [5](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A3.1.11+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 3.1.7](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.7) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.7+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.4) - -Contributor | Assigned issues --------------------------------------------------- |-----------------:| -[@roji](https://github.com/roji) | [4](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.4+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.3) - -Contributor | Assigned issues --------------------------------------------------- |-----------------:| -[@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.3+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [3](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2+is%3Aclosed+assignee%3Aroji) -[@grzybsonssg](https://github.com/grzybsonssg) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.2+is%3Aclosed+assignee%3Agrzybsonssg) - -### [Milestone 3.1.1.2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.2) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.2+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.1) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1.1+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [6](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.1+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [15](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3Aroji) -[@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3Aaustindrenski) -[@ins0mniaque](https://github.com/ins0mniaque) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3Ains0mniaque) -[@MarioPrabowo](https://github.com/MarioPrabowo) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3AMarioPrabowo) - -### [Milestone 3.0.1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.1) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.1+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.0.0](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [25](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3Aroji) -[@austindrenski](https://github.com/austindrenski) | [2](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3Aaustindrenski) -[@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/npgsql/EFCore.PG/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3AYohDeadfall) diff --git a/conceptual/EFCore.PG/release-notes/5.0.md b/conceptual/EFCore.PG/release-notes/5.0.md deleted file mode 100644 index 4e8bf951..00000000 --- a/conceptual/EFCore.PG/release-notes/5.0.md +++ /dev/null @@ -1,112 +0,0 @@ -# 5.0 Release Notes - -Version 5.0 of the Npgsql Entity Framework Core provider has been released and is available on nuget. This version works with [version 5.0 of Entity Framework Core](https://docs.microsoft.com/ef/core/what-is-new/ef-core-5.0/whatsnew), and brings new Npgsql features in addition to the general EF Core changes. - -## New Features - -Aside from general EF Core features new in 5.0, here is a non-exhaustive list of features added in the Npgsql EF Core provider: - -* Full support for PostgreSQL collations. [See the docs](http://www.npgsql.org/efcore/misc/collations-and-case-sensitivity.html?tabs=data-annotations) for more info. -* It is now much easier to create indexes for full-text search ([#1097](https://github.com/npgsql/efcore.pg/issues/1097), [#1253](https://github.com/npgsql/efcore.pg/issues/1253)). [See the docs](../mapping/full-text-search.md) for more info. -* Sequences are now automatically updated after seeding data to avoid duplicate values ([#367](https://github.com/npgsql/efcore.pg/issues/367)). -* [The `[JsonPropertyName]` attribute](https://docs.microsoft.com/dotnet/api/system.text.json.serialization.jsonpropertynameattribute) is now respected when mapping to JSON ([#1419](https://github.com/npgsql/efcore.pg/issues/1419)). -* Improved support for PostgreSQL arrays: - * Mapping `List` is now fully supported ([#395](https://github.com/npgsql/efcore.pg/issues/395)). - * Mapping arrays of nullable value types (e.g. `int?[]`) is now supported ([#1025](https://github.com/npgsql/efcore.pg/issues/1025)). -* Query translations: - * [Precise, exhaustive documentation](http://www.npgsql.org/efcore/mapping/translations.html) has been added on which functions can be used in LINQ queries. - * `Contains` over arrays now uses indexes in various scenarios, improving performance ([#1372](https://github.com/npgsql/efcore.pg/issues/1372)). - * Various members of [TimeSpan](https://docs.microsoft.com/dotnet/api/system.timespan?view=netcore-3.1) are now translated and can be used in queries ([#328](https://github.com/npgsql/efcore.pg/issues/328)). - * Support for [unaccent](https://www.postgresql.org/docs/current/unaccent.html) ([#1530](https://github.com/npgsql/efcore.pg/issues/1530)). Thanks [@cloudlucky](https://github.com/cloudlucky). - * Various translations over byte array properties have been added ([#1225](https://github.com/npgsql/efcore.pg/issues/1225), [#1226](https://github.com/npgsql/efcore.pg/issues/1226). -* Improved null semantics for PostgreSQL-specific operations results in tighter and more efficient SQL ([#1142](https://github.com/npgsql/efcore.pg/issues/1142)). -* Better support for NodaTime: - * It is now possible to map NodaTime `Duration` to PostgreSQL `interval`, previously only `Period` could be mapped ([#1567](https://github.com/npgsql/efcore.pg/issues/1567). - * Some additional arithmetic operation are now translated ([#1565](https://github.com/npgsql/efcore.pg/issues/1565)). -* It is now possible to add labels to existing enums (but not remove or modify existing ones). The provider will generate the appropriate migrations ([#1182](https://github.com/npgsql/efcore.pg/issues/1182)). - -The full list of issues for this release is [available here](https://github.com/npgsql/efcore.pg/milestone/24?closed=1). - -## Breaking changes - -Please consult the EF Core 5.0 [breaking changes page](https://docs.microsoft.com/ef/core/what-is-new/ef-core-5.0/breaking-changes) as well - the below lists only changes specific to the Npgsql provider. - -### Computed columns must now explicitly be configured as stored ([#1336](https://github.com/npgsql/efcore.pg/issues/1336)) - -Version 3.1 of the provider added support for [PostgreSQL generated columns](https://www.postgresql.org/docs/current/ddl-generated-columns.html) ([#939](https://github.com/npgsql/efcore.pg/issues/939)), referred to as [computed columns in EF Core](https://docs.microsoft.com/ef/core/modeling/generated-properties?tabs=data-annotations#computed-columns). EF Core 5.0 adds support for specifying whether a computed column is *virtual* (computed when fetched), or *stored* (persisted on disk and computed when modified). Aligning with most databases, EF Core by default creates virtual computed columns, but these are currently unsupported by PostgreSQL. - -As a result, you must explicitly specify on all computed columns that they are stored: - -```csharp -modelBuilder.Entity() - .Property(p => p.FullName) - .HasComputedColumnSql("...", stored: true); -``` - -If you have existing migrations which were created with previous versions of EF Core, the column definitions in those also need to be fixed up with `stored: true`. - -### IsCreatedConcurrently defaults to true ([#1212](https://github.com/npgsql/efcore.pg/issues/1212)) - -Previously, when `IsCreatedConcurrently` was used to configure an index without parameters, the default was `false` - this has changed to `true`. Note that indexes are never configured for for concurrent creation unless `IsCreatedConcurrently` is specified. - -## Contributors - -A big thank you to all the following people who contributed to the 5.0 release! - -### [Milestone 5.0.10](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.10) - -| Contributor | Assigned issues | -| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [3](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.10+is%3Aclosed+assignee%3Aroji) | -| [@dmitrynovik](https://github.com/dmitrynovik) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.10+is%3Aclosed+assignee%3Admitrynovik) | - -### [Milestone 5.0.7](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.7) - -| Contributor | Assigned issues | -| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [5](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.7+is%3Aclosed+assignee%3Aroji) | -| [@nathan-c](https://github.com/nathan-c) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.7+is%3Aclosed+assignee%3Anathan-c) | - -### [Milestone 5.0.6](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.6) - -| Contributor | Assigned issues | -| ------------------------------------ | ------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [2](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.6+is%3Aclosed+assignee%3Aroji) | -| [@kakone](https://github.com/kakone) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.6+is%3Aclosed+assignee%3Akakone) | - -### [Milestone 5.0.5.1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.5.1) - -| Contributor | Assigned issues | -| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------:| -| [@fsibilla](https://github.com/fsibilla) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.5.1+is%3Aclosed+assignee%3Afsibilla) | -| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.5.1+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 5.0.5](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.5) - -| Contributor | Assigned issues | -| ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [8](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.5+is%3Aclosed+assignee%3Aroji) | -| [@DanielAdolfsson](https://github.com/DanielAdolfsson) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.5+is%3Aclosed+assignee%3ADanielAdolfsson) | - -### [Milestone 5.0.2](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.2) - -| Contributor | Assigned issues | -| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [6](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.2+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 5.0.1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.1) - -| Contributor | Assigned issues | -| ------------------------------------ | ------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [4](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.1+is%3Aclosed+assignee%3Aroji) | -| [@akilin](https://github.com/akilin) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.1+is%3Aclosed+assignee%3Aakilin) | - -### [Milestone 5.0.0](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.0) - -| Contributor | Assigned issues | -| -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [50](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Aroji) | -| [@artfulsage](https://github.com/artfulsage) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Aartfulsage) | -| [@cloudlucky](https://github.com/cloudlucky) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Acloudlucky) | -| [@plamen-i](https://github.com/plamen-i) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Aplamen-i) | -| [@Quogu](https://github.com/Quogu) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3AQuogu) | diff --git a/conceptual/EFCore.PG/release-notes/6.0.md b/conceptual/EFCore.PG/release-notes/6.0.md deleted file mode 100644 index d2f45730..00000000 --- a/conceptual/EFCore.PG/release-notes/6.0.md +++ /dev/null @@ -1,261 +0,0 @@ -# 6.0 Release Notes - -The release candidate of Npgsql Entity Framework Core provider version 6.0 has been released and is available on nuget. This version works with [version 6.0 of Entity Framework Core](https://docs.microsoft.com/ef/core/what-is-new/ef-core-6.0/whatsnew), and brings new Npgsql features in addition to the general EF Core changes. - -Npgsql 6.0 brings some major breaking changes and is not a simple in-place upgrade. Carefully read the breaking change notes below and upgrade with care. - -## New features - -### Timestamp rationalization and improvements - -Support for `timestamp with time zone` and `timestamp without time zone` has been rationalized and simplified, and aligned with PostgreSQL best practices. In particular, the "UTC everywhere" pattern is much better supported via the PostgreSQL `timestamp with time zone` type, which is the recommended way to handle timestamps. A detailed explanation is available in [this blog post](https://www.roji.org/postgresql-dotnet-timestamp-mapping), below is a summary of the main improvements. - -* UTC timestamps have been cleanly separated from non-UTC timestamps, aligning with the PostgreSQL types. The former are represented by `timestamp with time zone` and DateTime with Kind UTC, the latter by `timestamp without time zone` and DateTime with Kind Local or Unspecified. It is recommended to use UTC timestamps where possible. -* Npgsql no longer performs any implicit timezone conversions when reading or writing any timestamp value - the value in the database is what you get, and the machine timezone no longer plays any role when reading/writing values. -* Npgsql no longer supports date/time representations which cannot be fully round-tripped to the database. If it can't be fully stored as-is, you can't write it. -* A compatibility switch enables opting out of the new behavior, to maintain backwards compatibility. - -This change introduces significant breaking changes (see below), although a compatibility flag can be used to opt out and revert to the previous behavior. - -Other date/time improvements include: - -* Support for the new [.NET DateOnly and TimeOnly types](https://devblogs.microsoft.com/dotnet/date-time-and-time-zone-enhancements-in-net-6/). -* Most [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset) members and methods are now translated. -* Many NodaTime translations have been added for [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html), [Period](https://nodatime.org/3.0.x/api/NodaTime.Period.html), [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html) and others. -* PostgreSQL `tstzrange` is now mapped to NodaTime [Interval](https://nodatime.org/3.0.x/api/NodaTime.Interval.html), and PostgreSQL `daterange` is now mapped to NodaTime [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html). Most methods on these types are translated ([#1998](https://github.com/npgsql/efcore.pg/issues/1998), [#2059](https://github.com/npgsql/efcore.pg/issues/2059)). - -### Other new features - -* The provider is now fully annotated for nullable reference types. -* Full support for the PostgreSQL 14 [multirange type](https://www.postgresql.org/docs/14/rangetypes.html), mapped to arrays or lists of `NpgsqlRange` ([#1963](https://github.com/npgsql/efcore.pg/issues/1963)). Includes translation of all major operators and functions, [see the updated docs](../mapping/range.md). -* Support for PostgreSQL 14 [column compression methods](https://paquier.xyz/postgresql-2/postgres-14-table-compression/) ([#2062](https://github.com/npgsql/efcore.pg/issues/2062)). -* Support for the PostgreSQL [ltree](https://www.postgresql.org/docs/current/ltree.html) type, which represents labels of data stored in a hierarchical tree-like structure. Requires PostgreSQL 13 and above. -* Multiple spatial translations have been added for NetTopologySuite ([DistanceKnn, <->](https://github.com/npgsql/efcore.pg/issues/1827), [ST_Force2D](https://github.com/npgsql/efcore.pg/issues/1917), [ST_Distance and ST_DWithin with spheriod](https://github.com/npgsql/efcore.pg/issues/1638)). -* More translations and better type inference for arrays ([#2026](https://github.com/npgsql/efcore.pg/issues/2026)). - -The full list of issues for this release is [available here](https://github.com/npgsql/efcore.pg/milestone/34?closed=1). - -## Breaking changes - -### Major changes to timestamp mapping - -> [!NOTE] -> It is possible to opt out of these changes to maintain backwards compatibility, see below. - -#### Quick summary - -* In many cases, it makes sense to store UTC timestamps in the database. To do this, migrate your `timestamp without time zone` columns to `timestamp with time zone` ([see migration notes below](#migrating-columns-from-timestamp-to-timestamptz)), and always use either DateTime with Kind=Utc or DateTimeOffset with offset 0. - * If using NodaTime (recommended), use either [Instant](https://nodatime.org/3.0.x/api/NodaTime.Instant.html) or [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html) with time zone UTC. -* To store non-UTC timestamps, use DateTime with Kind=Unspecified and [add explicit configuration](https://docs.microsoft.com/ef/core/modeling/entity-properties#column-data-types) to your properties to be `timestamp without time zone`. - * If using NodaTime (recommended), use [LocalDateTime](https://nodatime.org/3.0.x/api/NodaTime.LocalDateTime.html) (no explicit column configuration is required). - -#### Detailed notes - -The below notes will use the PostgreSQL aliases `timestamptz` to refer to `timestamp with time zone`, and `timestamp` to refer to `timestamp without time zone`. Note that `timestamp with time zone` represents a UTC timestamp and does **not** store a timezone in the database. - -* DateTime properties now map to `timestamptz` by default, instead of to `timestamp`; this follows the recommended practice of storing UTC timestamps by default, but will cause the first migration to change your column type. - * If the intention is to store point-in-time or UTC timestamps, it's recommended to allow the migration to occur ([see migration notes below](#migrating-columns-from-timestamp-to-timestamptz)). - * If the column really should store non-UTC timestamps (local or unspecified), [explicitly set the column type back to `timestamp`](https://docs.microsoft.com/ef/core/modeling/entity-properties#column-data-types). This is usually discouraged, but can be a temporary solution before transitioning to `timestamptz`. -* It is no longer possible to write DateTime with Kinds Local or Unspecified to `timestamptz` properties (which are the default for DateTime). Previously, Npgsql allowed writing those, performing timezone conversions from local to UTC. To write to `timestamptz`, provide a UTC DateTime. Similarly, it is no longer possible to write DateTime with Kind UTC to a `timestamp` column. -* `timestamptz` values are now read back as DateTime with Kind=UTC, without any conversions; these were previously returned as local DateTime, converted to the local machine's timezone. When reading `timestamptz` values as [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset), UTC values (offset 0) are always returned. -* It is no longer possible to write [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset) with offsets other than 0 (UTC), since these cannot be represented in PostgreSQL. These were previously implicitly converted to UTC before sending. - -See the [Npgsql ADO.NET docs](/doc/release-notes/5.0.html) for additional lower-level changes to timestamp handling. - -#### NodaTime changes - -* Properties with type [Instant](https://nodatime.org/3.0.x/api/NodaTime.Instant.html) are now mapped to `timestamptz` columns, and not to `timestamp`, since they represent a universally agreed-upon point in time. This follows the recommended practice, but will cause the first migration to change your column type. - * If the intention is to store point-in-time or UTC timestamps, it's recommended to allow the migration to occur ([see migration notes below](#migrating-columns-from-timestamp-to-timestamptz)). - * If the column really should store non-UTC timestamps (local or unspecified), change the property's type to [LocalDateTime](https://nodatime.org/3.0.x/api/NodaTime.LocalDateTime.html) instead; this will maintain the mapping to `timestamp`. This is usually discouraged, but can be a temporary solution before transitioning to `timestamptz`. -* When reading `timestamptz` as [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html) or [OffsetDateTime](https://nodatime.org/3.0.x/api/NodaTime.OffsetDateTime.html), UTC values are always returned. Previously, local values based on the PostgreSQL `TimeZone` parameter were returned. - -#### Migrating columns from timestamp to timestamptz - -As a result of the above changes, the first migration created after upgrading to 6.0 will alter the columns for all DateTime and Instant properties from `timestamp` to `timestamptz`. If these columns are meant to store point-in-time or UTC timestamps (the recommended practice), then it's best to let this migration proceed; but care must be taken. - -As a starting point, let's assume your existing `timestamp` column has the timestamp `2020-01-01 12:00:00`: - -```sql -SELECT "CreatedOn", pg_typeof("CreatedOn") AS type FROM "Blogs"; -``` - -Results in: - -```output - CreatedOn | type ----------------------+----------------------------- - 2020-01-01 12:00:00 | timestamp without time zone -``` - -The migration generated by version 6.0 will cause the following SQL to be generated: - -```sql -ALTER TABLE "Blogs" ALTER COLUMN "CreatedOn" TYPE timestamp with time zone; -``` - -When converting the `timestamp without time zone` column to `timestamp with time zone`, PostgreSQL will assume that existing values are local timestamps, and will convert them to UTC based on the `TimeZone` parameter. Performing the above query will result in something like: - -```output - CreatedOn | type -------------------------+-------------------------- - 2020-01-01 12:00:00+02 | timestamp with time zone -``` - -This means that your new `timestamptz` column now contains 10:00 UTC, which is probably not what you want: if the original values were in fact UTC values, you need them to be preserved as-is, changing only the column type. To do this, edit your migration and add the following to the top of your migration's Up and Down methods: - -```csharp -migrationBuilder.Sql("SET TimeZone='UTC';"); -``` - -This will ensure that no time zone conversions will be applied when converting the columns: - -```output - CreatedOn | type -------------------------+-------------------------- - 2020-01-01 14:00:00+02 | timestamp with time zone -``` - -#### Changing timestamp seed data - -When switching from `timestamp without time zone` to `timezone with time zone`, you may have have non-UTC timestamp literals in your seeding configuration: - -```csharp -modelBuilder.Entity().HasData(new Blog { Id = 1, Timestamp = new DateTime(2020, 1, 1, 0, 0, 0) }); -``` - -If so, you'll have to change these to be UTC. In addition, all migrations code since the change must be modified in the same way, to only seed UTC DateTime into the column; the model snapshot should be changed as well. - -#### Opting out of the new timestamp mapping logic - -The changes described above are far-reaching, and may break applications in various ways. You can upgrade to version 6.0 but opt out of the new mapping by enabling the `Npgsql.EnableLegacyTimestampBehavior` [AppContext switch](https://docs.microsoft.com/en-us/dotnet/api/system.appcontext?view=net-5.0). To do this and revert to the legacy timestamp behavior, add the following to your context's constructor, before any Npgsql or EF Core operations are invoked: - -```csharp -AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); -``` - -### NodaTime: tstzrange and daterange are mapped to Interval and DateInterval by default - -When using NodaTime, PostgreSQL `tstzrange` columns are scaffolded as [Interval](https://nodatime.org/3.0.x/api/NodaTime.Interval.html) properties instead of `NpgsqlRange` ([#4070](https://github.com/npgsql/npgsql/issues/4070)), and `daterange` columns are scaffolded as [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html) properties of `NpgsqlRange` ([#1998](https://github.com/npgsql/efcore.pg/issues/1998)). - -### Date/time min/max values are now converted to PostgreSQL infinity values by default - -PostgreSQL has special `infinity` and `-infinity` values for timestamps and dates, which are later and earlier than other value. Npgsql has supported mapping `DateTime.MaxValue` and `MinValue` to these infinity values via an `Convert Infinity DateTime` connection string parameter, which was disabled by default. This behavior is now on by default, since `DateTime.MaxValue` and `MinValue` are very rarely used as actual timestamps/dates, and the `Convert Infinity DateTime` parameter has been removed. To disable infinity conversions, add the following at the start of your application: - -```csharp -AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true); -``` - -[See the date/time documentation](/doc/types/datetime.html#infinity-values) for more details. - -### Value converters for array/list properties need to use a special new API - -Previously, it was possible to configure value converters for array/list properties with the general EF Core API: - -```csharp -modelBuilder.Entity.Property(e => e.ValueConvertedArray) - .HasConversion(w => w.Select(x => x.Value).ToArray(), v => v.Select(x => new IntWrapper(x)).ToArray()); -``` - -This is no longer possible and will cause an exception to be thrown. Instead, use the new `HasPostgresArrayConversion` API, providing conversion lambdas for the array's *elements*: - -```csharp -modelBuilder.Entity.Property(e => e.ValueConvertedArray) - .HasPostgresArrayConversion(w => w.Value, v => new IntWrapper(v)); -``` - -### Arrays/lists over ranges are mapped to PG14 multiranges - -PostgreSQL 14 introduced [a new multirange type](https://www.postgresql.org/docs/14/rangetypes.html), which is very similar to an array of ranges but supports various range-related operations efficiently. The provider now maps arrays and lists of `NpgsqlRange` to these new types by default. To map them to old-style arrays over ranges in PostgreSQL, [configure the column type explicitly](https://docs.microsoft.com/ef/core/modeling/entity-properties#column-data-types): - -### [Data Annotations](#tab/annotations) - -```csharp -[Column(TypeName = "int4range[]")] -public NpgsqlRange[] SomeArrayOverIntNpgsqlRange { get; set;} -``` - -### [Fluent API](#tab/fluent-api) - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder - .Entity() - .Property(e => e.SomeArrayOverIntNpgsqlRange) - .HasColumnType("int4range[]"); -} -``` - -*** - -### Trigrams and FuzzyStringMatch plugins are now built-in - -The Npgsql.EntityFrameworkCore.PostgreSQL.Trigrams and Npgsql.EntityFrameworkCore.PostgreSQL.FuzzyStringMatch plugins have been integrated into the main provider; as a result, there are no 6.0 versions of these nuget packages - simply remove the package references from your project when upgrading to 6.0.0. - -## Contributors - -A big thank you to all the following people who contributed to the 6.0 release! - -### [Milestone 6.0.8](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.8) - -| Contributor | Assigned issues | -| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [3](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.8+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 6.0.7](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.7) - -| Contributor | Assigned issues | -| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [5](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.7+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 6.0.6](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.6) - -| Contributor | Assigned issues | -| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [2](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.6+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 6.0.5](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.5) - -| Contributor | Assigned issues | -| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [5](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.5+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 6.0.4](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.4) - -| Contributor | Assigned issues | -| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [6](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.4+is%3Aclosed+assignee%3Aroji) | -| [@kourosko](https://github.com/kourosko) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.4+is%3Aclosed+assignee%3Akourosko) | - -### [Milestone 6.0.3](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.3) - -| Contributor | Assigned issues | -| -------------------------------------- | -------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [8](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.3+is%3Aclosed+assignee%3Aroji) | -| [@rus-art](https://github.com/rus-art) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.3+is%3Aclosed+assignee%3Arus-art) | - -### [Milestone 6.0.2](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.2) - -| Contributor | Assigned issues | -| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [4](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.2+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 6.0.1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.1) - -| Contributor | Assigned issues | -| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [5](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.1+is%3Aclosed+assignee%3Aroji) | -| [@Brar](https://github.com/Brar) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.1+is%3Aclosed+assignee%3ABrar) | -| [@vonzshik](https://github.com/vonzshik) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.1+is%3Aclosed+assignee%3Avonzshik) | - -### [Milestone 6.0.0](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0) - -| Contributor | Assigned issues | -| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [56](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Aroji) | -| [@vonzshik](https://github.com/vonzshik) | [2](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Avonzshik) | -| [@arontsang](https://github.com/arontsang) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Aarontsang) | -| [@Isitar](https://github.com/Isitar) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3AIsitar) | -| [@kislovs](https://github.com/kislovs) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Akislovs) | -| [@pafrench](https://github.com/pafrench) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Apafrench) | -| [@tiborfsk](https://github.com/tiborfsk) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Atiborfsk) | diff --git a/conceptual/EFCore.PG/release-notes/7.0.md b/conceptual/EFCore.PG/release-notes/7.0.md deleted file mode 100644 index 966ae014..00000000 --- a/conceptual/EFCore.PG/release-notes/7.0.md +++ /dev/null @@ -1,139 +0,0 @@ -# 7.0 Release Notes - -## New features - -### ExecuteUpdate and ExecuteDelete - -Support has been added for the new EF Core 7.0 `ExecuteUpdate` and `ExecuteDelete`, which allow expressing arbitrary, efficient updates via LINQ. See the EF [What's new section](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#executeupdate-and-executedelete-bulk-updates) for documentation. - -### Support for DbDataSource - -Npgsql 7.0 introduced , a major improvement to how database connections and configuration are managed in System.Data. enabled rich new configuration APIs, which are also available when using the Npgsql EF provider: - -```csharp -// Create a data source with the configuration you want: -var dataSourceBuilder = new NpgsqlDataSourceBuilder(builder.Configuration.GetConnectionString("MyContext")); -dataSourceBuilder - .UseLoggerFactory(loggerFactory) // Configure ADO.NET logging - .UsePeriodicPasswordProvider(); // Automatically rotate the password periodically -await using var dataSource = dataSourceBuilder.Build(); - -// Pass your data source to the EF provider: -builder.Services.AddDbContext(options => options.UseNpgsql(dataSource); -``` - -Note that the data source configuration works at the Npgsql ADO.NET layer, and is distinct from EF-level configuration. More improvements are planned in 8.0, to make data source usage more streamlined, especially around type mapping plugins, enums, etc. - -### Extensive support for aggregate function translation - -EF Core 7.0 added support for translating provider-specific aggregate functions, and EFCore.PG builds on top of that to translate most major aggregate functions that PostgreSQL supports. This unlocks support for: - -* **string_agg**: pack a column's values into a single string, with or without a delimiter. -* **array_agg**: pack a column's values into a PostgreSQL array. This can help with efficient fetching of dependent values, avoiding the so-called "cartesian explosion" problem. -* **Statistical functions**: standard deviation, variance and many others. -* **Spatial functions**: ST_Union, ST_Collect, ST_Extent and ST_ConvexHull. -* **JSON functions**: load values from the database as JSON documents with json_agg/jsonb_agg and json_object_agg/jsonb_object_agg. - -For the PostgreSQL documentation on aggregate functions, see [this page](https://www.postgresql.org/docs/current/functions-aggregate.html). The exact translations supported by the provider are documented in the [translations page](../mapping/translations.md#aggregate-functions). - -### Row value expressions - -The provider now supports translations which make use of *row value expressions*, which are conceptually similar to tuples. Row values are particularly useful for implementing *keyset pagination*, which is much more efficient than the common, offset-base pagination. To learn more about pagination techniques, see [this documentation page](https://learn.microsoft.com/ef/core/querying/pagination). - -Here's an example comparing two row values as an implementation of keyset pagination: - -```csharp -var nextPage = context.Posts - .OrderBy(b => b.Date) - .ThenBy(b => b.PostId) - .Where(b => EF.Functions.GreaterThan( - ValueTuple.Create(b.Date, b.PostId), - ValueTuple.Create(lastDate, lastId))) - .Take(10) - .ToList(); -``` - -This generates the following SQL: - -```sql -SELECT p."PostId", p."Date" -FROM "Posts" AS p -WHERE (p."Date", p."PostId") > (@__lastDate_1, @__lastId_2) -ORDER BY p."Date", p."PostId" -LIMIT @__p_3 -``` - -To the list of row value translations, see the [translations page](../mapping/translations.md#row-value-comparisons). - -### Other new features - -* Support for PostgreSQL 15 non-distinct NULLs in unique indexes, causing unique constraint violations if a column contains multiple null values. [See the documentation for more details](../modeling/indexes.md#treating-nulls-as-non-distinct). -* Stored procedure mappings: PostgreSQL support has been added for *stored procedure mapping*, which is a new feature in EF Core 7.0. See the EF [What's new section](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#stored-procedure-mapping) for documentation. Note that PostgreSQL 14 or above is required to use this feature (for output parameters). - -## Breaking changes - -Note: version 7.0 of the lower-level Npgsql ADO.NET driver, which is used by the EF provider, also has some breaking changes. It's recommended to read the [release notes](../../Npgsql/release-notes/7.0.md) for that as well. - -### Obsoleted UseXminAsConcurrencyToken - -Starting with version 7.0, concurrency token properties can be configured via the standard EF means, rather than the PostgreSQL-specific `UseXminAsConcurrencyToken`; simply configure any `uint` property with the `IsRowVersion()` Fluent API or the `[Timestamp]` Data Annotation. [See the documentation for more details](../modeling/concurrency.md). - -### Obsoleted default column collations - -Versions 6.0 and below had a mechanism that allowed defining a "default column collation", which is applied individually to every text column by default; this differed from the database collation, which is applied once to the database at creation time. This mechanism was introduced because in PostgreSQL, the database collation is quite limited, and for example does not allow specifying non-deterministic collations (e.g. case-insensitive ones). - -However, with the introduction of [pre-convention model configuration](https://docs.microsoft.com/ef/core/modeling/bulk-configuration#pre-convention-configuration) in EF Core, it's now possible to use that generic mechanism for specifying the default collation. As a result, the Npgsql-specific mechanism has been obsoleted and will be removed in a future version. - -Default column collations involve the following code: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.UseDefaultColumnCollation(""); -} -``` - -To switch to the standard EF Core API, replace the code above with the following: - -```csharp -protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) -{ - configurationBuilder.Properties().UseCollation(""); -} -``` - -## Contributors - -A big thank you to all the following people who contributed to the 7.0 release! - -### [Milestone 7.0.11](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.11) - -| Contributor | Assigned issues | -| -------------------------------- | -----------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.11+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 7.0.4](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.4) - -| Contributor | Assigned issues | -| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [7](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.4+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 7.0.3](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.3) - -| Contributor | Assigned issues | -| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------:| -| [@jhartmann123](https://github.com/jhartmann123) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.3+is%3Aclosed+assignee%3Ajhartmann123) | -| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.3+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 7.0.1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.1) - -| Contributor | Assigned issues | -| -------------------------------- | ----------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [3](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.1+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 7.0.0](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.0) - -| Contributor | Assigned issues | -| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [35](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.0+is%3Aclosed+assignee%3Aroji) | -| [@midgleyc](https://github.com/midgleyc) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A7.0.0+is%3Aclosed+assignee%3Amidgleyc) | diff --git a/conceptual/EFCore.PG/release-notes/8.0.md b/conceptual/EFCore.PG/release-notes/8.0.md deleted file mode 100644 index 280bf8dc..00000000 --- a/conceptual/EFCore.PG/release-notes/8.0.md +++ /dev/null @@ -1,248 +0,0 @@ -# 8.0 Release Notes - -Npgsql.EntityFrameworkCore.PostgreSQL version 8.0 is out and available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). - -## Full support for primitive collection querying - -One of PostgreSQL unique features as a relational database is its rich support for [array types](https://www.postgresql.org/docs/current/arrays.html), which can be stored just like any other basic data type and queried. The Npgsql EF provider has supported mapping .NET arrays and Lists to PostgreSQL arrays for a very long time; however, with the introducion of [rich primitive collection support in EF itself](https://learn.microsoft.com/ef/core/what-is-new/ef-core-8.0/whatsnew#primitive-collections), Npgsql's support for arrays was extended to include full querying capabilities. - -### Column collections - -On to the code! You can now use any LINQ operator - or chain of operators - on top of a primitive array or list property. For example, the following queries for all blogs who have at least 3 tags starting with "x": - -```csharp -class Blog -{ - ... - public List Tags { get; set; } -} - -var blogs = await ctx.Blogs - .Where(b => b.Tags.Count(t => t.StartsWith("x")) > 3) - .ToListAsync(); -``` - -This is now translated to the following SQL: - -```sql -SELECT b."Id", b."Tags" -FROM "Blogs" AS b -WHERE ( - SELECT count(*)::int - FROM unnest(b."Tags") AS t(value) - WHERE t.value LIKE 'x%') > 3 -``` - -Such complex translations rely on the PostgreSQL [`unnest`](https://www.postgresql.org/docs/current/functions-array.html#ARRAY-FUNCTIONS-TABLE) function, which allows expanding a PostgreSQL array to a set of rows; once that's done, the array values can be queried with regular SQL. - -We can go further, querying for all blogs whose tags - or any of their posts' tags - contains a certain value: - -```csharp -var blogs = await ctx.Blogs - .Where(b => b.Tags.Union(b.Posts.SelectMany(p => p.Tags)) - .Contains("foo")) - .ToListAsync(); -``` - -This uses `unnest` both on the blog's tags on and all its posts' tags (via a lateral join), to then do a UNION On results and check whether the value is contained. - -```sql -SELECT b."Id", b."Tags" -FROM "Blogs" AS b -WHERE 'foo' IN ( - SELECT t.value - FROM unnest(b."Tags") AS t(value) - UNION - SELECT t1.value - FROM "Post" AS p - JOIN LATERAL unnest(p."Tags") AS t1(value) ON TRUE - WHERE b."Id" = p."BlogId" -) -``` - -### Parameter collections - -But that's not all... The new primitive collection support works not just on columns, but also on parameterized lists. Previously, special and limited support existed for translating Contains over a parameterized list, as follows: - -```csharp -var ids = new[] { 1, 2, 3 }; - -var blogs = await ctx.Blogs - .Where(b => ids.Contains(b.Id)) - .ToListAsync(); -``` - -This has now been extended to allow composing any LINQ operator. For example, the following query queries for any blogs which have at least one tag, where that tag starts with a list of possible prefixes: - -```csharp -var prefixes = new[] { "f", "b" }; - -var blogs = await ctx.Blogs - .Where(b => prefixes.Any(p => b.Tags.Any(t => t.StartsWith(p)))) - .ToListAsync(); -``` - -Complex, I know! This translates to the following SQL: - -```sql -SELECT b."Id", b."Tags" -FROM "Blogs" AS b -WHERE EXISTS ( - SELECT 1 - FROM unnest(@__prefixes_0) AS p(value) - WHERE EXISTS ( - SELECT 1 - FROM unnest(b."Tags") AS t(value) - WHERE p.value IS NOT NULL AND left(t.value, length(p.value)) = p.value)) -``` - -Note the two usages of `unnest` here: one is used to expand the Tags column, whereas the other is used to expand the `@__prefixes_0` array parameter that EF sends. All this machinery works together to make your LINQ query execute correctly. - -### Inline collections - -Finally, support was added to *inline collections*, which are collections specified *inside* the query. For example, let's say that the list of tag prefixes in the previous query were always the same; in that case, we'd inline the prefixes variable as follows: - -```csharp -var blogs = await ctx.Blogs - .Where(b => new[] { "f", "b" }.Any(p => b.Tags.Any(t => t.StartsWith(p)))) - .ToListAsync(); -``` - -This translates to the following: - -```sql - SELECT b."Id", b."Tags" - FROM "Blogs" AS b - WHERE EXISTS ( - SELECT 1 - FROM (VALUES ('f'::text), ('b')) AS v("Value") - WHERE EXISTS ( - SELECT 1 - FROM unnest(b."Tags") AS t(value) - WHERE left(t.value, length(v."Value")) = v."Value")) -``` - -Note that the `unnest` over the parameter has been replaced with a standard SQL `VALUES` construct, which allows constructing a set of rows inline, inside the query. - -### More information - -Exciting stuff! We hope this helps you use LINQ to model and better interact with your database. - -* [The primitive collection section](https://learn.microsoft.com/ef/core/what-is-new/ef-core-8.0/whatsnew#primitive-collections) in the EF 8.0 What's New page. -* [.NET Blog post on primitive collections](https://devblogs.microsoft.com/dotnet/announcing-ef8-preview-4/) -* [PostgreSQL-specific information on primitive collections](https://www.roji.org/queryable-pg-arrays-in-ef8), including some specialized translations done for PostgreSQL. - -## EF JSON support via ToJson() - -Version 8.0 also brings support for EF7's [JSON columns](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#json-columns) feature (ToJson), which allows mapping JSON columns via owned entity types. While the Npgsql EF provider has had POCO JSON mapping for a very long time, the full modeling of the new ToJson() allows for a more powerful mapping strategy, with more query and update features. ToJson is the recommended way to map JSON going forward. - -You can read more on ToJson in the [Npgsql JSON doc page](../mapping/json.md), and in the [EF7 what's new docs](https://learn.microsoft.com/ef/core/what-is-new/ef-core-7.0/whatsnew#json-columns). Compared to the traditional Npgsql-specific POCO approach, a much wider range of LINQ queries can now be translated. For example, you can now compose LINQ operators over collections within JSON documents: - -```csharp -var blogs = await ctx.Customers - .Where(b => b.Details.Orders.Any(o => o.Price > 8)) - .ToListAsync(); -``` - -Note that this composes a LINQ operator - Any - on top of Orders, which is a list nested inside a JSON document. This translates to the following SQL: - -```sql -SELECT c."Id", c."Details" -FROM "Customers" AS c -WHERE EXISTS ( - SELECT 1 - FROM ROWS FROM (jsonb_to_recordset(c."Details" -> 'Orders') AS ( - "Price" numeric, - "ShippingAddress" text - )) AS o - WHERE o."Price" > 8.0) -``` - -Note the [`jsonb_to_recordset`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) function, which drills into the JSON document, finds the Orders property, and then expands that out to a set of rows, which can then be queried via regular SQL. - -Similarly, updates via EF's SaveChanges() are better, and can leverage *partial updating* to only patch the part of the JSON document which has changed. For example, let's assume that we load some customer with a JSON column, and change a single property within that JSON data: - -```csharp -var customer = await ctx.Customers.SingleAsync(c => c.Details.Name == "Foo"); -customer.Details.Name = "Bar"; -await ctx.SaveChangesAsync(); -``` - -Rather than needlessly sending the entire JSON document back to PostgreSQL, the EF provider uses the [`jsonb_set`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) function to patch the specific property which changed, which is more efficient: - -```sql -UPDATE "Customers" SET "Details" = jsonb_set("Details", '{Name}', @p0) -WHERE "Id" = @p1; -``` - -## Other new features - -Version 8.0 contains many other smaller features and bug fixes, both on the EF side and on the Npgsql provider side. [See the 8.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/53?closed=1) for the full list of Npgsql EF provider issues. - -## Breaking changes - -Note: version 8.0 of the lower-level Npgsql ADO.NET driver, which is used by the EF provider, also has some breaking changes. It's recommended to read the [release notes](../../Npgsql/release-notes/8.0.md) for that as well. - -### JSON POCO and other dynamic features now require an explicit opt-in - -Because of the NativeAOT and trimming work done for Npgsql 8.0 ([release notes](../../Npgsql/release-notes/8.0.md)), certain features now require an explicit opt-in, which you must add either on your or on : - -PostgreSQL type | Default .NET type ----------------------------------------- | -------------------------- -JSON POCO mapping, JsonNode and subtypes | -Unmapped enums, ranges, multiranges | -Read PostgreSQL records as .NET tuples | - -Existing code using the above features will start throwing exceptions after upgrading to version 8.0 of the EF Core provider; the exceptions provide explicit guidance on how to add the opt-ins. - -Note that EF Core itself is not yet compatible with NativeAOT, and Npgsql can only be used in NativeAOT applications without EF Core. - -### Default PostgreSQL compatibility mode has been bumped from 12 to 14 - -This means that the provider assumes at least PostgreSQL 14; if you're running against an older version, explicitly specify the PostgreSQL version when configuring your context: - -```csharp -optionsBuilder.UseNpgsql("", o => o.SetPostgresVersion(12, 0)) -``` - -### Obsoleted HasPostgresArrayConversion - -With EF 8.0 introducing first-class support for [primitive collections](https://devblogs.microsoft.com/dotnet/announcing-ef8-preview-4), the PostgreSQL driver aligned its PostgreSQL array support to use that. As a result, `HasPostgresArrayConversion` can no longer be used to configure value-converted arrays; instead, the new standard EF mechanism can be used. - -For example, the following Npgsql-specific code would configure value conversion for a property of type `MyType[]` to a PostgreSQL array of strings in EF Core 6 or 7: - -```csharp -modelBuilder.Entity().Property(b => b.ValueConvertedArray) - .HasPostgresArrayConversion(x => x.ToString(), s => MyType.Parse(s)); -``` - -The same can now achieved with the following standard EF 8 code: - -```csharp -modelBuilder.Entity().PrimitiveCollection(b => b.ValueConvertedArray) - .ElementType() - .HasConversion(typeof(MyConverter)); - -class MyConverter : ValueConverter -{ - public MyConverter() - : base(x => x.ToString(), s => MyType.Parse(s)) - { - } -} -``` - -### `cidr` now maps to `NpgsqlCidr` instead of `ValueTuple` - -As part of improving Npgsql's support for the PostgreSQL network mappings, the PostgreSQL `cidr` type now maps to the newly-introduced , and can no longer be mapped to `ValueTuple`. - -## Contributors - -A big thank you to all the following people who contributed to the 8.0 release! - -### [Milestone 8.0.0](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A8.0.0) - -| Contributor | Assigned issues | -| ---------------------------------- | -----------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [34](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3Aroji) | -| [@zpaks](https://github.com/zpaks) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3Azpaks) | diff --git a/conceptual/EFCore.PG/release-notes/9.0.md b/conceptual/EFCore.PG/release-notes/9.0.md deleted file mode 100644 index 99908d40..00000000 --- a/conceptual/EFCore.PG/release-notes/9.0.md +++ /dev/null @@ -1,98 +0,0 @@ -# 9.0 Release Notes - -Npgsql.EntityFrameworkCore.PostgreSQL version 9.0 is out and available on [nuget.org](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). - -## Improved, unified configuration experience - -The Npgsql EF provider is built on top of the lower-level Npgsql ADO.NET provider; the configuration interface between these two layers was less than ideal, and configuration been more difficult than it should have been. For version 9.0, the configuration experience has been considerably improved. - -Since version 7, the Npgsql ADO.NET provider has been moving to [NpgsqlDataSource](../../Npgsql/basic-usage.md#data-source) as the preferred way of configuring connections and obtaining them. At the EF level, it has been possible to pass an NpgsqlDataSource instance to `UseNpgsql()`; but this required that the user separately configure a data source and manage it. In addition, features such as plugins and enums require support from both the EF and ADO.NET layers, forcing users to perform multiple setup actions at the different layers. - -With version 9, `UseNpgsql()` becomes a single point for configuration, for both the EF and ADO.NET levels. EF can now internally set up an NpgsqlDataSource, automatically applying all the necessary configuration to it, and also exposes an API to allow users to apply arbitrary configuration to it as well: - -```csharp -builder.Services.AddDbContextPool(opt => - opt.UseNpgsql( - builder.Configuration.GetConnectionString("BloggingContext"), - o => o - .SetPostgresVersion(13, 0) - .UseNodaTime() - .MapEnum("mood") - .ConfigureDataSource(dataSourceBuilder => dataSourceBuilder.UseClientCertificate(certificate)))); -``` - -In the above code, the following configuration gestures are performed: - -1. `SetPostgresVersion()` is an EF-only option to produce SQL for PostgreSQL version 13 (avoiding newer incompatible features) -2. `UseNodaTime()`, adds a plugin allowing use of NodaTime for date/time type mapping. This also requires an ADO.NET NodaTime plugin which needed to be configured separately, but this is now done automatically. -3. `MapEnum()` maps a .NET enum type. Like `UseNodaTime()`, this also used to require a separate ADO.NET configuration gesture, but is now done automatically. As an added bonus, doing this now also adds the enum to the model, causing the enum to be created in the database via EF's migrations. -4. `ConfigureDataSource()` exposes an NpgsqlDataSourceBuilder, which you can use to configure arbitrary ADO.NET options. In this example, the certificate is defined for the TLS authentication process. - -For more information, see the [getting started docs](../index.md). - -### Improved configuration for enums and plugins - -Previously, configuration around enums and plugins (NodaTime, NetTopologySuite) was complicated, requiring multiple setup actions at both the EF and the lower-level Npgsql layers. EF 9.0 improves the configuration story, allowing you to configure enums and plugins via a single EF gesture: - -```csharp -builder.Services.AddPooledDbContext(options => options.UseNpgsql( - "", - o => o.MapEnum("mood"))); -``` - -This takes care of everything - EF configuration, lower-level Npgsql configuration and even the addition of the enum to the EF model, which ensures that the enum is created in the database in EF migrations. - -See the [enum](../mapping/enum.md), [NodaTime](../mapping/nodatime.md) and [NetTopologySuite](../mapping/nts.md) documentation for more details. - -## UUIDv7 GUIDs are generated by default - -When your entity types have a `Guid` key, EF Core by default generates key values for new entities client-side - in .NET - before inserting those entity types to the database; this can be better for performance in some situations. Before version 9.0, the provider generated random GUIDs (version 4) by calling the .NET [`Guid.NewGuid()`](https://learn.microsoft.com/en-us/dotnet/api/system.guid.newguid?view=net-8.0#system-guid-newguid) function. Unfortunately, random GUIDs aren't ideal for database indexing and can cause performance issues. - -Version 9.0 of the provider now generates the recently standardized version 7 GUIDs, which is a sequential GUID type that's more appropriate for database indexes and improves their performance. This new behavior is on by default and takes effect simply by upgrading the provider version. - -See [this post](https://www.cybertec-postgresql.com/en/unexpected-downsides-of-uuid-keys-in-postgresql) for more details and performance numbers on random vs. sequential GUIDs. - -Thanks to [@ChrisJollyAU](https://github.com/ChrisJollyAU) and [@Timovzl](https://github.com/Timovzl) for contributing this improvement! - -## Other new features - -* Translate `array.Where(i => i != x)` to `array_remove(array, x)` -* Translate `DateOnly.DayNumber`, `DateOnly.FromDayNumber()` and simplify `dateOnly1.DayNumber - dateOnly2.DayNumber` to `dateOnly1 - dateOnly2`. -* Map the PostgreSQL `jsonpath` type to .NET string; this allows mapping to `jsonpath` columns. - -See the [9.0.0 milestone](https://github.com/npgsql/efcore.pg/milestone/61?closed=1) for the full list of Npgsql EF provider issues. - -## Breaking changes - -### Enum mappings must now be configured at the EF level - -Previously, enum configuration involved mapping the enum at the lower-level Npgsql layer (either via `NpgsqlDataSourceBuilder.MapEnum` or via `NpgsqlConnection.GlobalTypeMapper.MapEnum`); the EF provider automatically picked this configuration up for the EF-level setup. Unfortunately, this design created numerous issues and bugs. - -As part of the improved enum configuration story in version 9.0 ([see above](#improved-configuration-for-enums-and-plugins)), enums must now be configured at the EF level; although this is a breaking change for existing applications, it usually results in simplified setup code and fixes various bugs and problematic behavior. - -If your application calls `UseNpgsql` with a simple connection string (rather than an NpgsqlDataSource), it simply needs to add a `MapEnum` call there: - -```csharp -builder.Services.AddDbContext(options => options.UseNpgsql( - "", - o => o.MapEnum("mood"))); -``` - -All other setup code - the `MapEnum` call on `NpgsqlConnection.GlobalTypeMapper` and the `HasPostgresEnum` call in `OnModelCreating` - can be removed. - -If your application passes an NpgsqlDataSource to `UseNpgsql`, it also needs to add the `MapEnum` call as above; but the `MapEnum` call on `NpgsqlDataSourceBuilder` must also be kept. - -See the [enum documentation](../mapping/enum.md) for more information. - -## Contributors - -A big thank you to all the following people who contributed to the 9.0 release! - -### [Milestone 9.0.0](https://github.com/npgsql/efcore.pg/milestone/61?closed=1) - -Contributor | Assigned issues ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ -[@roji](https://github.com/roji) | [28](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A9.0.0+is%3Aclosed+assignee%3Aroji) -[@ChrisJollyAU](https://github.com/ChrisJollyAU) | [2](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A9.0.0+is%3Aclosed+assignee%3AChrisJollyAU) -[@Timovzl](https://github.com/Timovzl) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A9.0.0+is%3Aclosed+assignee%3ATimovzl) -[@WhatzGames](https://github.com/WhatzGames) | [1](https://github.com/Npgsql/efcore.pg/issues?q=is%3Aissue+milestone%3A9.0.0+is%3Aclosed+assignee%3AWhatzGames) diff --git a/conceptual/EFCore.PG/toc.yml b/conceptual/EFCore.PG/toc.yml deleted file mode 100644 index dd6770bf..00000000 --- a/conceptual/EFCore.PG/toc.yml +++ /dev/null @@ -1,74 +0,0 @@ -- name: Getting started - href: index.md -- name: Release notes - items: - - name: "11.0" - href: release-notes/11.0.md - - name: "10.0" - href: release-notes/10.0.md - - name: "9.0" - href: release-notes/9.0.md - - name: "8.0" - href: release-notes/8.0.md - - name: Out of support - items: - - name: "7.0" - href: release-notes/7.0.md - - name: "6.0" - href: release-notes/6.0.md - - name: "5.0" - href: release-notes/5.0.md - - name: "3.1" - href: release-notes/3.1.md - - name: "2.2" - href: release-notes/2.2.md - - name: "2.1" - href: release-notes/2.1.md - - name: "2.0" - href: release-notes/2.0.md - - name: "1.1" - href: release-notes/1.1.md -- name: Creating a model - items: - - name: Tables - href: modeling/tables.md - - name: Generated properties - href: modeling/generated-properties.md - - name: Indexes - href: modeling/indexes.md - - name: Concurrency tokens - href: modeling/concurrency.md -- name: Mapping and translation - items: - - name: General - href: mapping/general.md - - name: Translations - href: mapping/translations.md - - name: JSON - href: mapping/json.md - - name: Spatial data - href: mapping/nts.md - - name: Full text search - href: mapping/full-text-search.md - - name: Vector search - href: mapping/vector-search.md - - name: NodaTime - href: mapping/nodatime.md - - name: Arrays - href: mapping/array.md - - name: Enums - href: mapping/enum.md - - name: Ranges - href: mapping/range.md -- name: Miscellaneous - items: - - name: Collations and case sensitivity - href: misc/collations-and-case-sensitivity.md - - name: Database creation - href: misc/database-creation.md - - name: Temporal constraints - href: misc/temporal-constraints.md - - name: Other - href: misc/other.md -- name: API reference - href: "../../obj/api/EFCore.PG/" diff --git a/conceptual/Npgsql/basic-usage.md b/conceptual/Npgsql/basic-usage.md deleted file mode 100644 index 52779bfb..00000000 --- a/conceptual/Npgsql/basic-usage.md +++ /dev/null @@ -1,323 +0,0 @@ -# Npgsql Basic Usage - -## Data source - -> [!NOTE] -> The data source concept was introduced in Npgsql 7.0. If you're using an older version, see [Connections without a data source](#connections-without-a-data-source) below. - -Starting with Npgsql 7.0, the starting point for any database operation is . The data source represents your PostgreSQL database, and can hand out connections to it, or support direct execution of SQL against it. The data source encapsulates the various Npgsql configuration needed to connect to PostgreSQL, as well the connection pooling which makes Npgsql efficient. - -The simplest way to create a data source is the following: - -```csharp -var connectionString = "Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase"; -await using var dataSource = NpgsqlDataSource.Create(connectionString); -``` - -In this code, a data source is created given a *connection string*, which is used to define which database to connect to, the authentication information to use, and various other connection-related parameters. The connection string consists of key/value pairs, separated with semicolons; many options are supported in Npgsql, these are documented on the [connection string page](connection-string-parameters.md). - -Npgsql's data source supports additional configuration beyond the connection string, such as logging, advanced authentication options, type mapping management, and more. To further configure a data source, use as follows: - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder("Host=localhost;Username=test;Password=test"); -dataSourceBuilder - .UseLoggerFactory(loggerFactory) // Configure logging - .UsePeriodicPasswordProvider() // Automatically rotate the password periodically - .UseNodaTime(); // Use NodaTime for date/time types -await using var dataSource = dataSourceBuilder.Build(); -``` - -You typically build a single data source, and then use that instance throughout your application; data sources are thread-safe, and (usually) correspond to a connection pool inside Npgsql. For more information on data source configuration, consult the relevant documentation pages. - -> [!NOTE] -> If you're using NativeAOT and trimming and are concerned with minimizing application size, consider using ; this builder includes only the very minimum of functionality by default, and allows adding additional features via opt-ins. - -## Basic SQL Execution - -Once you have a data source, an can be used to execute SQL against it: - -```csharp -await using var command = dataSource.CreateCommand("SELECT some_field FROM some_table"); -await using var reader = await command.ExecuteReaderAsync(); - -while (await reader.ReadAsync()) -{ - Console.WriteLine(reader.GetString(0)); -} -``` - -More information on executing commands is provided below. - -## Connections - -In the example above, we didn't deal with a database *connection*; we just executed a command directly against a data source representing the database. Npgsql internally arranges for a connection on which to execute your command, but you don't need to concern yourself with that. - -However, in some situations it's necessary to interact with a connection, typically when some sort of state needs to persist across multiple command executions. The common example for this is a database transaction, where multiple commands need to be executed within the same transaction, on the same transaction. A data source also acts as a factory for connections, so you can do the following: - -```csharp -await using var connection = await dataSource.OpenConnectionAsync(); -``` - -At this point you have an open connection, and can execute commands against it much like we did against the data source above: - -```csharp -await using var command = new NpgsqlCommand("SELECT '8'", connection); -await using var reader = await command.ExecuteReaderAsync(); -// Consume the results -``` - -Connections must be disposed when they are no longer needed - not doing so will result in a connection leak, which can crash your program. In the above code sample, this is done via the `await using` C# construct, which ensures the connection is disposed even if an exception is later thrown. It's a good idea to keep connections open for as little time a possible: database connections are scarce resources, and keeping them open for unnecessarily long times can create unnecessary load in your application and in PostgreSQL. - -### Pooling - -Opening and closing physical connections to PostgreSQL is an expensive and long process. Therefore, Npgsql connections are *pooled* by default: closing or disposing a connection doesn't close the underlying physical connection, but rather returns it to an internal pool managed by Npgsql. The next time a connection is needed, that pooled connection is returned again. This makes open and close extremely fast operations; do not hesitate to perform them a lot if needed, rather than holding a connection needlessly open for a long time. - -For information on tweaking the pooling behavior (or turning it off), see the [pooling section](connection-string-parameters.md#pooling) in the connection string page. - -### Connections without a data source - -The data source concept is new in Npgsql 7.0, and is the recommended way to use Npgsql. When using older versions, connections are instantiated directly, rather than obtaining them from a data source: - -```csharp -await using var conn = new NpgsqlConnection(connectionString); -await conn.OpenAsync(); -``` - -Direct instantiation of connection is still supported, but is discouraged for various reasons when using Npgsql 7.0 or above. - -## Other execution methods - -Above, we executed SQL via [ExecuteReaderAsync](https://docs.microsoft.com/dotnet/api/system.data.common.dbcommand.executereaderasync). There are various ways to execute a command, based on what results you expect from it: - -1. [ExecuteNonQueryAsync](https://docs.microsoft.com/dotnet/api/system.data.common.dbcommand.executenonqueryasync): executes SQL which doesn't return any results, typically `INSERT`, `UPDATE` or `DELETE` statements. Returns the number of rows affected. -2. [ExecuteScalarAsync](https://docs.microsoft.com/dotnet/api/system.data.common.dbcommand.executescalarasync): executes SQL which returns a single, scalar value. -3. [ExecuteReaderAsync](https://docs.microsoft.com/dotnet/api/system.data.common.dbcommand.executereaderasync): execute SQL which returns a full resultset. Returns an which can be used to access the resultset (as in the above example). - -For example, to execute a simple SQL `INSERT` which does not return anything, you can use `ExecuteNonQueryAsync` as follows: - -```csharp -await using var command = dataSource.CreateCommand("INSERT INTO some_table (some_field) VALUES (8)"); -await command.ExecuteNonQueryAsync(); -``` - -Note that each execute method involves a database roundtrip. To execute multiple SQL statements in a single roundtrip, see the [batching section](#batching) below. - -## Parameters - -When sending data values to the database, always consider using parameters rather than including the values in the SQL as follows: - -```csharp -await using var cmd = new NpgsqlCommand("INSERT INTO table (col1) VALUES ($1), ($2)", conn) -{ - Parameters = - { - new() { Value = "some_value" }, - new() { Value = "some_other_value" } - } -}; - -await cmd.ExecuteNonQueryAsync(); -``` - -The `$1` and `$2` in your SQL are *parameter placeholders*: they refer to the corresponding parameter in the command's parameter list, and are sent along with your query. This has the following advantages over embedding the value in your SQL: - -1. Parameters protect against SQL injection for user-provided inputs: the parameter data is sent to PostgreSQL separately from the SQL, and is never interpreted as SQL. -2. Parameters are required to make use of [prepared statements](prepare.md), which significantly improve performance if you execute the same SQL many times. -3. Parameter data is sent in an efficient, binary format, rather than being represented as a string in your SQL. - -Note that PostgreSQL does not support parameters in arbitrary locations - you can only parameterize data values. For example, trying to parameterize a table or column name will fail - parameters aren't a simple way to stick an arbitrary string in your SQL. - -### Positional and named placeholders - -Starting with Npgsql 6.0, the recommended placeholder style is *positional* (`$1`, `$2`); this is the native parameter style used by PostgreSQL, and your SQL can therefore be sent to the database as-is, without any manipulation. - -For legacy and compatibility reasons, Npgsql also supports *named placeholders*. This allows the above code to be written as follows: - -```csharp -await using var cmd = new NpgsqlCommand("INSERT INTO table (col1) VALUES (@p1), (@p2)", conn) -{ - Parameters = - { - new("p1", "some_value"), - new("p2", "some_other_value") - } -}; - -await cmd.ExecuteNonQueryAsync(); -``` - -Rather than matching placeholders to parameters by their position, Npgsql matches these parameter by name. This can be useful when porting database code from other databases, where named placeholders are used. However, since this placeholder style isn't natively supported by PostgreSQL, Npgsql must parse your SQL and rewrite it to use positional placeholders under the hood; this rewriting has a performance price, and some forms of SQL may not be parsed correctly. It's recommended to use positional placeholders whenever possible. - -For more information, see [this blog post](https://www.roji.org/parameters-batching-and-sql-rewriting). - -### Parameter types - -PostgreSQL has a strongly-typed type system: columns and parameters have a type, and types are usually not implicitly converted to other types. This means you have to think about which type you will be sending: trying to insert a string into an integer column (or vice versa) will fail. - -In the example above, we let Npgsql *infer* the PostgreSQL data type from the .NET type: when Npgsql sees a .NET `string`, it automatically sends a parameter of PostgreSQL type `text` (note that this isn't the same as, say `varchar`). In many cases this will work just fine, and you don't need to worry. In some cases, however, you will need to explicitly set, or *coerce*, the parameter type. For example, although Npgsql sends .NET `string` as `text` by default, it also supports sending `jsonb`. For more information on supported types and their mappings, see [this page](types/basic.md). - -`NpgsqlParameter` exposes several properties that allow you to coerce the parameter's data type: - -* `DbType`: a portable enum that can be used to specify database types. While this approach will allow you to write portable code across databases, it won't let you specify types that are specific to PostgreSQL. This is useful mainly if you're avoiding Npgsql-specific types, using [`DbConnection`](https://docs.microsoft.com/dotnet/api/system.data.common.dbconnection) and [`DbCommand`](https://docs.microsoft.com/dotnet/api/system.data.common.dbcommand) rather than and . -* `NpgsqlDbType`: an Npgsql-specific enum that contains (almost) all PostgreSQL types supported by Npgsql. -* `DataTypeName`: an Npgsql-specific string property which allows to directly set a PostgreSQL type name on the parameter. This is rarely needed - `NpgsqlDbType` should be suitable for the majority of cases. However, it may be useful if you're using unmapped user-defined types ([enums or composites](types/enums_and_composites.md)) or some PostgreSQL type which isn't included in `NpgsqlDbType` (because it's supported via an external plugin). - -### Strongly-typed parameters - -The standard ADO.NET parameter API is unfortunately weakly-typed: parameter values are set on `NpgsqlParameter.Value`, which, being an `object`, boxes value types such as `int`. If you're sending lots of value types to the database, this creates large amounts of useless heap allocations and strain the garbage collector. - -As an alternative, you can use `NpgsqlParameter`. This generic class has a `TypedValue` member, which is similar to `NpgsqlParameter.Value` but is strongly-typed, thus avoiding the boxing and heap allocation. Note that this strongly-typed parameter API is entirely Npgsql-specific, and will make your code non-portable to other database. See [#8955](https://github.com/dotnet/corefx/issues/8955) for an issue discussing this at the ADO.NET level. - -## Transactions - -### Basic transactions - -Transactions can be started by calling the standard ADO.NET method [`NpgsqlConnection.BeginTransaction()`](https://learn.microsoft.com/dotnet/api/system.data.common.dbconnection.begintransactionasync?view=net-6.0): - -```csharp -await using var connection = await dataSource.OpenConnectionAsync(); -await using var transaction = await connection.BeginTransactionAsync(); - -await using var command1 = new NpgsqlCommand("...", connection, transaction); -await command1.ExecuteNonQueryAsync(); - -await using var command2 = new NpgsqlCommand("...", connection, transaction); -await command2.ExecuteNonQueryAsync(); - -await transaction.CommitAsync(); -``` - -PostgreSQL doesn't support nested or concurrent transactions - only one transaction may be in progress at any given moment (starting a transaction while another transaction is already in progress throws an exception). Because of this, it isn't necessary to pass the NpgsqlTransaction object returned from `BeginTransaction()` to commands you execute - starting a transaction means that all subsequent commands will automatically participate in the transaction, until either a commit or rollback is performed. However, for maximum portability it's recommended to set the transaction on your commands. - -Although concurrent transactions aren't supported, PostgreSQL supports the concept of *savepoints* - you may set named savepoints in a transaction and roll back to them later without rolling back the entire transaction. Savepoints can be created, rolled back to, and released via [`NpgsqlTransaction.SaveAsync()`](https://docs.microsoft.com/dotnet/api/system.data.common.dbtransaction.saveasync), [`RollbackAsync()`](https://docs.microsoft.com/dotnet/api/system.data.common.dbtransaction.rollbackasync) and [`Release(name)`](https://docs.microsoft.com/dotnet/api/system.data.common.dbtransaction.releaseasync) respectively. [See the PostgreSQL documentation for more details.](https://www.postgresql.org/docs/current/static/tutorial-transactions.html). - -When starting a transaction, you may optionally set the *isolation level*. [See the docs for more details.](https://www.postgresql.org/docs/current/static/transaction-iso.html) - -### System.Transactions and distributed transactions - -In addition to `BeginTransactionAsync()`, .NET includes System.Transactions, an alternative API for managing transactions - [read the MSDN docs to understand the concepts involved](https://msdn.microsoft.com/library/ee818746.aspx). Npgsql fully supports this API, and automatically enlists if a connection is opened within an ambient TransactionScopes. - -When a transaction includes more than one database (or even more than one concurrent connections to the same database), the transaction is said to be *distributed*. .NET 7.0 brings the same distributed transaction support that .NET Framework supported, for Windows only. While Npgsql partially supports this mechanism, it does not implement the recovery parts of the distributed transaction, because of some design issues with .NET's support. While distributed transactions may work for you, it is discouraged to fully rely on them with Npgsql. - -Note that if you open and close connections to the same database inside an ambient transaction, without ever having two connections open *at the same time*, Npgsql internally reuses the same connection, avoiding the need for a distributed transaction. - -## Batching - -Let's say you need to execute two SQL statements for some reason. This can naively be done as follows: - -```csharp -await using var cmd = new NpgsqlCommand("INSERT INTO table (col1) VALUES ('foo')", conn); -await cmd.ExecuteNonQueryAsync(); - -cmd.CommandText = "SELECT * FROM table"; -await using var reader = await cmd.ExecuteReaderAsync(); -``` - -The above code needlessly performs two roundtrips to the database: your program will not send the `SELECT` until after the `INSERT` has completed and confirmation for that has been received. Network latency can make this very inefficient: as the distance between your .NET client and PostgreSQL increases, the time spent waiting for packets to cross the network can severely impact your application's performance. - -Instead, you can ask Npgsql to send the two SQL statements in a single roundtrip, by using batching: - -```csharp -await using var batch = new NpgsqlBatch(conn) -{ - BatchCommands = - { - new("INSERT INTO table (col1) VALUES ('foo')"), - new("SELECT * FROM table") - } -}; - -await using var reader = await batch.ExecuteReaderAsync(); -``` - -An simply contains a list of `NpgsqlBatchCommands`, each of which has a `CommandText` and a list of parameters (much like an ). All statements and parameters are efficiently packed into a single packet - when possible - and sent to PostgreSQL. - -> [!NOTE] -> If you haven't started an explicit transaction with , a batch is automatically wrapped in an implicit transaction. That is, if a statement within the batch fails, all later statements are skipped and the entire batch is rolled back. - -### Legacy batching - -Prior to Npgsql 6.0, `NpgsqlBatch` did not yet exist, and batching could be done as follows: - -```csharp -await using var cmd = new NpgsqlCommand("INSERT INTO table (col1) VALUES ('foo'); SELECT * FROM table", conn); -await using var reader = await cmd.ExecuteReaderAsync(); -``` - -This packs multiple SQL statements into the `CommandText` of a single `NpgsqlCommand`, delimiting them with semi-colons. This technique is still supported, and can be useful when porting database code from other database. However, legacy batching is generally discouraged since it isn't natively supported by PostgreSQL, forcing Npgsql to parse the SQL to find semicolons. This is similar to *named parameter placeholders*, [see this section for more details](#positional-and-named-placeholders). - -## Stored functions and procedures - -PostgreSQL supports [stored (or server-side) functions](https://www.postgresql.org/docs/current/static/sql-createfunction.html), and since PostgreSQL 11 also [stored procedures](https://www.postgresql.org/docs/current/sql-createprocedure.html). These can be written in SQL (similar to views), or in [PL/pgSQL](https://www.postgresql.org/docs/current/static/plpgsql.html) (PostgreSQL's procedural language), [PL/Python](https://www.postgresql.org/docs/current/static/plpython.html) or several other server-side languages. - -Once a function or procedure has been defined, calling it is a simple matter of executing a regular command: - -```csharp -// For functions -using var cmd = new NpgsqlCommand("SELECT my_func(1, 2)", conn); -using var reader = cmd.ExecuteReader(); - -// For procedures -using var cmd = new NpgsqlCommand("CALL my_proc(1, 2)", conn); -using var reader = cmd.ExecuteReader(); -``` - -You can replace the parameter values above with regular placeholders (e.g. `$1`), just like with a regular query. - -### CommandType.StoredProcedure - -> [!WARNING] -> Starting with Npgsql 7.0, [`CommandType.StoredProcedure`](https://learn.microsoft.com/dotnet/api/system.data.commandtype#system-data-commandtype-storedprocedure) now invokes stored procedures, and not function as before. See the [release notes](release-notes/7.0.md#commandtype_storedprocedure) for more information and how to opt out of this change. - -In some other databases, calling a stored procedures involves setting the command's `CommandType`: - -```csharp -using var command1 = new NpgsqlCommand("my_procedure", connection) -{ - CommandType = CommandType.StoredProcedure, - Parameters = - { - new() { Value = 8 } - } -}; -await using var reader = await command1.ExecuteReaderAsync(); -``` - -Npgsql supports this mainly for portability, but this style of calling has no advantage over the regular command shown above. When `CommandType.StoredProcedure` is set, Npgsql will simply generate the appropriate `CALL my_procedure($1)` for you, nothing more. Unless you have specific portability requirements, it is recommended you simply avoid `CommandType.StoredProcedure` and construct the SQL yourself. - -Be aware that `CommandType.StoredProcedure` generates a `CALL` command, which is suitable for invoking stored procedures and not functions. Versions of Npgsql prior to 7.0 generated a `SELECT` command suitable for functions, and this legacy behavior can be enabled; see the [7.0 release notes](release-notes/7.0.md#commandtype_storedprocedure) - -Note that if `CommandType.StoredProcedure` is set and your parameter instances have names, Npgsql generates parameters with `named notation`: `SELECT my_func(p1 => 'some_value')`. This means that your NpgsqlParameter names must match your PostgreSQL procedure or function parameters, or the call will fail. If you omit the names on your NpgsqlParameters, positional notation will be used instead. Note that positional parameters must always come before named ones. [See the PostgreSQL docs for more info](https://www.postgresql.org/docs/current/static/sql-syntax-calling-funcs.html). - -### Function in/out parameters - -In SQL Server (and possibly other databases), functions can have output parameters, input/output parameters, and a return value, which can be either a scalar or a table (TVF). To call functions with special parameter types, the `Direction` property must be set on the appropriate `DbParameter`. PostgreSQL functions, on the hand, always return a single table - they can all be considered TVFs. Somewhat confusingly, PostgreSQL does allow your functions to be defined with input/and output parameters: - -```csharp -CREATE FUNCTION dup(in int, out f1 int, out f2 text) - AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$ - LANGUAGE SQL; -``` - -However, the above syntax is nothing more than a definition of the function's resultset, and is identical to the following ([see the PostgreSQL docs](https://www.postgresql.org/docs/current/static/sql-createfunction.html)): - -```csharp -CREATE FUNCTION dup(int) RETURNS TABLE(f1 int, f2 text) - AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$ - LANGUAGE SQL; -``` - -In other words, PostgreSQL functions don't have output parameters that are distinct from the resultset they return - output parameters are just a syntax for describing that resultset. Because of this, on the Npgsql side there's no need to think about output (or input/output) parameters: simply invoke the function and process its resultset just like you would any regular resultset. - -However, to help portability, Npgsql does provide support for output parameters as follows: - -```csharp -using (var cmd = new NpgsqlCommand("SELECT my_func()", conn)) -{ - cmd.Parameters.Add(new NpgsqlParameter("p_out", DbType.String) { Direction = ParameterDirection.Output }); - cmd.ExecuteNonQuery(); - Console.WriteLine(cmd.Parameters[0].Value); -} -``` - -When Npgsql sees a parameter with `ParameterDirection.Output` (or `InputOutput`), it will simply search the function's resultset for a column whose name matches the parameter, and copy the first row's value into the output parameter. This provides no value whatsoever over processing the resultset yourself, and is discouraged - you should only use output parameters in Npgsql if you need to maintain portability with other databases which require it. diff --git a/conceptual/Npgsql/compatibility.md b/conceptual/Npgsql/compatibility.md deleted file mode 100644 index 31e6204e..00000000 --- a/conceptual/Npgsql/compatibility.md +++ /dev/null @@ -1,56 +0,0 @@ -# Compatibility Notes - -This page centralizes Npgsql's compatibility status with PostgreSQL and other components, and documents some important gotchas. - -## PostgreSQL - -We aim to be compatible with all [currently supported PostgreSQL versions](http://www.postgresql.org/support/versioning/), which means 5 years back. -Earlier versions may still work but we don't perform continuous testing on them or commit to resolving issues on them. - -## ADO.NET - -Npgsql is an ADO.NET-compatible provider, so it has the same APIs as other .NET database drivers and should behave the same. -Please let us know if you notice any non-standard behavior. - -## NativeAOT and trimming - -NativeAOT allows using ahead-of-time compilation to publish a fully self-contained application that has been compiled to native code. Native AOT apps have faster startup time and smaller memory footprints, and thanks to trimming can also have a much smaller size footprint on disk. - -Starting with version 8.0, Npgsql is fully compatible with NativeAOT and trimming. The majority of features are compatible with NativeAOT/trimming and can be used without issues, and most applications using Npgsql can be used as-is with NativeAOT/trimming without any changes. A few features which are incompatible require an explicit code opt-in, which generates a warning if used with NativeAOT/trimming enabled. - -## .NET Framework/.NET Core/mono - -Npgsql 4.* targets .NET Framework 4.6.1, as well as [.NET Standard 2.0](https://docs.microsoft.com/en-us/dotnet/standard/net-standard) which allows it to run on .NET Core. It is also tested and runs well on mono. - -Npgsql 5.* targets .NET Standard 2.0 and .NET 5. Starting with this version, we no longer run regression tests on .NET Framework and mono. In addition, the Visual Studio extension (VSIX) and the MSI GAC installer have been discontinued. - -## pgbouncer - -Npgsql works well with PgBouncer, but there are some quirks to be aware of. - -* In many cases, you'll want to turn off Npgsql's internal connection pool by specifying `Pooling=false` on the connection string. -* If you decide to keep Npgsql pooling on along with PgBouncer, and are using PgBouncer's transaction or statement mode, then you need to specify `No Reset On Close=true` on the connection string. This disables Npgsql's connection reset logic (`DISCARD ALL`), which gets executed when a connection is returned to Npgsql's pool, and which makes no sense in these modes. -* Prior to version 3.1, Npgsql sends the `statement_timeout` startup parameter when it connects, but this parameter isn't supported by pgbouncer. - You can get around this by specifying `CommandTimeout=0` on the connection string, and then manually setting the `CommandTimeout` - property on your `NpgsqlCommand` objects. Version 3.1 no longer sends `statement_timeout`. -* PgBouncer below 1.12 doesn't support SASL authentication. - -## Amazon Redshift - -Amazon Redshift is a cloud-based data warehouse originally based on PostgreSQL 8.0.2. -In addition, due to its nature some features have been removed and others changed in ways that make them incompatible with PostgreSQL. -We try to support Redshift as much as we can, please let us know about issues you run across. - -First, check out Amazon's [page about Redshift and PostgreSQL](http://docs.aws.amazon.com/redshift/latest/dg/c_redshift-and-postgres-sql.html) which -contains lots of useful compatibility information. - -Additional known issues: - -* If you want to connect over SSL, your connection string must contain `Server Compatibility Mode=Redshift`, otherwise you'll get a connection - error about `ssl_renegotiation_limit`. -* Entity Framework with database-computed identity values don't work with Redshift, since it doesn't support sequences -(see issue [#544](https://github.com/npgsql/npgsql/issues/544)). - -## DigitalOcean Managed Database - -DigitalOcean's Managed Database services requires you to connect to PostgreSQL over SSL. Unfortunately when you enable it in your connection string, you will get the same error regarding `ssl_renegotiation_limit` as Amazon Redshift. The Redshift compatibility mode setting resolves the issue on DigitalOcean. diff --git a/conceptual/Npgsql/connection-string-parameters.md b/conceptual/Npgsql/connection-string-parameters.md deleted file mode 100644 index 30cfd2cd..00000000 --- a/conceptual/Npgsql/connection-string-parameters.md +++ /dev/null @@ -1,127 +0,0 @@ -# Connection String Parameters - -To connect to a database, the application provides a connection string which specifies parameters such as the host, the username, the password, etc. Connection strings have the form `keyword1=value; keyword2=value;` and are case-insensitive. Values containing special characters (e.g. semicolons) can be double-quoted. For more information, [see the official doc page on connection strings](https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings). - -Below are the connection string parameters which Npgsql understands, as well as some standard PostgreSQL environment variables. - -## Basic connection - -Parameter | Description | Default ------------- | ---------------------------------------------------------------------------------- | ------- -Host | Specifies the host name - and optionally port - on which PostgreSQL is running. Multiple hosts may be specified, [see the docs for more info](failover-and-load-balancing.md). If the value begins with a slash, it is used as the directory for the Unix-domain socket (specifying a `Port` is still required). | *Required* -Port | The TCP port of the PostgreSQL server. | 5432 -Database | The PostgreSQL database to connect to. | Same as Username -Username | The username to connect with. If not specified, the OS username will be used. | PGUSER -Password | The password to connect with. Not required if using GSS/SSPI. | PGPASSWORD -Passfile | Path to a PostgreSQL password file (PGPASSFILE), from which the password is taken. | PGPASSFILE - -## Security and encryption - -Parameter | Description | Default ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------- -GSS Encryption Mode | Controls whether GSS encryption is used, depending on server support. [See docs for possible values and more info](security.md). | Prefer -SSL Mode | Controls whether SSL is used, depending on server support. [See docs for possible values and more info](security.md). | Prefer -Trust Server Certificate | Whether to trust the server certificate without validating it. [See docs for more info](security.md). | false -SSL Certificate | Location of a client certificate to be sent to the server. [See docs](security.md). | PGSSLCERT -SSL Key | Location of a client key for a client certificate to be sent to the server. | PGSSLKEY -SSL Password | Password for a key for a client certificate. | -Root Certificate | Location of a CA certificate used to validate the server certificate. | PGSSLROOTCERT -Check Certificate Revocation | Whether to check the certificate revocation list during authentication. | false -SSL Negotiation | Controls how SSL encryption is negotiated with the server, if SSL is used. Introduced in 9.0. [See docs for possible values and more info](security.md). | PGSSLNEGOTIATION -Channel Binding | Control whether channel binding is used when authenticating with SASL. Introduced in 8.0. | Prefer -Persist Security Info | Gets or sets a Boolean value that indicates if security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. | false -Kerberos Service Name | The Kerberos service name to be used for authentication. [See docs for more info](security.md). | postgres -Include Realm | The Kerberos realm to be used for authentication. [See docs for more info](security.md). -Include Error Detail | When enabled, PostgreSQL error and notice details are included on and . These can contain sensitive data. | false -Log Parameters | When enabled, parameter values are logged when commands are executed. | false - -## Pooling - -Parameter | Description | Default ---------------------------- | ------------------------------------------ | ------- -Pooling | Whether connection pooling should be used. | true -Minimum Pool Size | The minimum connection pool size. | 0 -Maximum Pool Size | The maximum connection pool size. | 100 since 3.1, 20 previously -Connection Idle Lifetime | The time (in seconds) to wait before closing idle connections in the pool if the count of all connections exceeds `Minimum Pool Size`. Introduced in 3.1. | 300 -Connection Pruning Interval | How many seconds the pool waits before attempting to prune idle connections that are beyond idle lifetime (see `Connection Idle Lifetime`). Introduced in 3.1. | 10 -Connection Lifetime | The total maximum lifetime of connections (in seconds). Connections which have exceeded this value will be destroyed instead of returned from the pool. This is useful in clustered configurations to force load balancing between a running server and a server just brought online. | 3600 (1 hour) since 9.0, 0 (disabled) previously - -## Timeouts and keepalive - -Parameter | Description | Default ------------------------- | ------------------------------------------------------------ | ------- -Timeout | The time to wait (in seconds) while trying to establish a connection before terminating the attempt and generating an error. | 15 -Command Timeout | The time to wait (in seconds) while trying to execute a command before terminating the attempt and generating an error. Set to zero for infinity. | 30 -Cancellation Timeout | The time to wait (in milliseconds) while trying to read a response for a cancellation request for a timed out or cancelled query, before terminating the attempt and generating an error. -1 skips the wait, 0 means infinite wait. Introduced in 5.0. | 2000 -Keepalive | The number of seconds of connection inactivity before Npgsql sends a keepalive query. | 0 (disabled) -Tcp Keepalive | Whether to use TCP keepalive with system defaults if overrides isn't specified. | false -Tcp Keepalive Time | The number of seconds of connection inactivity before a TCP keepalive query is sent. Use of this option is discouraged, use KeepAlive instead if possible. | 0 (disabled) -Tcp Keepalive Interval | The interval, in seconds, between when successive keep-alive packets are sent if no acknowledgement is received. `Tcp KeepAlive Time` must be non-zero as well. | value of `Tcp Keepalive Time` - -## Performance - -Parameter | Description | Default --------------------------- | ------------------------------------------------------------ | ------- -Max Auto Prepare | The maximum number SQL statements that can be automatically prepared at any given point. Beyond this number the least-recently-used statement will be recycled. Zero disables automatic preparation. | 0 -Auto Prepare Min Usages | The minimum number of usages an SQL statement is used before it's automatically prepared. | 5 -Read Buffer Size | Determines the size of the internal buffer Npgsql uses when reading. Increasing may improve performance if transferring large values from the database. | 8192 -Write Buffer Size | Determines the size of the internal buffer Npgsql uses when writing. Increasing may improve performance if transferring large values to the database. | 8192 -Socket Receive Buffer Size | Determines the size of socket receive buffer. | System-dependent -Socket Send Buffer Size | Determines the size of socket send buffer. | System-dependent -No Reset On Close | Improves performance in some cases by not resetting the connection state when it is returned to the pool, at the cost of leaking state. Use only if benchmarking shows a performance improvement | false - -## Failover and load balancing - -For more information, [see the dedicated docs page](failover-and-load-balancing.md). - -Parameter | Description | Default -------------------------- | -------------------------------------------------------------------------- | ------------------------- -Target Session Attributes | Determines the preferred PostgreSQL target server type. | PGTARGETSESSIONATTRS, Any -Load Balance Hosts | Enables balancing between multiple hosts by round-robin. | false -Host Recheck Seconds | Controls for how long the host's cached state will be considered as valid. | 10 - -## Misc - -Parameter | Description | Default ------------------------- | ---------------------------------------------------------------------------------------------------- | ---------- -Options[1](#misc_sup_1) | Specifies any valid [PostgreSQL connection options](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-OPTIONS) (e.g. `Options=-c synchronous_commit=local`). Introduced in 5.0. | PGOPTIONS -Application Name | The optional application name parameter to be sent to the backend during connection initiation. | PGAPPNAME -Enlist | Whether to enlist in an ambient TransactionScope. | true -Search Path | Sets the schema search path. | -Client Encoding | Gets or sets the client_encoding parameter. | PGCLIENTENCODING, UTF8 -Encoding | Gets or sets the .NET encoding that will be used to encode/decode PostgreSQL string data. | UTF8 -Timezone | Gets or sets the session timezone. | PGTZ -Array Nullability Mode | Configure the way arrays of value types are returned when requested as object instances. Possible values are: `Never` (arrays of value types are always returned as non-nullable arrays), `Always` (arrays of value types are always returned as nullable arrays) and `PerInstance` (the type of array that gets returned is determined at runtime). | Never - -1The `Options` connection string parameter is essentially the string of command line options that get passed to the [`postgres`](https://www.postgresql.org/docs/current/app-postgres.html) program when the process is started. -It is most commonly used to set named run-time parameters via the `-c` option but other options can be used too (although not all of them make sense in that context). -Setting multiple options is possible by separating them with a space character. Space and backslash characters in option values need to be escaped by prefixing a backslash character. -Example: `Options=-c default_transaction_isolation=serializable -c default_transaction_deferrable=on -c foo.bar=My\\ Famous\\\\Thing` - -## Obsolete/removed - -Parameter | Description | Default -------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------- -Load Table Composites | Load table composite type definitions, and not just free-standing composite types. Obsoleted in 9.0, use `NpgsqlDataSourceBuilder.ConfigureTypeLoading()`. | false -Server Compatibility Mode | A compatibility mode for special PostgreSQL server types. Currently "Redshift" is supported, as well as "NoTypeLoading", which will bypass the normal type loading mechanism from the PostgreSQL catalog tables and supports a hardcoded list of basic types. Obsoleted in 9.0, use `NpgsqlDataSourceBuilder.ConfigureTypeLoading()`. | none -Internal Command Timeout | The time to wait (in seconds) while trying to execute an internal command before terminating the attempt and generating an error. -1 uses CommandTimeout, 0 means no timeout. | -1 -EF Template Database | The database template to specify when creating a database in non-core Entity Framework. Removed in 8.0. | template1 -EF Admin Database | The database admin to specify when creating and dropping a database in non-core Entity Framework. Removed in 8.0. | template1 - -## Environment variables - -In addition to the connection string parameters above, Npgsql also recognizes the standard PostgreSQL environment variables below. This helps Npgsql-based applications behave similar to other, non-.NET PostgreSQL client applications. The PostgreSQL doc page on environment variables recognized by libpq can be found [here](https://www.postgresql.org/docs/current/libpq-envars.html). - -Environment variable | Description --------------------- | ----------- -PGUSER | Behaves the same as the [user](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-USER) connection parameter. -PGPASSWORD | Behaves the same as the [password](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-PASSWORD) connection parameter. Use of this environment variable is not recommended for security reasons, as some operating systems allow non-root users to see process environment variables via ps; instead consider using a password file (see [Section 33.15](https://www.postgresql.org/docs/current/libpq-pgpass.html)). -PGPASSFILE | Behaves the same as the [passfile](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-PASSFILE) connection parameter. -PGSSLCERT | Behaves the same as the [sslcert](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLCERT) connection parameter. -PGSSLKEY | Behaves the same as the [sslkey](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLKEY) connection parameter. -PGSSLROOTCERT | Behaves the same as the [sslrootcert](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLROOTCERT) connection parameter. -PGCLIENTENCODING | Behaves the same as the [client_encoding](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-CLIENT-ENCODING) connection parameter. -PGTZ | Sets the default time zone. (Equivalent to SET timezone TO ....) -PGOPTIONS | Behaves the same as the [options](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-OPTIONS) connection parameter. -PGAPPNAME | Behaves the same as the [application_name](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-APPLICATION-NAME) connection parameter. -PGSSLNEGOTIATION | Behaves the same as the [sslnegotiation](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLNEGOTIATION) connection parameter. diff --git a/conceptual/Npgsql/contributing.md b/conceptual/Npgsql/contributing.md deleted file mode 100644 index 3c3b9c72..00000000 --- a/conceptual/Npgsql/contributing.md +++ /dev/null @@ -1,3 +0,0 @@ -# Contributing to Npgsql - -As a general rule, Npgsql makes no attempt to validate what it sends to PostgreSQL. For all cases where PostgreSQL would simply return a reasonable error, we prefer that to happen rather than checking replicating validation checks client-side. diff --git a/conceptual/Npgsql/copy.md b/conceptual/Npgsql/copy.md deleted file mode 100644 index 934c42d1..00000000 --- a/conceptual/Npgsql/copy.md +++ /dev/null @@ -1,88 +0,0 @@ -# COPY - -PostgreSQL has a feature allowing efficient bulk import or export of data to and from a table. This is usually a much faster way of getting data in and out of a table than using INSERT and SELECT. See documentation for the [COPY command](http://www.postgresql.org/docs/current/static/sql-copy.html) for more details. - -Npgsql supports three COPY operation modes: binary, text and raw binary. - -## Binary COPY - -This mode uses the efficient PostgreSQL binary format to transfer data in and out of the database. The user uses an API to read and write rows and fields, which Npgsql decodes and encodes. When you've finished, you must call `Complete()` to save the data; not doing so will cause the COPY operation to be rolled back when the writer is disposed (this behavior is important in case an exception is thrown). - -> [!WARNING] -> It is the your responsibility to read and write the correct type! If you use COPY to write an int32 into a string field you may get an exception, or worse, silent data corruption. It is also highly recommended to use the overload of `Write()` which accepts an `NpgsqlDbType`, allowing you to unambiguously specify exactly what type you want to write. Test your code thoroughly. - -```csharp -// Import two columns to table data -using (var writer = conn.BeginBinaryImport("COPY data (field_text, field_int2) FROM STDIN (FORMAT BINARY)")) -{ - writer.StartRow(); - writer.Write("Hello"); - writer.Write(8, NpgsqlDbType.Smallint); - - writer.StartRow(); - writer.Write("Goodbye"); - writer.WriteNull(); - - writer.Complete(); -} - -// Export two columns to table data -using (var reader = Conn.BeginBinaryExport("COPY data (field_text, field_int2) TO STDOUT (FORMAT BINARY)")) -{ - reader.StartRow(); - Console.WriteLine(reader.Read()); - Console.WriteLine(reader.Read(NpgsqlDbType.Smallint)); - - reader.StartRow(); - reader.Skip(); - Console.WriteLine(reader.IsNull); // Null check doesn't consume the column - Console.WriteLine(reader.Read()); - - reader.StartRow(); // Last StartRow() returns -1 to indicate end of data -} -``` - -## Text COPY - -This mode uses the PostgreSQL text or csv format to transfer data in and out of the database. It is the user's responsibility to format the text or CSV appropriately, Npgsql simply provides a TextReader or Writer. This mode is less efficient than binary copy, and is suitable mainly if you already have the data in a CSV or compatible text format and don't care about performance. - -```csharp -using (var writer = conn.BeginTextImport("COPY data (field_text, field_int4) FROM STDIN")) { - writer.Write("HELLO\t1\n"); - writer.Write("GOODBYE\t2\n"); -} - -using (var reader = conn.BeginTextExport("COPY data (field_text, field_int4) TO STDOUT")) { - Console.WriteLine(reader.ReadLine()); - Console.WriteLine(reader.ReadLine()); -} -``` - -## Raw Binary COPY - -In this mode, data transfer is binary, but Npgsql does no encoding or decoding whatsoever - data is exposed as a raw .NET Stream. This mode makes sense only for bulk data and restore a table: the table is saved as a blob, which can later be restored. If you need to actually make sense of the data, you should be using regular binary mode instead (not raw). - -Example: - -```csharp -int len; -var data = new byte[10000]; -// Export table1 to data array -using (var inStream = conn.BeginRawBinaryCopy("COPY table1 TO STDOUT (FORMAT BINARY)")) { - // We assume the data will fit in 10000 bytes, in real usage you would read repeatedly, write into a file. - len = inStream.Read(data, 0, data.Length); -} - -// Import data array into table2 -using (var outStream = conn.BeginRawBinaryCopy("COPY table2 FROM STDIN (FORMAT BINARY)")) { - outStream.Write(data, 0, len); -} -``` - -## Cancel - -Import operations can be cancelled at any time by disposing `NpgsqlBinaryImporter` without calling `Complete()` on it. Export operations can be cancelled as well, by calling `Cancel()`. - -## Other - -See the CopyTests.cs test fixture for more usage samples. diff --git a/conceptual/Npgsql/dev/release-checklist.md b/conceptual/Npgsql/dev/release-checklist.md deleted file mode 100644 index c81fb9e6..00000000 --- a/conceptual/Npgsql/dev/release-checklist.md +++ /dev/null @@ -1,41 +0,0 @@ -# Npgsql Release Checklist - -## Release the actual version - -* Check out the git branch which represents the version you want to release. For a patch version, this will be e.g. `hotfix/9.0.2`; for a major version, this will be `main`. -* Verify that the version is correct inside `Directory.Build.props`. -* Do a git tag for the version (`git tag v9.0.2`) and push it to origin (`git push origin v9.0.2`). -* Go to the repository's [Actions tab](https://github.com/npgsql/npgsql/actions) and wait for the build to complete. -* If all goes well, you'll need to approve the deployment (this represents the push to nuget.org). If there's some sort of build failure, you can fix it, and then re-tag (`git tag -f v9.0.2`) and force-push (`git push -f upstream v9.0.2`). - -## Post-release actions - -* If you released a patch version, you need to create the new hotfix branch and remove the old one (both locally and from `origin`): `git checkout -b hotfix/9.0.3`. -* Edit `Directory.Build.props` to bump the new version, and commit (`git commit -a -m "Bump version to 9.0.3"`). -* At this point, push the new hotfix branch and remove the old one: - -```console -git push -u upstream hotfix/9.0.3 - -git branch -D hotfix/9.0.2 -git push upstream :hotfix/9.0.2 -``` - -* If you're releasing a major version, the steps are the same except that there's no old hotfix branch to remove, and the version needs to be updated in `main` (and pushed). - -## Github milestone and release - -* Go to the [Milestones page](https://github.com/npgsql/npgsql/milestones) of the repo. -* Create a milestone for the next version (e.g. 9.0.3). -* If there are any open issues in the version milestone which you just published, and those weren't actually completed, move them to the new milestone for the next version (or to the backlog). The released milestone should contain only closed issues. -* Edit the released milestone and set the date to today, just to have a record which version was published when. -* Closed the released milestone. - -* Go to the [Releases page](https://github.com/npgsql/npgsql/releases) of the repo. -* Click "Draft a new release", select the git tag you just released, and give the release the title "v9.0.2". -* Write a short text describing the changes; add a link to the closed issue list of the milestone ([example](https://github.com/npgsql/npgsql/milestone/125?closed=1)), and click "generate release notes". For a major version, link to the release notes page in our conceptual docs. -* Publish the release. - -## Update API documentation - -[Our documentation site](https://www.npgsql.org) generates API docs from the `Npgsql` and `EFCore.PG` submodules in the [documentation repository](https://github.com/npgsql/doc). After publishing a major version, check out the release tag in the corresponding submodule and commit the updated submodule pointer in the documentation repository. Update the SDK in the documentation build workflow or the target framework in `docfx.json` if the new version requires it. Merging the documentation changes to `main` triggers a rebuild and publishes the updated site. diff --git a/conceptual/Npgsql/dev/tests.md b/conceptual/Npgsql/dev/tests.md deleted file mode 100644 index d7559c88..00000000 --- a/conceptual/Npgsql/dev/tests.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -layout: page -title: Tests ---- - -## Overview - -Npgsql has an extensive test suite to guard against regressions. The test suite is run on the official build server for the .NET Framework and .NET Core with all supported PostgreSQL backends. - -Continuous integration results are publicly available via [Github Actions](https://github.com/npgsql/npgsql/actions). - -## Getting Started - -### Setup PostgreSQL - -The Npgsql test suite requires a PostgreSQL backend for tests to run. By default, the test suite expects PostgreSQL to be running on the local machine with the default port (5432). - -1. Install PostgreSQL: -2. Start the PostgreSQL backend. - -### Create the `npgsql_tests` account - -By default, the test suite expects an account named `npgsql_tests` with a password of `npgsql_tests`. This account is used by the test suite to create a database named `npgsql_tests` and run the tests. - -```bash -$ psql -h localhost -U postgres -postgres=# CREATE USER npgsql_tests PASSWORD 'npgsql_tests' SUPERUSER; -postgres=# CREATE DATABASE npgsql_tests OWNER npgsql_tests; -``` - -_Note: superuser access is required to create and drop test databases, load extensions (e.g. `hstore`, `postgis`), etc._ - -### Clone the repository - -```bash -cd ~ -git clone git@github.com:npgsql/npgsql.git (use ssh) -git clone https://github.com/npgsql/npgsql.git (use https) -``` - -### Run the test suite - -```bash -cd ~/npgsql -dotnet test ./test/Npgsql.Tests -dotnet test ./test/Npgsql.PluginTests -dotnet test ./test/Npgsql.Benchmarks -``` diff --git a/conceptual/Npgsql/dev/type-representations.md b/conceptual/Npgsql/dev/type-representations.md deleted file mode 100644 index 197d630c..00000000 --- a/conceptual/Npgsql/dev/type-representations.md +++ /dev/null @@ -1,387 +0,0 @@ ---- -layout: page -title: PostgreSQL Types ---- - -## Overview - -The following are notes by Emil Lenngren on PostgreSQL wire representation of types: - -~~~text -bool: - text: t or f - binary: a byte: 1 or 0 - -bytea: - text: - either \x followed by hex-characters (lowercase by default), - or plain characters, where non-printable characters (between 0x20 and 0x7e, inclusive) are written as \nnn (octal) and \ is written as \\ - binary: the bytes as they are - -char: - This type holds a single char/byte. (Not to be confused with bpchar (blank-padded char) which is PostgreSQL's alias to the SQL standard's char). - The char may be the null-character - text: the char as a byte, encoding seems to be ignored - binary: the char as a byte - -name: - A null-padded string of NAMEDATALEN (currently 64) bytes (the last byte must be a null-character). Used in pg catalog. - text: the name as a string - binary: the name as a string - -int2/int4/int8: - text: text representation in base 10 - binary: binary version of the integer - -int2vector: - non-null elements, 0-indexed, 1-dim - text: 1 2 3 4 - binary: same as int2[] - -oidvector: - non-null elements, 0-indexed, 1-dim - text: 1 2 3 4 - binary: same as oid[] - -regproc: - internally just an OID (UInt32) - text: -, name of procedure, or numeric if not found - binary: only the OID in binary - -regprocedure/regoper/regoperator/regclass/regconfig/regdictionary: - similar to regproc - -text: - text: the string as it is - binary: the string as it is - -oid: - A 32-bit unsigned integer used for internal object identification. - text: the text-representation of this integer in base 10 - binary: the UInt32 - -tid: - tuple id - Internally a tuple of a BlockNumber (UInt32) and an OffsetNumber (UInt16) - text: (blockNumber,offsetNumber) - binary: the block number in binary followed by offset number in binary - -xid: - transaction id - Internally just a TransactionId (UInt32) - text: the number - binary: the number in binary - -cid: - command id - Internally just a CommandId (UInt32) - text: the number - binary: the number in binary - -json: - json - text: the json an text - binary: the json as text - -jsonb: - json internally stored in an efficient binary format - text: the json as text - binary: An Int32 (version number, currently 1), followed by data (currently just json as text) - -xml: - Xml. It is probably most efficient to use the text format, especially when receiving from client. - text: the xml as text (when sent from the server: encoding removed, when receiving: assuming database encoding) - binary: the xml as text (when sent from the server: in the client's specified encoding, when receiving: figures out itself) - -pg_node_tree: - used as type for the column typdefaultbin in pg_type - does not accept input - text: text - binary: text - -smgr: - storage manager - can only have the value "magnetic disk" - text: magnetic disk - binary: not available - -point: - A tuple of two float8 - text: - (x,y) - The floats are interpreted with the C strtod function. - The floats are written with the snprintf function, with %.*g format. NaN/-Inf/+Inf can be written, but not interpretability depends on platform. The extra_float_digits setting is honored. - For linux, NaN, [+-]Infinity, [+-]Inf works, but not on Windows. Windows also have other output syntax for these special numbers. (1.#QNAN for example) - binary: the two floats - -lseg: - A tuple of two points - text: [(x1,y1),(x2,y2)] see point for details - binary: the four floats in the order x1, y1, x2, y2 - -path: - A boolean whether the path is opened or closed + a vector of points. - text: [(x1,y1),...] for open path and ((x1,y1),...) for closed paths. See point for details. - binary: first a byte indicating open (0) or close (1), then the number of points (Int32), then a vector of points - -box: - A tuple of two points. The coordinates will be reordered so that the first is the upper right and the second is the lower left. - text: (x1,y1),(x2,y2) see point for details - binary: the four floats in the order x1, y1, x2, y2 (doesn't really matter since they will be reordered) - -polygon: - Same as path but with two differences: is always closed and internally stores the bounding box. - text: same as closed path - binary: the number of points (Int32), then a vector of points - -line (version 9.4): - Ax + By + C = 0. Stored with three float8. - Constraint: A and B must not both be zero (only checked on text input, not binary). - text: {A,B,C} see point for details about the string representation of floats. Can also use the same input format as a path with two different points, representing the line between those. - binary: the three floats - -circle: - <(x,y),r> (center point and radius), stored with three float8. - text: <(x,y),r> see point for details about the string representation of floats. - binary: the three floats x, y, r in that order - -float4/float8: - text: - (leading/trailing whitespace is skipped) interpreted with the C strtod function, but since it has problems with NaN, [+-]Infinity, [+-]Inf, those strings are identified (case-insensitively) separately. - when outputting: NaN, [+-]Infinity is treated separately, otherwise the string is printed with snprintf %.*g and the extra_float_digits setting is honored. - binary: the float - -abstime: - A unix timestamp stored as a 32-bit signed integer with seconds-precision (seconds since 1970-01-01 00:00:00), in UTC - Has three special values: Invalid (2^31-1), infinity (2^31-3), -infinity (-2^31) - text: same format as timestamptz, or "invalid", "infinity", "-infinity" - binary: Int32 - -reltime: - A time interval with seconds-precision (stored as an 32-bit signed integer) - text: same as interval - binary: Int32 - -tinterval: - Consists of a status (Int32) and two abstimes. Status is valid (1) iff both abstimes are valid, else 0. - Note that the docs incorrectly states that ' is used as quote instead of " - text: ["" ""] - binary: Int32 (status), Int32 (abstime 1), Int32 (abstime 2) - -unknown: - text: text - binary: text - -money: - A 64-bit signed integer. For example, $123.45 is stored as the integer 12345. Number of fraction digits is locale-dependent. - text: a locale-depedent string - binary: the raw 64-bit integer - -macaddr: - 6 bytes - text: the 6 bytes in hex (always two characters per byte) separated by : - binary: the 6 bytes appearing in the same order as when written in text - -inet/cidr: - Struct of Family (byte: ipv4=2, ipv6=3), Netmask (byte with number of bits in the netmask), Ipaddr bytes (16) - Text: The IP-address in text format and /netmask. /netmask is omitted in inet if the netmask is the whole address. - Binary: family byte, netmask byte, byte (cidr=1, inet=0), number of bytes in address, bytes of the address - -aclitem: - Access list item used in pg_class - Text: Something like postgres=arwdDxt/postgres - Binary: not available - -bpchar: - Blank-padded char. The type modifier is used to blank-pad the input. - text: text - binary: text - -varchar: - Variable-length char. The type modifier is used to check the input's length. - text: text - binary: text - -date: - A signed 32-bit integer of a date. 0 = 2000-01-01. - Infinity: INT_MAX, -Infinity: INT_MIN - Text: Date only using the specified date style - Binary: Int32 - -time: - A signed 64-bit integer representing microseconds from 00:00:00.000000. (Legacy uses 64-bit float). Negative values are not allowed. - Max value is 24:00:00.000000. - text: hh:mm:ss or hh:mm:ss.ffffff where the fraction part is between 1 and 6 digits (trailing zeros are not written) - binary: the 64-bit integer - -timetz: - A struct of - Time: A signed 64-bit integer representing microseconds from 00:00:00.000000. (Legacy uses 64-bit float). Negative values are not allowed. - Max value is 24:00:00.000000. - Zone: A signed 32-bit integer representing the zone (in seconds). Note that the sign is inverted. So GMT+1h is stored as -1h. - text: hh:mm:ss or hh:mm:ss.ffffff where the fraction part is between 1 and 6 digits (trailing zeros are not written) - binary: the 64-bit integer followed by the 32-bit integer - -timestamp: - A signed 64-bit integer representing microseconds from 2000-01-01 00:00:00.000000 - Infinity is LONG_MAX and -Infinity is LONG_MIN - (Infinity would be 294277-01-09 04:00:54.775807) - Earliest possible timestamp is 4714-11-24 00:00:00 BC. Even earlier would be possible, but due to internal calculations those are forbidden. - text: dependent on date style - binary: the 64-bit integer - -timestamptz: - A signed 64-bit integer representing microseconds from 2000-01-01 00:00:00.000000 UTC. (Time zone is not stored). - Infinity is LONG_MAX and -Infinity is LONG_MIN - text: first converted to the time zone in the db settings, then printed according to the date style - binary: the 64-bit integer - -interval: - A struct of - Time (Int64): all time units other than days, months and years (microseconds) - Day (Int32): days, after time for alignment - Month (Int32): months and years, after time for alignment - text: Style dependent, but for example: "-11 mons +15435 days -11111111:53:00" - binary: all fields in the struct - -bit/varbit: - First a signed 32-bit integer containing the number of bits (negative length not allowed). Then all the bits in big end first. - So a varbit of length 1 has the first (and only) byte set to either 0x80 or 0x00. Last byte is assumed (and is automatically zero-padded in recv) to be zero-padded. - text: - when sending from backend: all the bits, written with 1s and 0s. - when receiving from client: (optionally b or B followed by) all the bits as 1s and 0s, or a x or X followed by hexadecimal digits (upper- or lowercase), big endian first. - binary: the 32-bit length followed by the bytes containing the bits - -numeric: - A variable-length numeric value, can be negative. - text: NaN or first - if it is negative, then the digits with . as decimal separator - binary: - first a header of 4 16-bit integers: - number of digits in the digits array that follows (unsigned integer), - weight of the first digit (10000^weight), can be both negative, positive or 0, - sign: negative=0x4000, positive=0x0000, NaN=0xC000 - dscale: number of digits (in base 10) to print after the decimal separator - then the array of digits: - The digits are stored in base 10000, where each digit is a 16-bit integer. - Trailing zeros are not stored in this array, to save space. - The digits are stored such that, if written as base 10000, the decimal separator can be inserted between two digits in base 10000, - i.e. when this is to be printed in base 10, only the first digit in base 10000 can (possibly) be printed with less than 4 characters. - Note that this does not apply for the digits after the decimal separator; the digits should be printed out in chunks of 4 - characters and then truncated with the given dscale. - -refcursor: - uses the same routines as text - -record: - Describes a tuple. Is also the "base class" for composite types (i.e. it uses the same i/o functions). - text: - ( followed by a list of comma-separated text-encoded values followed by ). - Empty element means null. - Quoted with " and " if necessary. " is escaped with "" and \ is escaped with \\ (this differs from arrays where " is escaped with \"). - Must be quoted if it is an empty string or contains one of "\,() or a space. - binary: - First a 32-bit integer with the number of columns, then for each column: - An OID indicating the type of the column - The length of the column (32-bit integer), or -1 if null - The column data encoded as binary - -cstring: - text/binary: all characters are sent without the trailing null-character - -void: - Used for example as return value in SELECT * FROM func_returning_void() - text: an empty string - binary: zero bytes - -uuid: - A 16-byte uuid. - text: group of 8, 4, 4, 4, 12 hexadecimal lower-case characters, separated by -. The first byte is written first. It is allowed to surround it with {}. - binary: the 16 bytes - -txid_snapshot: - (txid is a UInt64) - A struct of - UInt32 nxip (size of the xip array) - txid xmin (no values in xip is smaller than this) - txid xmax (no values in xip is larger than or equal this) - txid[] xip (is ordered in ascending order) - text: xmin:xmax:1,2,3,4 - binary: all fields in the structure - -tsvector: - Used for text searching. Example of tsvector: 'a':1,6,10 'on':5 'and':8 'ate':9A 'cat':3 'fat':2,11 'mat':7 'rat':12 'sat':4 - Max length for each lexeme string is 2046 bytes (excluding the trailing null-char) - The words are sorted when parsed, and only written once. Positions are also sorted and only written once. - For some reason, the unique check does not seem to be made for binary input, only text input... - text: As seen above. ' is escaped with '' and \ is escaped with \\. - binary: - UInt32 number of lexemes - for each lexeme: - lexeme text in client encoding, null-terminated - UInt16 number of positions - for each position: - UInt16 WordEntryPos, where the most significant 2 bits is weight, and the 14 least significant bits is pos (can't be 0). Weights 3,2,1,0 represent A,B,C,D - -tsquery: - A tree with operands and operators (&, |, !). Operands are strings, with optional weight (bitmask of ABCD) and prefix search (yes/no, written with *). - text: the tree written in infix notation. Example: ( 'abc':*B | 'def' ) & !'ghi' - binary: the tree written in prefix notation: - First the number of tokens (a token is an operand or an operator). - For each token: - UInt8 type (1 = val, 2 = oper) followed by - For val: UInt8 weight + UInt8 prefix (1 = yes / 0 = no) + null-terminated string, - For oper: UInt8 oper (1 = not, 2 = and, 3 = or, 4 = phrase). - In case of phrase oper code, an additional UInt16 field is sent (distance value of operator). Default is 1 for <->, otherwise the n value in ''. - -enum: - Simple text - -gtsvector: - GiST for tsvector. Probably internal type. - -int4range/numrange/tsrange/tstzrange/daterange/int8range and user-defined range types: - /* A range's flags byte contains these bits: */ - #define RANGE_EMPTY 0x01 /* range is empty */ - #define RANGE_LB_INC 0x02 /* lower bound is inclusive */ - #define RANGE_UB_INC 0x04 /* upper bound is inclusive */ - #define RANGE_LB_INF 0x08 /* lower bound is -infinity */ - #define RANGE_UB_INF 0x10 /* upper bound is +infinity */ - #define RANGE_LB_NULL 0x20 /* lower bound is null (NOT USED) */ - #define RANGE_UB_NULL 0x40 /* upper bound is null (NOT USED) */ - #define RANGE_CONTAIN_EMPTY 0x80/* marks a GiST internal-page entry whose - * subtree contains some empty ranges */ - A range has no lower bound if any of RANGE_EMPTY, RANGE_LB_INF (or RANGE_LB_NULL, not used anymore) is set. The same applies for upper bounds. - text: - A range with RANGE_EMPTY is just written as the string "empty". - Inclusive bounds are written with [ and ], else ( and ) is used. - The two values are comma-separated. - Missing bounds are written as an empty string (without quotes). - Each value is quoted with " if necessary. Quotes are necessary if the string is either the empty string or contains "\,()[] or spaces. " is escaped with "" and \ is escaped with \\. - Example: [18,21] - binary: First the flag byte. Then, if has lower bound: 32-bit length + binary-encoded data. Then, if has upper bound: 32-bit length + binary-encoded data. - -hstore: - Key/value-store. Both keys and values are strings. - text: - Comma-space separated string, where each item is written as "key"=>"value" or "key"=>NULL. " and \ are escaped as \" and \\. - Example: "a"=>"b", "c"=>NULL, "d"=>"q" - binary: - Int32 count - for each item: - Int32 keylen - string of the key (not null-terminated) - Int32 length of item (or -1 if null) - the item as a string - -ghstore: - internal type for indexing hstore - -domain types: - mapped types used in information_schema: - cardinal_number: int4 (must be nonnegative or null) - character_data: varchar - sql_identifier: varchar - time_stamp: timestamptz - yes_or_no: varchar(3) (must be "YES" or "NO" or null) - intnotnull: when an int4 is cast to this type, it is checked that the int4 is not null, but it still returns an int4 and not intnotnull... -~~~ diff --git a/conceptual/Npgsql/diagnostics/exceptions_notices.md b/conceptual/Npgsql/diagnostics/exceptions_notices.md deleted file mode 100644 index 723d1463..00000000 --- a/conceptual/Npgsql/diagnostics/exceptions_notices.md +++ /dev/null @@ -1,21 +0,0 @@ -# Exceptions, errors and notices - -## Exception types - -Most exceptions thrown by Npgsql are either of type , or wrapped by one; this allows your application to catch `NpgsqlException` where appropriate, for all database-related errors. Note that `NpgsqlException` is a sub-class of the general [System.Data.DbException](https://docs.microsoft.com/dotnet/api/system.data.common.dbexception), so if your application uses more than one database type, you can catch that as well. - -When Npgsql itself encounters an error, it typically raises that as an `NpgsqlException` directly, possibly wrapping an inner exception. For example, if a networking error occurs while communicating with PostgreSQL, Npgsql will raise an `NpgsqlException` wrapping an `IOException`; this allow you both to identify the root cause of the problem, while still identifying it as database-related. - -In other cases, PostgreSQL itself will report an error to Npgsql; Npgsql raises these by throwing a [PostgresException](xref:Npgsql.PostgresException), which is a sub-class of `NpgsqlException` adding important contextual information on the error. Most importantly, `PostgresException` exposes the [SqlState](xref:Npgsql.PostgresException.SqlState) property, which contains the [PostgreSQL error code](https://www.npgsql.org/doc/api/Npgsql.PostgresException.html#Npgsql_PostgresException_SqlState). This value can be consulted to identify which error type occurred. - -When executing multiple commands via , the property references the command within the batch which triggered the exception. This allows you to understand exactly what happened, and access the specific SQL which triggered the error. - -## PostgreSQL notices - -Finally, PostgreSQL also raises "notices", which contain non-critical information on command execution. Notices are not errors: they do not indicate failure and can be safely ignored, although they may contain valuable information on the execution of your commands. - -Npgsql logs notices in the *debug* logging level. To deal with notices programmatically, Npgsql also exposes the event, which you can hook into for any further processing: - -```csharp -conn.Notice += (_, args) => Console.WriteLine(args.Notice.MessageText); -``` diff --git a/conceptual/Npgsql/diagnostics/logging.md b/conceptual/Npgsql/diagnostics/logging.md deleted file mode 100644 index 7e194b75..00000000 --- a/conceptual/Npgsql/diagnostics/logging.md +++ /dev/null @@ -1,177 +0,0 @@ -# Logging - -> [!NOTE] -> Starting with version 7.0, Npgsql supports standard .NET logging via [Microsoft.Extensions.Logging](https://learn.microsoft.com/dotnet/core/extensions/logging). If you're using an earlier version of Npgsql, skip down to [this section](#old-logging). - -Npgsql fully supports logging various events via the standard .NET [Microsoft.Extensions.Logging](https://learn.microsoft.com/dotnet/core/extensions/logging) package. These can help debug issues and understand what's going on as your application interacts with PostgreSQL. - -## Console programs - -To set up logging in Npgsql, create your `ILoggerFactory` as usual, and then configure an `NpgsqlDataSource` with it. Any use of connections handed out by the data source will log via your provided logger factory. - -The following shows a minimal console application logging to the console via [Microsoft.Extensions.Logging.Console](https://www.nuget.org/packages/Microsoft.Extensions.Logging.Console): - -```csharp -// Create a Microsoft.Extensions.Logging LoggerFactory, configuring it with the providers, -// log levels and other desired configuration. -var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); - -// Create an NpgsqlDataSourceBuilder, configuring it with our LoggerFactory -var dataSourceBuilder = new NpgsqlDataSourceBuilder("Host=localhost;Username=test;Password=test"); -dataSourceBuilder.UseLoggerFactory(loggerFactory); -await using var dataSource = dataSourceBuilder.Build(); - -// Any connections handed out by the data source will log via the LoggerFactory: -await using var connection = await dataSource.OpenConnectionAsync(); -await using var command = new NpgsqlCommand("SELECT 1", connection); -_ = await command.ExecuteScalarAsync(); -``` - -Running this program outputs the following to the console: - -```console -info: Npgsql.Command[2001] - Command execution completed (duration=16ms): SELECT 1 -``` - -By default, Npgsql logs command executions at the `Information` log level, as well as various warnings and errors. To see more detailed logging, increase the log level to `Debug` or `Trace`. - -## ASP.NET and dependency injection - -If you're using ASP.NET, use `AddNpgsqlDataSource()` to integrate with dependency injection and logging. This method is included in Npgsql starting with version 11. For earlier versions, add a reference to [Npgsql.DependencyInjection](https://www.nuget.org/packages/Npgsql.DependencyInjection). - -```csharp -var builder = WebApplication.CreateBuilder(args); -builder.Logging.AddConsole(); -builder.Services.AddNpgsqlDataSource("Host=localhost;Username=test;Password=test"); -``` - -The `AddNpgsqlDataSource` arranges for a data source to be configured in the DI container, which automatically uses the logger factory configured via the standard ASP.NET means. This allows your endpoints to get injected with Npgsql connections which log to the same logger factory when used. - -## Configuration without NpgsqlDataSource - -If your application doesn't use `NpgsqlDataSource`, you can still configure Npgsql's logger factory globally, as follows: - -```csharp -var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); -NpgsqlLoggingConfiguration.InitializeLogging(loggerFactory); - -await using var conn = new NpgsqlConnection("Host=localhost;Username=test;Password=test"); -conn.Execute("SELECT 1"); -``` - -Note that you must call `InitializeLogging` at the start of your program, before any other Npgsql API is used. - -## Parameter logging - -By default, when logging SQL statements, Npgsql does not log parameter values, since these may contain sensitive information. You can opt into parameter logging when debugging your application: - -### [Console Program](#tab/console) - -```csharp -dataSourceBuilder.EnableParameterLogging(); -``` - -### [ASP.NET Program](#tab/aspnet) - -```csharp -builder.Services.AddNpgsqlDataSource( - "Host=localhost;Username=test;Password=test", - builder => builder.EnableParameterLogging()); -``` - -### [Without DbDataSource](#tab/without-dbdatasource) - -```csharp -NpgsqlLoggingConfiguration.InitializeLogging(loggerFactory, parameterLoggingEnabled: true); -``` - -*** - -> [!WARNING] -> Do not leave parameter logging enabled in production, as sensitive user information may leak into your logs. - -## Logging in older versions of Npgsql - -Prior to 7.0, Npgsql had its own, custom logging API. To use this, statically inject a logging provider implementing the `INpgsqlLoggingProvider` interface as follows: - -```csharp -NpgsqlLogManager.Provider = new ??? -``` - -*Note: you must set the logging provider before invoking any other Npgsql method, at the very start of your program.* - -It's trivial to create a logging provider that passes log messages to whatever logging framework you use, you can find such an adapter for NLog below. - -### ConsoleLoggingProvider - -Npgsql comes with one built-in logging provider: `ConsoleLoggingProvider`. It simply dumps all log messages with a given level or above to standard output. -You can set it up by including the following line at the beginning of your application: - -```csharp -NpgsqlLogManager.Provider = new ConsoleLoggingProvider(, , ); -``` - -Level defaults to `NpgsqlLogLevel.Info` (which will only print warnings and errors). -You can also have log levels and connector IDs logged. - -### NLogLoggingProvider (or implementing your own) - -The following provider is used in the Npgsql unit tests to pass log messages to [NLog](http://nlog-project.org/). -You're welcome to copy-paste it into your project, or to use it as a starting point for implementing your own custom provider. - -```csharp -class NLogLoggingProvider : INpgsqlLoggingProvider -{ - public NpgsqlLogger CreateLogger(string name) - { - return new NLogLogger(name); - } -} - -class NLogLogger : NpgsqlLogger -{ - readonly Logger _log; - - internal NLogLogger(string name) - { - _log = LogManager.GetLogger(name); - } - - public override bool IsEnabled(NpgsqlLogLevel level) - { - return _log.IsEnabled(ToNLogLogLevel(level)); - } - - public override void Log(NpgsqlLogLevel level, int connectorId, string msg, Exception exception = null) - { - var ev = new LogEventInfo(ToNLogLogLevel(level), "", msg); - if (exception != null) - ev.Exception = exception; - if (connectorId != 0) - ev.Properties["ConnectorId"] = connectorId; - _log.Log(ev); - } - - static LogLevel ToNLogLogLevel(NpgsqlLogLevel level) - { - switch (level) - { - case NpgsqlLogLevel.Trace: - return LogLevel.Trace; - case NpgsqlLogLevel.Debug: - return LogLevel.Debug; - case NpgsqlLogLevel.Info: - return LogLevel.Info; - case NpgsqlLogLevel.Warn: - return LogLevel.Warn; - case NpgsqlLogLevel.Error: - return LogLevel.Error; - case NpgsqlLogLevel.Fatal: - return LogLevel.Fatal; - default: - throw new ArgumentOutOfRangeException("level"); - } - } -} -``` diff --git a/conceptual/Npgsql/diagnostics/metrics.md b/conceptual/Npgsql/diagnostics/metrics.md deleted file mode 100644 index 201be1e7..00000000 --- a/conceptual/Npgsql/diagnostics/metrics.md +++ /dev/null @@ -1,47 +0,0 @@ -# OpenTelemetry Metrics - -Npgsql supports reporting aggregated metrics which provide snapshots on its state and activities at a given point. These can be especially useful for diagnostics issues such as connection leaks, or doing general performance analysis Metrics are reported via the standard .NET System.Diagnostics.Metrics API; [see these docs](https://learn.microsoft.com/dotnet/core/diagnostics/metrics) for more details. The Npgsql metrics implement the experimental [OpenTelemetry semantic conventions for database metrics](https://opentelemetry.io/docs/specs/semconv/database/database-metrics/) - adding some additional useful ones - and will evolve as that specification stabilizes. - -> [!NOTE] -> Npgsql 10.0 changed the metrics names to align with the OpenTelemetry standard. The names shown below reflect the Npgsql 10 counters. -> -> Npgsql versions before 8.0, as well as TFMs under net6.0, emit metrics via the older Event Counters API instead of the new OpenTelemetry ones. - -Metrics are usually collected and processed via tools such as [Prometheus](https://prometheus.io), and plotted on dashboards via tools such as [Grafana](https://grafana.com). Configuring .NET to emit metrics to these tools is beyond the scope of this documentation, but you can use the command-line tool `dotnet-counters` to quickly test Npgsql's support. To collect metrics via `dotnet-counters`, [install the `dotnet-counters` tool](https://docs.microsoft.com/dotnet/core/diagnostics/dotnet-counters). Then, find out your process PID, and run it as follows: - -```output -dotnet counters monitor --counters Npgsql -p -``` - -`dotnet-counters` will now attach to your running process and start reporting continuous counter data: - -```output -[Npgsql] - db.client.operation.npgsql.bytes_read (By / 1 sec) - db.client.connection.pool.name=CustomersDB 1,020 - db.client.operation.npgsql.bytes_written (By / 1 sec) - db.client.connection.pool.name=CustomersDB 710 - db.client.operation.duration (s) - db.client.connection.pool.name=CustomersDB,Percentile=50 0.001 - db.client.connection.pool.name=CustomersDB,Percentile=95 0.001 - db.client.connection.pool.name=CustomersDB,Percentile=99 0.001 - db.client.operation.npgsql.executing ({command}) - db.client.connection.pool.name=CustomersDB 2 - db.client.operation.npgsql.prepared_ratio - db.client.connection.pool.name=CustomersDB 0 - db.client.connection.max ({connection}) - db.client.connection.pool.name=CustomersDB 100 - db.client.connection.count ({connection}) - db.client.connection.pool.name=CustomersDB,state=idle 3 - db.client.connection.pool.name=CustomersDB,state=used 2 -``` - -Npgsql emits multiple *dimensions* with its metrics, such as the connection state (idle or used). The `db.client.connection.pool.name` tag identifies the data source so you can track multiple pools separately. Starting with Npgsql 11, this tag defaults to the connection string's `Application Name` if set; otherwise, it uses the connection string with the password removed. You can set an explicit name for consistent tracking: - -```csharp -var builder = new NpgsqlDataSourceBuilder("Host=localhost;Username=test;Password=test") -{ - Name = "CustomersDB" -}; -await using var dataSource = builder.Build(); -``` diff --git a/conceptual/Npgsql/diagnostics/overview.md b/conceptual/Npgsql/diagnostics/overview.md deleted file mode 100644 index 02e85a33..00000000 --- a/conceptual/Npgsql/diagnostics/overview.md +++ /dev/null @@ -1,9 +0,0 @@ -# Diagnostics overview - -Npgsql provides several ways to analyze what's going on inside Npgsql and to diagnose performance issues. Each has its own dedicated doc page: - -* [**Tracing**](tracing.md) allows collecting information on which queries are executed, including precise timing information on start, end and duration. These events can be collected in a database, searched, graphically explored and otherwise analyzed. -* [**Logging**](logging.md) generates textual information on various events within Npgsql; log levels can be adjusted to collect low-level information, helpful for diagnosing errors. -* [**Metrics**](metrics.md) generates aggregated quantitative data, useful for tracking the performance of your application in realtime and over time (e.g. how many queries are currently being executed in a particular moment). - -For information on the exceptions thrown by Npgsql, and on notices produced by PostgreSQL, [see this page](exceptions_notices.md). diff --git a/conceptual/Npgsql/diagnostics/tracing.md b/conceptual/Npgsql/diagnostics/tracing.md deleted file mode 100644 index be31366f..00000000 --- a/conceptual/Npgsql/diagnostics/tracing.md +++ /dev/null @@ -1,100 +0,0 @@ -# Tracing with OpenTelemetry (experimental) - -> [!NOTE] -> -> [The OpenTelemetry specifications for database tracing](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/database.md) are currently experimental, so Npgsql's support may change in upcoming releases. - -[OpenTelemetry](https://opentelemetry.io/) is a widely-adopted framework for distributed observability across many languages and components; its tracing standards allow applications and libraries to emit information on activities and events, which can be exported by the application, stored and analyzed. Activities typically have start and end times, and can encompass other activities recursively; this allows you to analyze e.g. exactly how much time was spent in the database when handling a certain HTTP call. - -## Basic usage - -To make Npgsql emit tracing data, reference the [Npgsql.OpenTelemetry](https://www.nuget.org/packages/Npgsql.OpenTelemetry) NuGet package from your application, and set up tracing as follows: - -```csharp -using var tracerProvider = Sdk.CreateTracerProviderBuilder() - .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("npgsql-tester")) - .SetSampler(new AlwaysOnSampler()) - // This optional activates tracing for your application, if you trace your own activities: - .AddSource("MyApp") - // This activates up Npgsql's tracing: - .AddNpgsql() - // This prints tracing data to the console: - .AddConsoleExporter() - .Build(); -``` - -Once this is done, you should start seeing Npgsql trace data appearing in your application's console. At this point, you can look into exporting your trace data to a more useful destination: systems such as [Zipkin](https://zipkin.io/) or [Jaeger](https://www.jaegertracing.io/) can efficiently collect and store your data, and provide user interfaces for querying and exploring it. Setting these up in your application is quite easy - simply replace the console exporter with the appropriate exporter for the chosen system. - -For example, Zipkin visualizes traces in the following way: - -![Zipkin UI Sample](/img/zipkin.png) - -In this trace, the Npgsql query (to database testdb) took around 800ms, and was nested inside the application's `work1` activity, which also had another unrelated `subtask1`. This allows understanding the relationships between the different activities, and where time is being spent. - -## Configuration options - -> [!NOTE] -> -> This feature was introduced in Npgsql 9.0 - -Once you've enabled Npgsql tracing as above, you can tweak its configuration via the API: - -```csharp -dataSourceBuilder.ConfigureTracing(o => o - // Set the command SQL as the span name - .ConfigureCommandSpanNameProvider(cmd => cmd.CommandText) - // Filter out COMMIT commands - .ConfigureCommandFilter(cmd => !cmd.CommandText.StartsWith("COMMIT", StringComparison.OrdinalIgnoreCase))); -``` - -This allows you to: - -* Specify a filter which determines which commands get traced -* Set the tracing span name (e.g. use the command's SQL as the span name) -* Add arbitrary tags to the tracing span, based on the command -* Disable the time-to-first-read event that's emitted in spans -* Disable tracing physical connection open span - -## Using `AsyncLocal` to pass arbitrary information to your callbacks - -The callbacks available via only accept the or as their parameters. This limitation makes it difficult to inject contextual data; such as assigning arbitrary names to your commands so they appear as the span names in your tracing monitor. You can solve this by using .NET [`AsyncLocal`](https://learn.microsoft.com/dotnet/api/system.threading.asynclocal-1) to flow arbitrary information from the command call site (where you execute the command) to your tracing callbacks. - -For example, the following adds an `ExecuteReaderWithSpanNameAsync` extension method to : - -```c# -internal static class DbCommandExtensions -{ - internal static readonly AsyncLocal CommandName = new(); - - public static async Task ExecuteReaderWithSpanNameAsync(this NpgsqlCommand command, string spanName) - { - var previousValue = CommandName.Value; - CommandName.Value = spanName; - - try - { - return await command.ExecuteReaderAsync(); - } - finally - { - CommandName.Value = previousValue; - } - } -} -``` - -You can now configure your data source to use this span name in commands: - -```c# -dataSourceBuilder.ConfigureTracing(o => - o.ConfigureCommandSpanNameProvider(_ => - DbCommandExtensions.CommandName.Value)); -``` - -At this point, you can execute commands as follows, and see the provided value appearing in your tracing: - -```c# -await using var reader = await command.ExecuteReaderWithSpanNameAsync("FetchAllUsers"); -``` - -We'll likely work on future improvements to streamline this and make the above unnecessary. diff --git a/conceptual/Npgsql/failover-and-load-balancing.md b/conceptual/Npgsql/failover-and-load-balancing.md deleted file mode 100644 index 82b6deab..00000000 --- a/conceptual/Npgsql/failover-and-load-balancing.md +++ /dev/null @@ -1,136 +0,0 @@ -# Multiple Hosts, Failover and Load Balancing - -> [!NOTE] -> The functionality described in this page was introduced in Npgsql 6.0. - -Npgsql 6.0 allows specifying multiple hosts in your application's connection strings, allowing various failover and load balancing scenarios to be supported without the need for any additional component such as pgpool or pgbouncer. This typically requires setting up replication between your multiple PostgreSQL servers, to keep your standby servers in sync with your primary; this can be done with the help of PostgreSQL logical or physical replication, and some cloud providers provide this out of the box. Whatever the solution chosen, it's important to understand that this is out of Npgsql's scope - Npgsql is only responsible for connecting to your multiple servers as described below, and not for keeping your servers in sync. - -## Multiple servers and failover - -Npgsql allows you to specify multiple servers in your connection string as follows: - -### [Npgsql 7.0+](#tab/7) - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder("Host=server1,server2;Username=test;Password=test"); -await using var dataSource = dataSourceBuilder.BuildMultiHost(); -await using var connection = await dataSource.OpenConnectionAsync(); -``` - -### [Older versions](#tab/old) - -```csharp -await using var connection = new NpgsqlConnection("Host=server1,server2;Username=test;Password=test"); -``` - -*** - -Different ports may be specified per host with the standard colon syntax: `Host=server1:5432,server2:5433`. - -By default, Npgsql will try to connect to the servers in the order in which they were specified. In the above example, `server2` is only used if a connection could not be established to `server1` (or if the connection pool for `server1` has been exhausted). This allows a simple *failover* setup, where Npgsql always connects to a single, primary server, but can connect to a standby in case the primary is down; this improves the reliability of your application. In this configuration, we sometimes refer to the standby as "warm" - it is always up and in sync with the primary, but is only used when the primary is down. - -> [!NOTE] -> Using failover as described above does not mean you don't have to worry about errors when your primary server is down. When opening a connection, you may get a broken connection from the pool: Npgsql has no way of knowing whether the connection is working without actually executing something on it, which would negate the perf advantages of pooling. Also, once you have an open connection, Npgsql will never implicitly retry a failed command on a failover server, since that command may be in a transaction (or otherwise depend on some state in the first connection). In other words, you must always be prepared to catch I/O-related exceptions when interacting with the database, and possibly implement a retrying strategy, opening a new connection and re-executing the series of commands. - -## Specifying server types - -In the failover scenario above, if `server1` goes down, `server2` is typically promoted to being the new primary. However, `server1` may be brought back up and assume the role of standby - the servers will have switched roles - and Npgsql will continue to connect to `server1` whenever possible. If you need to connect to a specific server type - e.g. to the primary in order to perform writes - you can do so as follows: - -### [Npgsql 7.0+](#tab/7) - -```csharp -await using var connection = await dataSource.OpenConnectionAsync(TargetSessionAttributes.Primary); -``` - -This makes Npgsql return connections only to the primary server, regardless of where it's located in the host list you provide. - -You can also get a separate data source which will only return connections to a specific server type. For example, you can create a primary-only data sources in your application startup, and use that data source as usual: - -```csharp -// At startup: -_primaryDataSource = dataSource.WithTargetSession(TargetSessionAttributes.Primary); - -// ... and wherever you need a connection: -await using var connection = await _primaryDataSource.OpenConnectionAsync(); -``` - -### [Older versions](#tab/old) - -```csharp -await using var connection = new NpgsqlConnection("Host=server1,server2;Username=test;Password=test;Target Session Attributes=primary"); -``` - -This makes Npgsql return connections only to the primary server, regardless of where it's located in the host list you provide. - -*** - -## Load distribution - -Going a step further, it's important to understand that applications don't always make use of the database in the same way; some parts of your application only need to read data from the database, while others need to write data. If you have one or more standby servers, Npgsql can dispatch read-only queries to those servers to reduce the load on your primary. While the failover setup described above improves *reliability*, this technique improves *performance*. - -You can tell Npgsql that you *prefer* a connection to a standby: - -### [Npgsql 7.0+](#tab/7) - -```csharp -// At startup: -_preferStandbyDatASource = dataSource.WithTargetSession(TargetSessionAttributes.PreferStandby); - -// ... and wherever you need a connection: -await using var connection = await _preferStandbyDatASource.OpenConnectionAsync(); -``` - -### [Older versions](#tab/old) - -```csharp -await using var connection = new NpgsqlConnection("Host=server1,server2;Username=test;Password=test;Target Session Attributes=prefer-standby"); -``` - -*** - -With "prefer standby", as long as at least one standby server is available, Npgsql returns connections to that server. However, if all standby servers are down (or have exhausted their `Max Pool Size` setting), a connection to the primary is returned instead. - -The following options are supported for the target session attributes: - -### [Npgsql 7.0+](#tab/7) - -Option | Description -------------- | ----------- -Any | Any successful connection is acceptable. -Primary | Server must not be in hot standby mode (`pg_is_in_recovery()` must return false). -Standby | Server must be in hot standby mode (`pg_is_in_recovery()` must return true). -PreferPrimary | First try to find a primary server, but if none of the listed hosts is a primary server, try again in `Any` mode. -PreferStandby | First try to find a standby server, but if none of the listed hosts is a standby server, try again in `Any` mode. -ReadWrite | Session must accept read-write transactions by default (that is, the server must not be in hot standby mode and the `default_transaction_read_only` parameter must be off). -ReadOnly | Session must not accept read-write transactions by default (the converse). - -### [Older versions](#tab/old) - -Option | Description --------------- | ----------- -any | Any successful connection is acceptable. -primary | Server must not be in hot standby mode (`pg_is_in_recovery()` must return false). -standby | Server must be in hot standby mode (`pg_is_in_recovery()` must return true). -prefer-primary | First try to find a primary server, but if none of the listed hosts is a primary server, try again in `Any` mode. -prefer-standby | First try to find a standby server, but if none of the listed hosts is a standby server, try again in `Any` mode. -read-write | Session must accept read-write transactions by default (that is, the server must not be in hot standby mode and the `default_transaction_read_only` parameter must be off). -read-only | Session must not accept read-write transactions by default (the converse). - -*** - -Npgsql detects whether a server is a primary or a standby by occasionally querying [`pg_is_in_recovery()`](https://www.postgresql.org/docs/current/functions-admin.html#FUNCTIONS-RECOVERY-CONTROL), and whether a server is read-write or read-only by querying [`default_transaction_read_only`](https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-DEFAULT-TRANSACTION-READ-ONLY) - this is consistent with how PostgreSQL's libpq implements `target_session_attributes`. Servers are queried just before a connection is returned from the pool; the query intervals can be controlled via the `Host Recheck Seconds` parameter (10 seconds by default). - -> [!NOTE] -> If you choose to distribute load across multiple servers, make sure you understand what consistency guarantees are provided by PostgreSQL in your particular setup. In some cases, hot standbys lag behind their primary servers, and will therefore return slightly out-of-date results. This is usually OK, but if you require up-to-date results at all times, synchronous commit may provide a good solution (albeit with a performance cost). - -## Load balancing - -We have seen how to select servers based on the type of workload we want to execute. However, in the above examples, Npgsql still attempts to return connections based on the host order specified in the connection string; this concentrates load on a single primary and possibly a single secondary, and doesn't balance load across multiple servers of the same type. - -You can specify `Load Balance Hosts=true` in the connection string to instruct Npgsql to load balance across all servers, by returning connections in round-robin fashion: - -```text -Host=server1,server2,server3,server4,server5;Username=test;Password=test;Load Balance Hosts=true;Target Session Attributes=prefer-standby -``` - -With this connection string, every time a connection is opened, Npgsql starts at a different point in the list. For example, in the 3rd connection attempt, Npgsql first tries to return a connection to `server3`; if that server is reachable and is a standby, it is selected. This allows spreading your (typically read-only) application load across all available servers, and can greatly improve your scalability. diff --git a/conceptual/Npgsql/faq.md b/conceptual/Npgsql/faq.md deleted file mode 100644 index f94a525f..00000000 --- a/conceptual/Npgsql/faq.md +++ /dev/null @@ -1,65 +0,0 @@ -# FAQ - -## How can I call a PostgreSQL 11 stored procedure? I tried doing so with CommandType.StoredProcedure and got an error... - -PostgreSQL 11 stored procedures can be called, but unfortunately not with `CommandType.StoredProcedure`. PostgreSQL has supported stored *functions* for a long while, and since these have acted as replacements for non-existing procedures, Npgsql's `CommandType.StoredProcedure` has been implemented to invoke them; this means that `CommandType.StoredProcedure` translates into `SELECT * FROM my_stored_function()`. The new stored procedures introduce a special invocation syntax - `CALL my_stored_procedure()` - which is incompatible with the existing stored function syntax. - -On the brighter side, it's very easy to invoke stored procedures (or functions) yourself - you don't really need `CommandType.StoredProcedure`. Simply create a regular command and set `CommandText` to `CALL my_stored_procedure($1, $2)`, handling parameters like you would any other statement. In fact, with Npgsql and PostgreSQL, `CommandType.StoredProcedure` doesn't really have any added value over constructing the command yourself. - -## I opened a pooled connection, and it throws right away when I use it! What gives? - -We know it's frustrating and seems weird, but this behavior is by-design. - -While your connection is idle in the pool, any number of things could happen to it - a timeout could cause it to break, or some other similar network problem. Unfortunately, with the way networking works, there is no reliable way for us to know on the client if a connection is still alive; the only thing we can do is send something to PostgreSQL, and wait for the response to arrive. Doing this whenever a connection is handed out from the pool would kill the very reason pooling exists - it would dramatically slow down pooling, which is there precisely to avoid unneeded network roundtrips. - -But the reality is even more grim than that. Even if Npgsql checked whether a connection is live before handing it out of the pool, there's nothing guaranteeing that the connection won't break 1 millisecond after that check - it's a total race condition. So the check wouldn't just degrade performance, it would also be largely useless. The reality of network programming is that I/O errors can occur at any point, and your code must take that into account if it has high reliability requirements. Resilience/retrying systems can help you with this; take a look at [Polly](https://github.com/App-vNext/Polly) as an example. - -One thing which Npgsql can do to help a bit, is the [keepalive feature](https://www.npgsql.org/doc/keepalive.html); this does a roundtrip with PostgreSQL every e.g. 1 second - including when the connection is idle in the pool - and destroys it if an I/O error occurs. However, depending on timing, you may still get a broken connection out of the pool - unfortunately there's simply no way around that. - -## I get an exception "The field field1 has a type currently unknown to Npgsql (OID XXXXX). You can retrieve it as a string by marking it as unknown". - -Npgsql has to implement support for each PostgreSQL type, and it seems you've stumbled upon an unsupported type. - -First, head over to our [issues page](https://github.com/npgsql/npgsql/issues) and check if an issue already exists on your type, -otherwise please open one to let us know. - -Then, as a workaround, you can have your type treated as text - it will be up to you to parse it in your program. -One simple way to do this is to append ::TEXT in your query (e.g. `SELECT 3::TEXT`). - -If you don't want to modify your query, Npgsql also includes an API for requesting types as text. -The following code returns all the columns in the resultset as text: - -```csharp -await using (var cmd = new NpgsqlCommand(...)) { - cmd.AllResultTypesAreUnknown = true; - await using var reader = await cmd.ExecuteReaderAsync(); - // Read everything as strings -} -``` - -You can also specify text only for some columns in your resultset: - -```csharp -await using (var cmd = new NpgsqlCommand(...)) { - // Only the second field will be fetched as text - cmd.UnknownResultTypeList = new[] { false, true }; - await using var reader = await cmd.ExecuteReaderAsync(); - // Read everything as strings -} -``` - -## I'm trying to write a JSONB type and am getting 'column "XXX" is of type jsonb but expression is of type text' - -When sending a JSONB parameter, you must explicitly specify its type to be JSONB with NpgsqlDbType: - -```csharp -await using (var cmd = new NpgsqlCommand("INSERT INTO foo (col) VALUES ($1)", conn)) { - cmd.Parameters.AddWithValue(NpgsqlDbType.Jsonb, jsonText); -} -``` - -## I'm trying to apply an Entity Framework 6 migration and I get `Type is not resolved for member 'Npgsql.NpgsqlException,Npgsql'` - -Unfortunately, a shortcoming of EF6 requires you to have Npgsql.dll in the Global Assembly Cache (GAC), otherwise you can't see -migration-triggered exceptions. You can add Npgsql.dll to the GAC by opening a VS Developer Command Prompt as administator and -running the command `gacutil /i Npgsql.dll`. You can remove it from the GAC with `gacutil /u Npgsql`. diff --git a/conceptual/Npgsql/index.md b/conceptual/Npgsql/index.md deleted file mode 100644 index 3c633e85..00000000 --- a/conceptual/Npgsql/index.md +++ /dev/null @@ -1,36 +0,0 @@ -# Getting Started - -[![stable](https://img.shields.io/nuget/v/Npgsql.svg?label=stable)](https://www.nuget.org/packages/Npgsql/) -[![next patch](https://img.shields.io/myget/npgsql/v/npgsql.svg?label=next%20patch)](https://www.myget.org/feed/npgsql/package/nuget/Npgsql) -[![vnext](https://img.shields.io/myget/npgsql-vnext/v/npgsql.svg?label=vnext)](https://www.myget.org/feed/npgsql-vnext/package/nuget/Npgsql) -[![build](https://img.shields.io/github/actions/workflow/status/npgsql/npgsql/build.yml?branch=main)](https://github.com/npgsql/npgsql/actions) - -The best way to use Npgsql is to install its [nuget package](https://www.nuget.org/packages/Npgsql/). - -Npgsql aims to be fully ADO.NET-compatible, its API should feel almost identical to other .NET database drivers. - -Here's a basic code snippet to get you started: - -```csharp -var connectionString = "Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase"; -await using var dataSource = NpgsqlDataSource.Create(connectionString); - -// Insert some data -await using (var cmd = dataSource.CreateCommand("INSERT INTO data (some_field) VALUES ($1)")) -{ - cmd.Parameters.AddWithValue("Hello world"); - await cmd.ExecuteNonQueryAsync(); -} - -// Retrieve all rows -await using (var cmd = dataSource.CreateCommand("SELECT some_field FROM data")) -await using (var reader = await cmd.ExecuteReaderAsync()) -{ - while (await reader.ReadAsync()) - { - Console.WriteLine(reader.GetString(0)); - } -} -``` - -You can find more info about the ADO.NET API in the [MSDN docs](https://msdn.microsoft.com/en-us/library/h43ks021(v=vs.110).aspx) or in many tutorials on the Internet. diff --git a/conceptual/Npgsql/installation.md b/conceptual/Npgsql/installation.md deleted file mode 100644 index 35e4b421..00000000 --- a/conceptual/Npgsql/installation.md +++ /dev/null @@ -1,42 +0,0 @@ -# Installation - -## Offical Packages - -Official releases of Npgsql are always available on [nuget.org](https://www.nuget.org/packages/Npgsql/). This is the recommended way to use Npgsql. - -We occasionally publish previews to nuget.org as well - these are generally quite safe for use, and can help us find issues before official packages are released. - -## Daily Builds - -In addition to the official releases, we automatically publish CI packages for every build. You can use these to test new features or bug fixes that haven't been released yet. Two CI nuget feeds are available: - -* [The patch feed](https://www.myget.org/feed/Packages/npgsql) contains CI packages for the next hotfix/patch version. These packages are generally very stable and safe. - To use it, add to your NuGet.Config. -* [The vNext feed](https://www.myget.org/feed/Packages/npgsql-vnext) contains CI packages for the next minor or major versions. These are less stable and should be tested with care. - To use it, add to your NuGet.Config. - -## Older, unsupported installation methods - -### Windows MSI Installer - -If you need to use Npgsql as a database provider for PowerBI, Excel or other similar systems, you need to install it into the Windows [Global Assembly Cache (GAC)](https://msdn.microsoft.com/en-us/library/yf1d93sz%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396), and do some special configuration. Npgsql versions prior to 5.0.0 provided a Windows installer (MSI) which does the installation for you, and which are still usable and maintained with critical bug fixes. Do not use the Windows MSI installer unless you're sure that your program requires GAC installation - this method is otherwise highly discouraged. - -The Npgsql Windows MSI installer for Npgsql 4.1.x can be found on [our Github releases page](https://github.com/npgsql/npgsql/releases): it will install Npgsql (and optionally the Entity Framework providers) into your GAC and add Npgsql's DbProviderFactory into your `machine.config` file. Some additional assemblies which are Npgsql dependencies will be installed into the GAC as well (e.g. `System.Threading.Tasks.Extensions.dll`). - -### Visual Studio Integration - -Older versions of Npgsql came with a Visual Studio extension (VSIX) which integrated PostgreSQL access into Visual Studio. The extension allowed connecting to PostgreSQL from within Visual Studio's Server Explorer, creating an Entity Framework 6 model from an existing database, etc. The extension had various limitations and known issues, mainly because of problems with Visual Studio's extensibility around database. - -Use of the extension is no longer recommended. However, if you'd like to give it a try, it can be installed directly from [the Visual Studio Marketplace page](https://marketplace.visualstudio.com/vsgallery/258be600-452d-4387-9a2f-89ae10e84ae0). - -### DbProviderFactory in .NET Framework - -On .NET Framework, you can register Npgsql's `DbProviderFactory` in your applications `App.Config` (or `Web.Config`), allowing you to use general, provider-independent ADO.NET types in your application (e.g. `DbConnection` instead of `NpgsqlConnection`) - [see this tutorial](https://msdn.microsoft.com/en-us/library/dd0w4a2z%28v=vs.110%29.aspx?f=255&MSPPError=-21472173960). To do this, add the following to your `App.config`: - -```xml - - - - - -``` diff --git a/conceptual/Npgsql/keepalive.md b/conceptual/Npgsql/keepalive.md deleted file mode 100644 index 72ddab04..00000000 --- a/conceptual/Npgsql/keepalive.md +++ /dev/null @@ -1,20 +0,0 @@ -# Keepalive - -Some clients keep idle connections for long periods of time - this is especially frequent when waiting for PostgreSQL notifications. -In this scenario, how can the client know the connection is still up, and hasn't been broken by a server or network outage? -For this purpose, Npgsql has a keepalive feature, which makes it initiate periodic ping roundtrips. -This feature is by default disabled, and must be enabled via the -[Keepalive](connection-string-parameters.md#timeouts-and-keepalive) connection string parameter, setting the number of seconds between each keepalive. - -When keepalive is enabled, Npgsql will emit an -[`NpgsqlConnection.StateChange`](https://msdn.microsoft.com/en-us/library/system.data.common.dbconnection.statechange(v=vs.110).aspx) -event if the keepalive fails. - -Note that you should only turn this feature on if you need it. Unless you know you'll have long-lived idle connections, and that your -backend (or network equipment) will interfere with these connections, it's better to leave this off. - -## TCP Keepalives - -The keepalive mechanism above is ideal for long-standing idle connections, but it cannot be used during query processing. With some PostgreSQL-like data warehouse products such as [Amazon Redshift](http://docs.aws.amazon.com/redshift/latest/mgmt/welcome.html) or [Greenplum](http://greenplum.org/), it is not uncommon for a single SQL statement to take a long time to execute, and during that time it is not possible to send application-level pings. For these cases you may want to turn on *TCP keepalive*, which is quite different from the application-level keepalive described above. To better understand the different kinds of keepalives, see [this blog post](http://blog.stephencleary.com/2009/05/detection-of-half-open-dropped.html). As that article explains, TCP keepalive depends on networking stack support and might not always work, but it is your only option during query processing. - -On Linux, you turn keepalives simply by specifying `Tcp Keepalive=true` in your connection string. The default system-wide settings will be used (for interval, count...) - it is currently impossible to specify these at the application level. On Windows, you can also specify `Tcp Keepalive Time` and `Tcp Keepalive Interval` to tweak these settings. diff --git a/conceptual/Npgsql/performance.md b/conceptual/Npgsql/performance.md deleted file mode 100644 index 96aadebd..00000000 --- a/conceptual/Npgsql/performance.md +++ /dev/null @@ -1,72 +0,0 @@ -# Performance - -## Diagnostics - -To be able to improve performance, you first need to be able to see which queries are slow, and generally observe how your application is behaving. PostgreSQL provide some powerful features for knowing what's going on in the database; [the statistics collector](https://www.postgresql.org/docs/current/monitoring-stats.html) is a good place to start, and in particular the `pg_stat_activity` table, which shows which queries are being executed at any given point. - -Beyond PostgreSQL, Npgsql provides its own set of diagnostics features for tracing, logging and producing metrics. Tracing and metrics are particularly useful for performance analysis - consider collecting this data continuously on your production platform. These features are documented in the dedicated [diagnostics page](diagnostics/overview.md). - -## Prepared Statements - -One of the most important (and easy) ways to improve your application's performance is to prepare your commands. Even if you're not coding against ADO.NET directly (e.g. using Dapper or an O/RM), Npgsql has an automatic preparation feature which allows you to benefit from the performance gains associated with prepared statements. [See this blog post](http://www.roji.org/prepared-statements-in-npgsql-3-2) and/or [the documentation](prepare.md) for more details. - -## Batching/Pipelining - -When you execute a command, Npgsql executes a roundtrip to the database. If you execute multiple commands (say, inserting 3 rows or performing multiple selects), you're executing multiple roundtrips; each command has to complete before the next command can start execution. Depending on your network latency, this can considerably degrade your application's performance. - -You can batch multiple SQL statements in a single roundtrip: - -```csharp -var batch = new NpgsqlBatch(connection) -{ - BatchCommands = { new("SELECT ..."), new("SELECT ...") } -}; -await using (var reader = await batch.ExecuteReaderAsync()) -{ - while (await reader.ReadAsync()) { - // Read first resultset - } - - await reader.NextResultAsync(); - - while (await reader.ReadAsync()) { - // Read second resultset - } -} -``` - -## Disable enlisting to TransactionScope - -By default, Npgsql will enlist to ambient transactions. This occurs when a connection is opened while inside a `TransactionScope`, and can provide a powerful programming model for working with transactions. However, this involves checking whether an ambient transaction is in progress each time a (pooled) connection is open, an operation that takes more time than you'd think. Scenarios where connections are very short-lived and open/close happens very frequently can benefit from removing this check - simply include `Enlist=false` in the connection string. Note that you can still enlist manually by calling `NpgsqlConnection.Enlist()`. - -## Pooled Connection Reset - -When a pooled connection is closed, Npgsql will arrange for its state to be reset the next time it's used. This prevents leakage of state from one usage cycle of a physical connection to another one. For example, you may change certain PostgreSQL parameters (e.g. `statement_timeout`), and it's undesirable for this change to persist when the connection is closed. - -Connection reset happens via the PostgreSQL [`DISCARD ALL` command](https://www.postgresql.org/docs/current/static/sql-discard.html), or, if there are any prepared statements at the time of closing, by a combination of the equivalent statements described in the docs (to prevent closing those statements). Note that these statements aren't actually sent when closing the connection - they're written into Npgsql's internal write buffer, and will be sent with the first user statement after the connection is reopened. This prevents a costly database roundtrip. - -If you really want to squeeze every last bit of performance from PostgreSQL, you may disable connect reset by specifying `No Reset On Close` on your connection string - this will slightly improve performance in scenarios where connection are very short-lived, and especially if prepared statements are in use. - -## Reading Large Values - -When reading results from PostgreSQL, Npgsql first reads raw binary data from the network into an internal read buffer, and then parses that data as you call methods such as `NpgsqlDataReader.GetString()`. While this allows for efficient network reads, it's worth thinking about the size of this buffer, which is 8K by default. Under normal usage, Npgsql attempts to read each row into the buffer; if that entire row fits in 8K, you'll have optimal performance. However, if a row is bigger than 8K, Npgsql will allocate an "oversize buffer", which will be used until the connection is closed or returned to the pool. If you're not careful, this can create significant memory churn that will slow down your application. To avoid this, if you know you're going to be reading 16k rows, you can specify `Read Buffer Size=18000` in your connection string (leaving some margin for protocol overhead), this will ensure that the read buffer is reused and no extra allocation occur. - -Another option is to pass `CommandBehavior.SequentialAccess` to `NpgsqlCommand.ExecuteReader()`. Sequential mode means that Npgsql will no longer read entire rows into its buffer, but will rather fill up the buffer as needed, reading more data only when it's empty. The same 8K read buffer will be used regardless of the row's total size, and Npgsql will take care of the details. In sequential mode, however, you must read the row's fields in the order in which you specified them; you cannot read the 2nd field and then go back to the 1st field, and trying to do so will generate an exception. Similarly, you cannot read the same field twice - once you've read a field, it has been consumed. - -For more information on `CommandBehavior.SequentialAccess`, see [this page](https://msdn.microsoft.com/en-us/library/87z0hy49(v=vs.110).aspx). If you decide to use this feature, be aware that it isn't used as often and may therefore contain bugs. - -You can also control the socket's receive buffer size (not to be confused with Npgsql's internal buffer) by setting the `Socket Receive Buffer Size` connection string parameter. - -## Writing Large Values - -Writing is somewhat similar - Npgsql has an internal write buffer (also 8K by default). When writing your query's SQL and parameters to PostgreSQL, Npgsql always writes "sequentially", that is, filling up the 8K buffer and flushing it when full. You can use `Write Buffer Size` to control the buffer's size. - -You can also control the socket's send buffer size (not to be confused with Npgsql's internal buffer) by setting the `Socket Send Buffer Size` connection string parameter. - -## Avoiding boxing when writing parameter values - -See [this section](basic-usage.md#strongly-typed-parameters). - -## Unix Domain Socket - -If you're connecting to a PostgreSQL server on the same machine, you can boost performance a little by connecting via Unix domain socket rather than via a regular TCP/IP socket. To do this, simply specify the directory of your PostgreSQL sockets in the `Host` connection string parameter - if this parameter starts with a slash or drive letter, it will be taken to mean a filesystem path. diff --git a/conceptual/Npgsql/prepare.md b/conceptual/Npgsql/prepare.md deleted file mode 100644 index cf74e3a6..00000000 --- a/conceptual/Npgsql/prepare.md +++ /dev/null @@ -1,86 +0,0 @@ -# Prepared Statements - -## Introduction - -It's recommended that you start by reading [this blog post](http://www.roji.org/prepared-statements-in-npgsql-3-2). - -Most applications repeat the same SQL statements many times, passing different parameters. In such cases, it's very beneficial to *prepare* commands - this will send the command's statement(s) to PostgreSQL, which will parse and plan for them. The prepared statements can then be used on execution, saving valuable planning time. The more complex your queries, the more you'll notice the performance gain; but even very simple queries tend to benefit from preparation. - -Following is a benchmark Npgsql.Benchmarks.Prepare, which measures the execution time of the same query, executed prepared and unprepared. `TablesToJoin` is a parameter which increases the query complexity - it determines how many tables the query joins from. - -| Method | TablesToJoin | Mean | StdErr | StdDev | Op/s | Scaled | Scaled-StdDev | Allocated | -| ------------- |------------- |--------------- |----------- |------------ |--------- |------- |-------------- |---------- | -| **Unprepared** | **0** | **67.1964 us** | **0.1586 us** | **0.6142 us** | **14881.75** | **1.00** | **0.00** | **1.9 kB** | -| Prepared | 0 | 43.5007 us | 0.2466 us | 0.9227 us | 22988.13 | 0.65 | 0.01 | 305 B | -| **Unprepared** | **1** | **98.8502 us** | **0.1278 us** | **0.4949 us** | **10116.32** | **1.00** | **0.00** | **1.93 kB** | -| Prepared | 1 | 53.7518 us | 0.0486 us | 0.1818 us | 18604.04 | 0.54 | 0.00 | 306 B | -| **Unprepared** | **2** | **180.0599 us** | **0.2990 us** | **1.1579 us** | **5553.71** | **1.00** | **0.00** | **2.06 kB** | -| Prepared | 2 | 70.3609 us | 0.1715 us | 0.6417 us | 14212.44 | 0.39 | 0.00 | 306 B | -| **Unprepared** | **5** | **1,084.6065 us** | **1.1822 us** | **4.2626 us** | **921.99** | **1.00** | **0.00** | **2.37 kB** | -| Prepared | 5 | 110.0652 us | 0.1098 us | 0.3805 us | 9085.52 | 0.10 | 0.00 | 308 B | -| **Unprepared** | **10** | **23,086.5956 us** | **37.2072 us** | **139.2167 us** | **43.32** | **1.00** | **0.00** | **3.11 kB** | -| Prepared | 10 | 197.1392 us | 0.3044 us | 1.1790 us | 5072.56 | 0.01 | 0.00 | 308 B | - -As is immediately apparent, even an extremely simple scenario (TablesToJoin=0, SQL=SELECT 1), preparing the query with PostgreSQL provides a 36% speedup. As query complexity increases by adding join tables, the gap widens dramatically. - -The only potential disadvantage of prepared statements is that they hold server-side resources (e.g. cached plans). If you're dynamically generating SQL queries, make sure you don't overwhelm the server by preparing too much. Most reasonable applications shouldn't have to worry about this. - -## Simple Preparation - -To prepare your commands, simply use the following standard ADO.NET code: - -```csharp -var cmd = new NpgsqlCommand(...); -cmd.Parameters.Add("param", NpgsqlDbType.Integer); -await cmd.PrepareAsync(); -// Set parameters -await cmd.ExecuteNonQueryAsync(); -// And so on -``` - -The above shows the typical use-case, where you first prepare a command without providing any parameter values, and then execute that same command many times, setting different values each time. In this case, all parameters are added before calling `PrepareAsync()`, and these must have `DbType`, `NpgsqlDbType` or `DataTypeName` set in order to identify the parameter type, which is necessary for preparation. Alternatively, you can set values on the command's parameters before preparing it, in which case parameter types are inferred as usual ([see parameter documentation](basic-usage.md#parameters)). - -Note that preparation happens on individual statements, and not on commands, which can contain multiple statements, batching them together. This can be important in cases such as the following: - -```csharp -var cmd = new NpgsqlCommand("UPDATE foo SET bar=@bar WHERE baz=@baz; UPDATE foo SET bar=@bar WHERE baz=@baz"); -// set parameters. -await cmd.PrepareAsync(); -``` - -Although there are two statements in this command, the same prepared statement is used to execute since the SQL is identical. - -## Persistency - -With many database drivers, prepared statements are closed when their owning command was disposed. This significantly reduces their usefulness, especially since closing a pooled connection automatically closes all prepared statements. For applications where connections are short-lived - most web applications - this effectively makes prepared statements useless. - -In Npgsql, all prepared statements are persistent - they don't get closed when a command or connection is closed. Npgsql keeps track of statements prepared on each physical connection; if you prepare the same SQL a second time on the same physical connection, Npgsql will simply reuse the prepared statement from the first preparation. This means that in an application with short-lived, pooled connections, prepared statements will gradually be created as the application warms up and the connections are first used. Then, opening a new pooled connection will return a physical connection that already has a prepared statement for your SQL, providing a very substantial performance boost. For example: - -```csharp -await using (var conn = await dataSource.OpenConnectionAsync()) -await using (var cmd = new NpgsqlCommand("", conn)) -{ - await cmd.PrepareAsync(); // First time on this physical connection, Npgsql prepares with PostgreSQL - await cmd.ExecuteNonQueryAsync(); -} - -await using (var conn = await dataSource.OpenConnectionAsync()) -await using (var cmd = new NpgsqlCommand("", conn)) -{ - // We assume the internal connection pool returned the same physical connection used above - await cmd.PrepareAsync(); // The connection already has a prepared statement for , this doesn't need to do anything - await cmd.ExecuteNonQueryAsync(); -} -``` - -You can still choose to close a prepared statement by calling `NpgsqlCommand.Unprepare()`. You can also unprepare all statements on a given connection by calling `NpgsqlConnection.UnprepareAll()`. - -## Automatic Preparation - -While the preparation examples shown above provide a very significant performance boost, they depend on you calling the `Prepare()` command. Unfortunately, if you're using some data layer above ADO.NET, such as [Dapper](https://github.com/StackExchange/dapper-dot-net) or [Entity Framework](https://docs.microsoft.com/en-us/ef/), chances are these layers don't prepare for you. While issues exist for both [Dapper](https://github.com/StackExchange/dapper-dot-net/issues/474) and [Entity Framework Core](https://github.com/aspnet/EntityFramework/issues/5459), they don't take advantage of prepared statement at the moment. - -Npgsql supports automatic preparation. When turned on, this will make Npgsql track the statements you execute and automatically prepare them when you reach a certain threshold. When you reach that threshold, the statement is automatically prepared, and from that point on will be executed as prepared, yielding all the performance benefits discussed above. To turn on this feature, you simply need to set the `Max Auto Prepare` connection string parameter, which determines how many statements can be automatically prepared on the connection at any given time (this parameter defaults to 0, disabling the feature). A second parameter, `Auto Prepare Min Usages`, determines how many times a statement needs to be executed before it is auto-prepared (defaults to 5). Since no code changes are required, you can simply try setting `Max Auto Prepare` and running your application to see an immediate speed increase. Note also that, like explicitly-prepared statements, auto-prepared statements are persistent, allowing you to reap the performance benefits in short-lived connection applications. - -Note that if you're coding directly against Npgsql or ADO.NET, explicitly preparing your commands with `Prepare()` is still recommended over letting Npgsql prepare automatically. Automatic preparation does incur a slight performance cost compared to explicit preparation, because of the internal LRU cache and various book-keeping data structures. Explicitly preparing also allows you to better control exactly which statements are prepared and which aren't, and ensures your statements will always stay prepared, and never get ejected because of the LRU mechanism. - -Note that automatic preparation is a complex new feature which should be considered somewhat experimental; test carefully, and if you see any strange behavior or problem try turning it off. diff --git a/conceptual/Npgsql/release-notes/10.0.md b/conceptual/Npgsql/release-notes/10.0.md deleted file mode 100644 index 73e346a7..00000000 --- a/conceptual/Npgsql/release-notes/10.0.md +++ /dev/null @@ -1,125 +0,0 @@ -# Npgsql 10.0 Release Notes - -Npgsql version 10.0 is out and available on [nuget.org](https://www.nuget.org/packages/Npgsql). - -While this is a relatively minor release in terms of changes, it does contain new features and improvements. Notable changes: - -## Tracing and metrics improvements - -Npgsql 10.0 brings multiple observability improvements: - -* Command tracing has been changed to align with [the stable OpenTelemetry tracing semantic conventions](https://opentelemetry.io/docs/specs/semconv/database/database-spans/). This allows tracing any database driver using the same span and tags. -* Metrics support has also been changed to conform to the [OpenTelemetry metrics semantic conventions](https://opentelemetry.io/docs/specs/semconv/database/database-metrics/). The stable `db.client.operation.duration` metric is now emitted, as well as the non-stable `db.client.connection.count`, `db.client.connection.max`. The remaining Npgsql-specific metrics have been renamed for consistency. -* COPY operations (binary, text and raw import/export) are now fully traced. Thanks to [@manandre](https://github.com/manandre) for contributing this feature! -* The opening of physical connections is now also traced, allowing you to observe and identify performance issues. - -Note that these changes modify the metric names and tracing span tags, and so are breaking to anyone currently consuming Npgsql tracing/metrics. - -## GSSAPI session encryption - -GSSAPI session encryption is an alternative to SSL/TLS session encryption, where special temporary tokens are used to encrypt traffic between the client and the server (MIT Kerberos is one of the GSSAPI providers that can be used for that), unlike SSL/TLS, where the SSL certificate is used for the same purpose. You can use the `GssEncryptionMode` connection string parameter to control whether GSS session encryption is used; the default is `Prefer`, which will enable the feature if possible but proceed if it's not available. - -To learn more, [see the security and encryption docs](../security.md). - -## Support for RequireAuth in connection string - -`RequireAuth` is used to determine which authentication methods are allowed/required. For example, if you want to make sure that passwords aren't sent as cleartext or MD5, you can specify `RequireAuth=!Password,!MD5`. Or, if you want to make sure to always authenticate either via ScramSHA256 or GSS, then you can specify it as `RequireAuth=ScramSHA256,GSS`. To learn more, see PostgreSQL [docs](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-REQUIRE-AUTH). - -## Support for the cube extension - -PostgreSQL bundles the [`cube`](https://www.postgresql.org/docs/current/cube.html) extension, which provides a multi-dimensional cube data type and associated operations. Npgsql 10 now fully supports the `cube` type out-of-the-box: - -```c# -command.CommandText = """ - CREATE EXTENSION IF NOT EXISTS cube; - CREATE TABLE data (my_cude CUBE); -"""; -await command.ExecuteNonQueryAsync(); - -var cube = new NpgsqlCube([1.0, 2.0, 3.0], [4.0, 5.0, 6.0]); -command.CommandText = "INSERT INTO data (my_cude) VALUES ($1)"; -command.Parameters.Add(new() { Value = cube }); -await command.ExecuteNonQueryAsync(); - -command.CommandText = "SELECT my_cude FROM data"; -var readCube = (NpgsqlCube)(await command.ExecuteScalarAsync())!; -Console.WriteLine($"Read cube: {readCube}"); -``` - -Thanks to [@kirkbrauer](https://github.com/kirkbrauer) for contributing this feature! - -## Various other changes - -* OpenTelemetry tracing now also included by default for whenever a physical connection to database is open. -* Added support for `PGAPPNAME` environment variable. It's mapped to `ApplicationName` field of the connection string. -* Added support for SHA3 hash algorithms with SASL authentication. Previously, Npgsql falled back to SCRAM-SHA-256 if the certificate, provided by the database, had SHA3 signature algorithm. -* `NpgsqlConnection.Open` now wraps `SocketException` with `NpgsqlException` when hostname can't be resolved. -* Metrics names are now more aligned to the OpenTelemetry standard (see breaking change note below). -* The connection string now supports specifying `TargetSessionAttributes` when used with `NpgsqlDataSourceBuilder`. This means that code creating `NpgsqlDataSource` doesn't have to be aware that it's used with multiple hosts. -* The built-in geometry types (e.g. `NpgsqlBox`) can now be deconstructed. Thanks [@ddas09](https://github.com/ddas09) for contributing! -* The new `IDbTypeResolver` now allows remapping DbType values to arbitrary PostgreSQL types. - -## Breaking changes - -### .NET 6 is no longer supported - -With .NET 6 being out of support since November 2024, Npgsql 10.0 also drops support for .NET 6. This change allows us to have a much better capability parity between different versions of .NET, while also removing hundreds lines of compatibility-only code and simplifying the codebase. - -### `date` and `time` are now mapped to `DateOnly` and `TimeOnly` - -The PostgreSQL `date` and `time` types are now read as .NET [`DateOnly`](https://learn.microsoft.com/dotnet/api/system.dateonly) and [`TimeOnly`](https://learn.microsoft.com/dotnet/api/system.timeonly), instead of [`DateTime`](https://learn.microsoft.com/dotnet/api/system.datetime) and [`TimeSpan`](https://learn.microsoft.com/dotnet/api/system.timespan) by default, respectively. This affects non-generic read methods which return `object`, such as and ; you can still read `DateTime` and `TimeSpan` via the generic . - -If your code relies on Npgsql returning `DateTime`/`TimeSpan` by default, and you are unable to either call `GetFieldValue()` or change your code to handle `DateOnly`/`TimeOnly` instead, then you can revert Npgsql's behavior to the pre-10.0 behavior. To do this, drop the [LegacyDateAndTimeResolverFactory.cs](/static/LegacyDateAndTimeResolverFactory.cs) into your project, and register it with your `NpgsqlDataSourceBuilder` as follows: - -```c# -NpgsqlDataSourceBuilder build = ...; -builder.AddTypeInfoResolverFactory(new LegacyDateAndTimeResolverFactory()); -``` - -Alternatively, if you're not yet using `NpgsqlDataSource`, register it with the global type mapper: - -```c# -NpgsqlConnection.GlobalTypeMapper.AddTypeInfoResolverFactory(new LegacyDateAndTimeResolverFactory()); -``` - -### `cidr` is now mapped to `IPNetwork` - -With .NET 6 no longer supported by Npgsql, the PostgreSQL `cidr` type is now mapped to `IPNetwork` by default instead of `NpgsqlCidr`. In addition, `NpgsqlCidr` is now obsolete and will be removed in the future. - -### Tracing and metrics have been changed to align with the OpenTelemetry standard - -Npgsql emits metrics and tracing data that provide various information about commands and connections. Since these were designed when the OpenTelemetry specifications were in an earlier stage, they did not align with current standard naming. Npgsql 10 changes metrics names and tracing span tags to better align with the standard, allowing Npgsql observability data to be tracked in dashboards just like other standards-conforming database drivers. If you already have a dashboard set up to consume Npgsql observability data, its configuration will need to change to accomodate the new naming. - -### Cannot load library libgssapi_krb5.so.2 when Kerberos is not installed - -Since Npgsql 10.0 defaults to trying GSSAPI session encryption, it may generate the following error on some Linux environments: - -```error -Cannot load library libgssapi_krb5.so.2: cannot open shared object file: No such file or directory -``` - -Npgsql internally handles this and falls back to connecting without GSSAPI, so the error is harmless. You can specify `GSS Encryption Mode=Disable` to stop Npgsql from trying to use GSSAPI and remove the error. - -### Only root CA certificate is used to validate TLS chain - -While establishing TLS connection with PostgreSQL, Npgsql will now only use the provided root CA certificate to validate TLS chain instead of using it in addition to the system CA store. This behaviour aligns with libpq and prevents establishing unintended connections. - -### COPY operation's `Timeout` property now treats `Timeout.InfiniteTimeSpan` as an infinite timeout instead of `TimeSpan.Zero` - -This is in line with other .NET API (like `NetworkStream.ReadTimeout`), where `Timeout.InfiniteTimeSpan` and `Timeout.Infinite` are treated as infinite. - -### `PostgresException.BatchCommand` is `null` by default - -This prevents accidental leak of queries and parameters when exceptions are logged. To change this behavior you can set `IncludeFailedBatchedCommand` in connection string to `true`. - -### NpgsqlConnection.BeginText{Import,Export}Async now return NpgsqlCopyTextReader instead of TextWriter - -The methods to start a text import/export operation have been changed to return a more specific `NpgsqlCopyTextReader`, rather than a general `TextWriter`; this was done since `NpgsqlCopyTextReader` exposes some additional APIs to allow cancelling and setting the timeout on a COPY operation. Since `NpgsqlCopyTextReader` extends `TextWriter`, this is a binary breaking change only - recompiling against the new version of Npgsql should work without any source changes. - -### NpgsqlParameter.DataTypeName now takes precedence over NpgsqlDbType - -NpgsqlParameter allows configuring which PostgreSQL is sent to the database via several methods: DataTypeName (for a PostgreSQL type name as a string), NpgsqlDbType (PG-specific enum), or DbType (database-agnostic enum). Starting with Npgsql 10, setting DataTypeName takes precedence over NpgsqlDbType. - -### JSON mutable DOM mappings (e.g. JsonNode, JsonArray...) now require EnableJsonTypes on NpgsqlSlimDataSourceBuilder - -NativeAOT applications which use `NpgsqlSlimDataSourceBuilder` and make use of mutable JSON types (`JsonNode`, `JsonValue`...) now have to call `EnableJsonTypes()`. Previously, calling `EnableJsonDynamicTypes()` added these mappings. diff --git a/conceptual/Npgsql/release-notes/11.0.md b/conceptual/Npgsql/release-notes/11.0.md deleted file mode 100644 index ce0f8320..00000000 --- a/conceptual/Npgsql/release-notes/11.0.md +++ /dev/null @@ -1,23 +0,0 @@ -# Npgsql 11.0 Release Notes - -Npgsql 11.0.0 is available on [NuGet](https://www.nuget.org/packages/Npgsql/11.0.0). - -See the [11.0.0 milestone](https://github.com/npgsql/npgsql/milestone/132?closed=1) for the full list of issues. - -## Breaking changes - -### Dependency injection is now part of Npgsql - -The `Npgsql.DependencyInjection` package was merged into `Npgsql`. Remove the separate package reference when upgrading. Existing calls to `AddNpgsqlDataSource()` and related methods continue to work from the `Microsoft.Extensions.DependencyInjection` namespace, except for previously obsolete overloads, which have been removed. See [dependency injection setup](../diagnostics/logging.md#aspnet-and-dependency-injection) ([#6594](https://github.com/npgsql/npgsql/pull/6594)). - -### Removed multiplexing - -The experimental multiplexing mode has been removed. It could increase throughput for some workloads but did not scale well with high concurrency on machines with many CPU cores. Remove `Multiplexing` and `Write Coalescing Buffer Threshold Bytes` from your connection strings, even if multiplexing was disabled, and remove any assignments to the corresponding connection string builder properties. Regular connection pooling is unchanged ([#6457](https://github.com/npgsql/npgsql/pull/6457)). - -### Removed deprecated large object APIs - -`NpgsqlLargeObjectManager` and `NpgsqlLargeObjectStream`, obsolete since Npgsql 8.0, have been removed. Use PostgreSQL's [large object functions](https://www.postgresql.org/docs/current/lo-funcs.html) directly. For example, `lo_get` and `lo_put` read and write byte ranges. If you use `lo_open` to obtain a descriptor, use it on the same connection and within the same transaction. Existing large objects do not need to be migrated ([#6493](https://github.com/npgsql/npgsql/pull/6493)). - -### Application Name can change pool metric labels - -If you set `Application Name` in your connection string without explicitly naming the data source, Npgsql 11 uses that application name rather than the connection string as the `db.client.connection.pool.name` metric tag. Update dashboards that filter on the old label, or set `NpgsqlDataSourceBuilder.Name` explicitly to control the label and distinguish pools with the same application name. See [metrics](../diagnostics/metrics.md) ([#6533](https://github.com/npgsql/npgsql/pull/6533)). diff --git a/conceptual/Npgsql/release-notes/3.0.md b/conceptual/Npgsql/release-notes/3.0.md deleted file mode 100644 index 39bd9344..00000000 --- a/conceptual/Npgsql/release-notes/3.0.md +++ /dev/null @@ -1,126 +0,0 @@ -# Npgsql 3.0 Release Notes - -## Migrating from 2.2 to 3.0 - -Version 3.0 represents a near-total rewrite of Npgsql. In addition to changing how Npgsql works internally and communicates with PostgreSQL, a conscious effort was made to better align Npgsql with the ADO.NET specs/standard and with SqlClient where that made sense. This means that you cannot expect to drop 3.0 as a replacement to 2.2 and expect things to work - upgrade cautiously and test extensively before deploying anything to production. - -The following is a *non-exhaustive* list of things that changed. If you run against a breaking change not documented here, please let us know and we'll add it. - -## Major - -* Support for .NET 2.0, .NET 3.5 and .NET 4.0 has been dropped - you will have to upgrade to .NET 4.5 to use Npgsql 3.0. We'll continue to do bugfixes on the 2.2 branch for a while on a best-effort basis. -* The Entity Framework provider packages have been renamed to align with Microsoft's new naming. The new packages are *EntityFramework5.Npgsql* and *EntityFramework6.Npgsql*. EntityFramework7.Npgsql is in alpha. -* A brand-new bulk copy API has been written, using binary encoding for much better performance. See [the docs](../copy.md). -* Composite (custom) types aren't supported yet, but this is a high-priority feature for us. See [#441](https://github.com/npgsql/npgsql/issues/441). - -## SSL - -* Npgsql 2.2 didn't perform validation on the server's certificate by default, so self-signed certificate were accepted. The new default is to perform validation. Specify the [Trust Server Certificate](../connection-string-parameters.md#security-and-encryption) connection string parameter to get back previous behavior. -* The "SSL" connection string parameter has been removed, use "SSL Mode" instead. -* The "SSL Mode" parameter's Allow option has been removed, as it wasn't doing anything. - -## Type Handling - -* Previously, Npgsql allowed writing a NULL by setting NpgsqlParameter.Value to `null`. This is [not allowed in ADO.NET](https://msdn.microsoft.com/en-us/library/system.data.common.dbparameter.value%28v=vs.110%29.aspx) and is no longer supported, set to `DBNull.Value` instead. -* In some cases, you will now be required to explicitly set a parameter's type although you didn't have to before (you'll get an error 42804 explaining this). This can happen especially in Dapper custom custom type handlers ([#694](https://github.com/npgsql/npgsql/issues/694)). Simply set the NpgsqlDbType property on the parameter. -* Removed support for writing a parameter with an `IEnumerable` value, since that would require Npgsql to enumerate it multiple times internally. `IList` and IList are permitted. -* It is no longer possible to write a .NET enum to an integral PostgreSQL column (e.g. int4). Proper enum support has been added which allows writing to PostgreSQL enum columns (see [the docs](https://www.npgsql.org/doc/enum.html). To continue writing enums to integral columns as before, simply add an explicit cast to the integral type in your code. -* NpgsqlMacAddress has been removed and replaced by the standard .NET PhysicalAddress. -* Npgsql's BitString has been removed and replaced by the standard .NET BitArray. -* NpgsqlTime has been removed and replaced by the standard .NET TimeSpan. -* NpgsqlTimeZone has been removed. -* NpgsqlTimeTZ now holds 2 TimeSpans, rather than an NpgsqlTime and an NpgsqlTimeZone. -* NpgsqlTimeStamp no longer maps DateTime.{Max,Min}Value to {positive,negative} infinity. Use NpgsqlTimeStamp.Infinity and NpgsqlTimeStamp.MinusInfinity explicitly for that. You can also specify the "Convert Infinity DateTime" connection string parameter to retain the old behavior. -* Renamed NpgsqlInet's addr and mask to Address and Mask. -* NpgsqlPoint now holds Doubles instead of Singles ([#437](https://github.com/npgsql/npgsql/issues/437)). -* NpgsqlDataReader.GetFieldType() and GetProviderSpecificFieldType() now return Array for arrays. - Previously they returned int[], even for multidimensional arrays. -* NpgsqlDataReader.GetDataTypeName() now returns the name of the PostgreSQL type rather than its OID. - -## Retired features - -* Removed the "Preload Reader" feature, which loaded the entire resultset into memory. If you require this (inefficient) behavior, read the result into memory outside Npgsql. We plan on working on MARS support, see [#462](https://github.com/npgsql/npgsql/issues/462). -* The "Use Extended Types" parameter is no longer needed and isn't supported. To access PostgreSQL values that can't be represented by the standard CLR types, use the standard ADO.NET `NpgsqlDataReader.GetProviderSpecificValue` or even better, the generic `NpgsqlDataReader.GetFieldValue`. -* Removed the feature where Npgsql automatically "dereferenced" a resultset of refcursors into multiple resultsets (this was used to emulate returning multiple resultsets from stored procedures). Note that if your function needs to return a single resultset, it should be simply returning a table rather than a cursor (see `RETURNS TABLE`). See [#438](https://github.com/npgsql/npgsql/issues/438). -* Removed the AlwaysPrepare connection string parameter -* Removed the Encoding connection string parameter, which was obsolete and unused anyway (UTF8 was always used regardless of what was specified) -* Removed the Protocol connection string parameter, which was obsolete and unused anyway (protocol 3 was always used) -* Removed NpgsqlDataReader.LastInsertedOID, it did not allow accessing individual OIDs in multi-statement commands. Replaced with NpgsqlDataReader.Statements, which provides OID and affected row information on a statement-by-statement basis. -* Removed `NpgsqlDataReader.HasOrdinal`, was a badly-named non-standard API without a serious use case. `GetName()` can be used as a workaround. - -## Other - -* It is no longer possible to create database entities (tables, functions) and then use them in the same multi-query command - you must first send a command creating the entity, and only then send commands using it. See [#641](https://github.com/npgsql/npgsql/issues/641) for more details. -* Previously, Npgsql set DateStyle=ISO, lc_monetary=C and extra_float_digits=3 on all connections it created. This is no longer case, if you rely on these parameters you must send them yourself. -* NpgsqlConnection.Clone() will now only return a new connection with the same connection string as the original. Previous versions returned an open connection if the original was open, and copied the Notice event listeners as well. Note: NpgsqlConnection.Clone() was accidentally missing from 3.0.0 and 3.0.1. -* Removed the obsolete `NpgsqlParameterCollection.Add(name, value)` method. Use `AddWithValue()` instead, which also exists in SqlClient. -* The savepoint manipulation methods on `NpgsqlTransaction` have been renamed from `Save`, and `Rollback` to `CreateSavepoint` and `RollbackToSavepoint`. This broke the naming conventions for these methods across other providers (SqlClient, Oracle...) and so in 3.0.2 the previous names were returned and the new names marked as obsolete. 3.1 will remove the the new names and leaves only `Save` and `Rollback`. See [#738](https://github.com/npgsql/npgsql/issues/738). -* The default CommandTimeout has changed from 20 seconds to 30 seconds, as in [ADO.NET](https://msdn.microsoft.com/en-us/library/system.data.idbcommand.commandtimeout(v=vs.110).aspx). -* `CommandType.TableDirect` now requires CommandText to contain the name of a table, as per the [MSDN docs](https://msdn.microsoft.com/en-us/library/system.data.commandtype%28v=vs.110%29.aspx). Multiple tables (join) aren't supported. -* `CommandType.StoredProcedure` now requires CommandText contain *only* the name of a function, without parentheses or parameter information, as per the [MSDN docs](https://msdn.microsoft.com/en-us/library/system.data.commandtype%28v=vs.110%29.aspx). -* Moved the `LastInsertedOID` property from NpgsqlCommand to NpgsqlReader, like the standard ADO.NET `RecordsAffected`. -* A single SQL statement may no longer have more than 65535 parameters. If you're bulk-importing a large number of rows, consider using the [binary COPY API](https://www.npgsql.org/doc/copy.html) which is considerably more efficient, or an alternative method such as [inserting from array parameters](https://klotzandrew.com/blog/postgres-passing-65535-parameter-limit). - -## Contributors - -Thank you very much to the following people who have contributed to the individual 3.0.x. releases. - -### [Milestone 3.0.8](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.8) - -Contributor | Assigned issues ------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [11](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.8+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.0.7](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.7) - -Contributor | Assigned issues ------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.7+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.0.6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.6) - -Contributor | Assigned issues ------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [10](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.6+is%3Aclosed+assignee%3Aroji) -[@Emill](https://github.com/Emill) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.6+is%3Aclosed+assignee%3AEmill) - -### [Milestone 3.0.5](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.5) - -Contributor | Assigned issues ------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.5+is%3Aclosed+assignee%3Aroji) -[@kenjiuno](https://github.com/kenjiuno) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.5+is%3Aclosed+assignee%3Akenjiuno) - -### [Milestone 3.0.4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.4) - -Contributor | Assigned issues ------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [10](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.4+is%3Aclosed+assignee%3Aroji) -[@damageboy](https://github.com/damageboy) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.4+is%3Aclosed+assignee%3Adamageboy) - -### [Milestone 3.0.3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.3) - -Contributor | Assigned issues ------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [14](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.3+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.0.2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.2) - -Contributor | Assigned issues ------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [8](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.2+is%3Aclosed+assignee%3Aroji) -[@Emill](https://github.com/Emill) | [4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.2+is%3Aclosed+assignee%3AEmill) - -### [Milestone 3.0.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.1) - -Contributor | Assigned issues ------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [13](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.1+is%3Aclosed+assignee%3Aroji) -[@Emill](https://github.com/Emill) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.1+is%3Aclosed+assignee%3AEmill) - -### [Milestone 3.0.0](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.0) - -Contributor | Assigned issues ------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [62](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3Aroji) -[@Emill](https://github.com/Emill) | [3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.0.0+is%3Aclosed+assignee%3AEmill) diff --git a/conceptual/Npgsql/release-notes/3.1.md b/conceptual/Npgsql/release-notes/3.1.md deleted file mode 100644 index 11faf637..00000000 --- a/conceptual/Npgsql/release-notes/3.1.md +++ /dev/null @@ -1,98 +0,0 @@ -# Npgsql 3.1 Release Notes - -## Migrating from 3.0 to 3.1 - -* CommandTimeout used to be implemented with PostgreSQL's `statement_timeout` parameter, but this wasn't a very reliable method and has been removed. CommandTimeout is now implemented via socket timeouts only, see [#689](https://github.com/npgsql/npgsql/issues/689) for more details. Note that if a socket timeout occurs, the connection is broken and must be reopened. -* The [`Persist Security Info`](../connection-string-parameters.md#security-and-encryption) parameter has been implemented and is false by default. This means that once a connection has been opened, you will not be able to get its password. -* Removed ContinuousProcessing mode, and replaced it with [Wait](../wait.md), a simpler and less bug-prone mechanism for consuming asynchronous notifications ([#1024](https://github.com/npgsql/npgsql/issues/1024)). -* The `Maximum Pool Size` connection is parameter is now 100 default instead of 20 (this is default in SqlClient, pg_bouncer...). -* The `Connection Lifetime` parameter has been renamed to `Connection Idle Lifetime`, and its default has been changed from 15 to 300. Also, once the number of seconds has elapsed the connection is closed immediately; the previous behavior closed half of the connections. -* `RegisterEnum` and `RegisterEnumGlobally` have been renamed to `MapEnum` and `MapEnumGlobally` respectively. -* If you used enum mapping in 3.0, the strategy for translating between CLR and PostgreSQL type names has changed. In 3.0 Npgsql simply used the CLR name (e.g. SomeField) as the PostgreSQL name; Npgsql 3.1 uses a user-definable name translator, default to snake case (e.g. some_field). See [#859](https://github.com/npgsql/npgsql/issues/859). -* The `EnumLabel` attribute has been replaced by the `PgName` attribute (which is also used for the new composite type support). -* When PostgreSQL sends an error, it is no longer raised by an NpgsqlException but by a PostgresException. PostgresException is a subclass of NpgsqlException so code catching NpgsqlException should still work, but the PostgreSQL-specific exception properties will only be available on PostgresException. -* The Code property on NpgsqlException has been renamed to SqlState. It has also been moved to PostgresException. -* NpgsqlNotice has been renamed to PostgresNotice -* For multistatement commands, PostgreSQL parse errors will now be thrown only when the user calls NextResult() and gets to the problematic statement. -* It is no longer possible to dispose a prepared statement while a reader is still open. Since disposing a prepared statement includes database interaction, the connection must be idle. -* Removed `NpgsqlConnection.SupportsHexByteFormat`. -* Renamed `NpgsqlConnection.Supports_E_StringPrefix` to `SupportsEStringPrefix`. - -## Contributors - -Thank you very much to the following people who have contributed to the individual 3.1.x. releases. - -### [Milestone 3.1.10](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A3.1.10) - -| Contributor | Assigned issues | -| -------------------------------- | --------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [5](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A3.1.10+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 3.1.9](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.9) - -Contributor | Assigned issues --------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [10](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.9+is%3Aclosed+assignee%3Aroji) -[@DaveVdE](https://github.com/DaveVdE) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.9+is%3Aclosed+assignee%3ADaveVdE) -[@rwasef1830](https://github.com/rwasef1830) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.9+is%3Aclosed+assignee%3Arwasef1830) - -### [Milestone 3.1.8](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.8) - -Contributor | Assigned issues --------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [10](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.8+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.7](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.7) - -Contributor | Assigned issues --------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [7](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.7+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.6) - -Contributor | Assigned issues --------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [5](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.6+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.5](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.5) - -Contributor | Assigned issues --------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.5+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.4) - -Contributor | Assigned issues --------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.4+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.3) - -Contributor | Assigned issues --------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [10](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.3+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.2) - -Contributor | Assigned issues --------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.2+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.10](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.10) - -Contributor | Assigned issues --------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [5](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.10+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.1) - -Contributor | Assigned issues --------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [5](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.1+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.1.0](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.0) - -Contributor | Assigned issues --------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [24](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3Aroji) -[@Emill](https://github.com/Emill) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.1.0+is%3Aclosed+assignee%3AEmill) diff --git a/conceptual/Npgsql/release-notes/3.2.md b/conceptual/Npgsql/release-notes/3.2.md deleted file mode 100644 index f7252ce9..00000000 --- a/conceptual/Npgsql/release-notes/3.2.md +++ /dev/null @@ -1,86 +0,0 @@ -# Npgsql 3.2 Release Notes - -Npgsql 3.2 is out and available on nuget.org. This is a major release with substantial internal changes and should be deployed with care. For critical applications it may be advisable to wait until 3.2.1 is out. - -This release contains a large number of new features, but the main focus is performance - some usage scenarios may show dramatic improvements. See below for more details. - -## Major Changes - -* Prepared statements are now persistent (survive beyond pooled connection close/open), providing significant performance improvements for applications with short-lived connections, such as most webapps ([#483](https://github.com/npgsql/npgsql/issues/483)). Also, statements can optionally be prepared automatically by Npgsql based on use, unlocking prepared statement performance for O/RMs and data layers which don't prepare themselves, such as Dapper or Entity Framework Core ([#1237](https://github.com/npgsql/npgsql/issues/1237)). See [this blog post for more info](http://www.roji.org/prepared-statements-in-npgsql-3-2). -* The internal I/O system has been overhauled to continue supporting sync and async I/O, but with a vastly better coding model. This should eliminate most protocol sync bugs, and make it much easier to maintain and write new type handlers ([#1326](https://github.com/npgsql/npgsql/issues/1326)). -* Kerberos login ("integrated security") is now support on Linux/Mac ([#1079](https://github.com/npgsql/npgsql/issues/1079)). -* Support for System.Transactions and distributed transactions has been rewritten, and should have fewer problems than before ([#122](https://github.com/npgsql/npgsql/issues/122)). -* Performance counters have been implemented, [similar to what SqlClient provides](https://msdn.microsoft.com/library/ms254503(v=vs.110).aspx). ([#619](https://github.com/npgsql/npgsql/issues/619)). -* The Visual Studio integration extension (DDEX) has been rewritten for a much better installation experience, and includes some new features as well ([#1407](https://github.com/npgsql/npgsql/issues/1407)). -* If your application attempts to make use of more than one connection at the same time, an "operation already in progress" was thrown. This exception now provides more information to help you track down the bug ([#1248](https://github.com/npgsql/npgsql/issues/1248)). - -Many other small changes have been made, especially with regards to performance. [Here's the full list](https://github.com/npgsql/npgsql/milestone/24?closed=1). - -## Breaking Changes from 3.1 - -* Connections can no longer be constructed with `NpgsqlConnectionStringBuilder` - only plain string connection strings are supported ([#1415](https://github.com/npgsql/npgsql/issues/1415)). -* The `Buffer Size` connection string parameter has been replaced by `Read Buffer Size` and `Write Buffer Size`. - -## Contributors - -Thank you very much to the following people who have contributed to the individual 3.2.x. releases. - -### [Milestone 3.2.7](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.7) - -Contributor | Assigned issues ------------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.7+is%3Aclosed+assignee%3Aroji) -[@erwaller](https://github.com/erwaller) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.7+is%3Aclosed+assignee%3Aerwaller) - -### [Milestone 3.2.6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.6) - -Contributor | Assigned issues ------------------------------------------------------- |-----------------:| -[@roji](https://github.com/roji) | [8](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.6+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.2.5](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.5) - -Contributor | Assigned issues ------------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.5+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.2.4.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.4.1) - -Contributor | Assigned issues ------------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.4.1+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.2.4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.4) - -Contributor | Assigned issues ------------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.4+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.2.3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.3) - -Contributor | Assigned issues ------------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [9](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.3+is%3Aclosed+assignee%3Aroji) -[@funny-falcon](https://github.com/funny-falcon) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.3+is%3Aclosed+assignee%3Afunny-falcon) -[@jlareo](https://github.com/jlareo) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.3+is%3Aclosed+assignee%3Ajlareo) -[@odiernod](https://github.com/odiernod) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.3+is%3Aclosed+assignee%3Aodiernod) - -### [Milestone 3.2.2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.2) - -Contributor | Assigned issues ------------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [11](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.2+is%3Aclosed+assignee%3Aroji) -[@kurtschelfthout](https://github.com/kurtschelfthout) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.2+is%3Aclosed+assignee%3Akurtschelfthout) -[@Emill](https://github.com/Emill) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.2+is%3Aclosed+assignee%3AEmill) - -### [Milestone 3.2.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.1) - -Contributor | Assigned issues ------------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [7](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2.1+is%3Aclosed+assignee%3Aroji) - -### [Milestone 3.2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2) - -Contributor | Assigned issues ------------------------------------------------------- | ---------------:| -[@roji](https://github.com/roji) | [33](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A3.2+is%3Aclosed+assignee%3Aroji) diff --git a/conceptual/Npgsql/release-notes/4.0.md b/conceptual/Npgsql/release-notes/4.0.md deleted file mode 100644 index 150b71b5..00000000 --- a/conceptual/Npgsql/release-notes/4.0.md +++ /dev/null @@ -1,195 +0,0 @@ -# Npgsql 4.0 Release Notes - -Npgsql 4.0 is out and available at nuget.org. This is a major version with significant changes, upgrade with care, consult the breaking changes section below and test well before deploying to production. - -A special thanks goes out to @YohDeadfall for his many contributions and reviews. Thanks also (alphabetically) to @austindrenski, @Brar, @kspeakman, @rwasef1830, @shortspider, @StillLearnin, @uhayat for their valuable contributions. - -## High performance - -A concentrated effort has substantially increased Npgsql performance, especially in highly concurrent, low-latency scenarios. Improvements include: - -* Rewriting of the connection pool to be lock-free, since contention started to be an issue in highly concurrent, short-lived connection scenarios ([#1839](https://github.com/npgsql/npgsql/issues/1839)). -* Significant reduction of allocations through more recycling and other techniques. -* New API for generically providing parameters, avoiding boxing of value types ([#1639](https://github.com/npgsql/npgsql/issues/1639)). -* Avoiding numerous internal async calls where they weren't needed. -* ... many others - -In round 16 of the TechEmpower benchmark, .NET Core/ASP.NET Core [came in 7th place running with Npgsql](https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=fortune), making it one of the fastest mainstream web stacks available - see [this blog post for more info](http://www.roji.org/npgsql-4-perf). Please let us know how the new version works for you - both positive and negative comments are welcome. - -If you're interested in Npgsql performance and haven't yet seen [the performance page](../performance.md), it's a good opportunity to check it out (it's valid also for 3.2 users). - -## Improved spatial support (PostGIS) - -Previous versions have allowed basic usage of PostGIS's spatial types via built-in Npgsql types, which were limited in many ways. Thanks to a new plugin infrastructure, you can now use the [Npgsql.NetTopologySuite](../types/nts.md) plugin, which maps PostGIS types to the [NetTopologySuite](https://github.com/NetTopologySuite/NetTopologySuite) spatial library's types. NetTopologySuite's types are more complete, and support a variety of spatial operations and conversions you can perform after loading your spatial data from PostgreSQL. - -If you prefer to use JSON for your spatial types, the [Npgsql.GeoJSON](../types/geojson.md) plugin maps PostGIS types to [GeoJSON.NET types](https://github.com/GeoJSON-Net/GeoJSON.Net). GeoJSON is a standard JSON format for spatial data. - -Finally, if you prefer to use the previous Npgsql types (e.g. `PostgisPoint`), these are available via the Npgsql.LegacyPostgis plugin. - -Thanks to @YohDeadfall for implementing both the NetTopologySuite and GeoJSON plugins. - -## NodaTime date/time support - -[NodaTime](https://nodatime.org) is a powerful alternative to .NET's built-in date/time types, such as `DateTime`. The built-in types are flawed in many ways: they have problematic support for timezones, don't have a date-only or time-only types, and promote problematic programming but not making the right distinctions. If your application handles dates and times in anything but the most basic way, you should seriously consider using NodaTime. To learn more read [this blog post by Jon Skeet](https://blog.nodatime.org/2011/08/what-wrong-with-datetime-anyway.html). - -You can now use the new [Npgsql.NodaTime](../types/nodatime.md) to have Npgsql map PostgreSQL date/time types to NodaTime types. - -## Json.NET - -Another plugin, [Npgsql.Json.NET](../types/json.md), works with [Newtonsoft Json.NET](https://www.newtonsoft.com/json) to automatically serialize and deserialize PostgreSQL's `jsonb` and `json` types to your objects, providing a seamless database JSON programming experience. Instead of working with strings which you have to serialize and deserialize, Npgsql does it for you. - -## Other improvements - -* Fix the binary COPY API to make it interact better with exceptions ([#1646](https://github.com/npgsql/npgsql/issues/1646)). -* Npgsql better supports working with enums and composites, even without mapping them, and better supports new types introduced via plugins ([#1792](https://github.com/npgsql/npgsql/issues/1792)). -* Better "reflection" capabilities. Continuing work from 3.2, Npgsql now exposes more information about PostgreSQL types, allowing you to dynamically reflect on columns types returned by queries, or required as parameters ([#1276](https://github.com/npgsql/npgsql/issues/1276), [#1779](https://github.com/npgsql/npgsql/issues/1779)). -* Derive parameters for queries. You can now also use `NpgsqlCommandBuilder` to dynamically understand which parameters and types are required for arbitrary queries (previously supported only for functions) ([#1698](https://github.com/npgsql/npgsql/pull/1698), thanks @Brar!). -* Allow reading a single character from a PostgreSQL text column ([#1188](https://github.com/npgsql/npgsql/issues/1188)). -* Decimals read from PostgreSQL will now have the correct scale ([#1925](https://github.com/npgsql/npgsql/pull/1925)). Thanks @StillLearnin and @YohDeadfall. - -In addition to more documentation, several blog posts are planned to explain the above in more details (to be announced on [@shayrojansky](https://twitter.com/shayrojansky)). - -## Breaking changes from 3.2 - -> [!CAUTION] -> The date/time behavior has changed in the following ways: -> -> 1. `DateTime` is *always* sent as `timestamp` by default, regardless of its kind. You can still specify `NpgsqlDbType.TimestampTz`, in which case local `DateTime` gets converted to UTC before sending. -> 2. When reading `timestamptz` as a `DateTimeOffset`, the machine local offset will be used. Previously a `DateTimeOffset` in UTC was returned. -> 3. It is no longer possible to read or write `DateTimeOffset` as `timestamp`, only as `timestamptz`. - -> [!CAUTION] -> The API for binary import (COPY IN) has changed substantially in a breaking way, and code from 3.2 will *not* work as-is on 4.0. -> -> You must now call `NpgsqlBinaryImporter.Complete()` to save your imported data; not doing so will roll the operation back. `NpgsqlBinaryImporter.Cancel()` has been removed - simply closing/disposing the importer will implicitly cancel the import. This is similar to how `TransactionScope` works and is necessary to prevent accidental commit of data on exception. See [#1646](https://github.com/npgsql/npgsql/issues/1646). - -> [!CAUTION] -> If you're using decimal/numeric numbers (not floating-point), there's a chance your data needs to be fixed (previous versions incorrectly inserted a scale larger than 28, which is the maximum allowed by .NET `decimal`). If you're having trouble reading data previously inserted by Npgsql, consider running [this fixup code](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/438#issuecomment-394014075). If your data really does contain more than 28/29 fractional digits and you need to keep that precision, see [the workarounds proposed in this comment](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/438#issuecomment-393917327) for loading these values. - -* .NET Standard 1.3 is no longer supported. .NET Standard 2.0 is the lowest supported version. -* Npgsql used to use its own internal TLS/SSL due to issues with some server. As these issues have been resolved, the standard .NET SslStream is now used by default ([#1482](https://github.com/npgsql/npgsql/issues/1482)), but you can still set `Use SSL Stream=false` to keep using the internal implementation (please report why you need this, as it's likely the internal implementation will be removed in a future release). -* The reader instances returned by `NpgsqlCommand.ExecuteReader()` are now recycled, to reduce memory allocations ([#1649](https://github.com/npgsql/npgsql/issues/1649)). You should not keep a reference or interact with a reader after its command has been disposed (such interaction was limited in any case). -* The `Min Pool Size` parameter will no longer make the pool create new connections internally - it will only have an effect on how many connections are pruned. Previously, in various points the pool would check if the current number of connections was below `Min Pool Size`, and if so, automatically created new ones - this no longer happens. -* Parameter types have become more strict. Previous versions allowed to you pass arbitrary value types, such as writing CLR string to int columns, or anything that implemented IConvertible. Although some implicit conversions are still supported (e.g. long -> int, short -> int), some have been removed. -* Data type names returned from `NpgsqlDataReader.GetDataTypeName()` and other APIs are now more standards-conforming (e.g. `integer[]` instead of `_int4`), and properly include type modifiers (e.g. `character varying(10)`) ([#1919](https://github.com/npgsql/npgsql/issues/1919)). -* `NpgsqlParameter.EnumType` and `NpgsqlParameter.SpecificType` have been removed. See [Composites and Enums](../types/enums_and_composites.md) for more details. -* Parameter names are no longer trimmed, set your names to the exact parameter name specified in your SQL. -* If a parameter's name isn't set, it will no longer default to Parameter1, Parameter2, etc. -* The following APIs "connection capability" APIs have been removed from NpgsqlConnection: `UseConformantStrings`, `SupportsEStringPrefix`, `UseSslStream`. -* The default name translator, `NpgsqlSnakeCaseNameTranslator`, has been changed to handle acronyms better. Given the property name `IsJSON`, the old translator algorithm would output `is_j_s_o_n`, while the new outputs `is_json`. To revert back to the old algorithm, create a `NpgsqlSnakeCaseNameTranslator` instance with `legacyMode: true` and pass it when calling the `MapComposite` and `MapEnum` methods. -* If you are reading tables as composites ([#990](https://github.com/npgsql/npgsql/issues/990)), you will have to add the new `Load Table Composites` to your connection string. -* `NpgsqlConnection.GetSchema()` will no longer return system tables (i.e. tables in schemas `pg_catalog` and `information_schema`), [#1831](https://github.com/npgsql/npgsql/issues/1831). -* You may no longer have multiple streams or text readers open on a reader (this was previously supported with non-sequential readers). Accessing a new column closes any open stream or text reader. -* The `DateTimeOffset` instances returned for PostgreSQL `timetz` now have their date set to 0001-01-02 instead of the previous 0001-01-01 ([#1924](https://github.com/npgsql/npgsql/pull/1924)). - -## Contributors - -Thank you very much to the following people who have contributed to the individual 4.0.x. releases. - -### [Milestone 4.0.11](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.0.11) - -| Contributor | Assigned issues | -| ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------:| -| [@manandre](https://github.com/manandre) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.0.11+is%3Aclosed+assignee%3Amanandre) | -| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.0.11+is%3Aclosed+assignee%3Aroji) | -| [@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.0.11+is%3Aclosed+assignee%3AYohDeadfall) | - -### [Milestone 4.0.10](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.0.10) - -| Contributor | Assigned issues | -| ---------------------------------- | ---------------------------------------------------------------------------------------------------------:| -| [@kYann](https://github.com/kYann) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.0.10+is%3Aclosed+assignee%3AkYann) | -| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.0.10+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 4.0.9](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.9) - -Contributor | Assigned issues ------------------------------------------------ | ----------------:| -[@roji](https://github.com/roji) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.9+is%3Aclosed+assignee%3Aroji) -[@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.9+is%3Aclosed+assignee%3AYohDeadfall) - -### [Milestone 4.0.8](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.8) - -Contributor | Assigned issues ------------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.8+is%3Aclosed+assignee%3Aroji) -[@romanov-is-here](https://github.com/romanov-is-here) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.8+is%3Aclosed+assignee%3Aromanov-is-here) -[@thetranman](https://github.com/thetranman) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.8+is%3Aclosed+assignee%3Athetranman) -[@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.8+is%3Aclosed+assignee%3AYohDeadfall) - -### [Milestone 4.0.7](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.7) - -Contributor | Assigned issues ------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.7+is%3Aclosed+assignee%3Aroji) -[@aspaw](https://github.com/aspaw) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.7+is%3Aclosed+assignee%3Aaspaw) - -### [Milestone 4.0.6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.6) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.6+is%3Aclosed+assignee%3Aroji) -[@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.6+is%3Aclosed+assignee%3Aaustindrenski) -[@zabulus](https://github.com/zabulus) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.6+is%3Aclosed+assignee%3Azabulus) - -### [Milestone 4.0.5](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.5) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.5+is%3Aclosed+assignee%3Aroji) -[@YohDeadfall](https://github.com/YohDeadfall) | [5](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.5+is%3Aclosed+assignee%3AYohDeadfall) -[@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.5+is%3Aclosed+assignee%3Aaustindrenski) - -### [Milestone 4.0.4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.4) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.4+is%3Aclosed+assignee%3Aroji) -[@YohDeadfall](https://github.com/YohDeadfall) | [3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.4+is%3Aclosed+assignee%3AYohDeadfall) -[@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.4+is%3Aclosed+assignee%3Aaustindrenski) - -### [Milestone 4.0.3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.3) - -Contributor | Assigned issues ------------------------------------------------ | ----------------:| -[@roji](https://github.com/roji) | [6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.3+is%3Aclosed+assignee%3Aroji) -[@YohDeadfall](https://github.com/YohDeadfall) | [3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.3+is%3Aclosed+assignee%3AYohDeadfall) - -### [Milestone 4.0.2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.2) - -Contributor | Assigned issues | ----------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -[@roji](https://github.com/roji) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.2+is%3Aclosed+assignee%3Aroji) | -[@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.2+is%3Aclosed+assignee%3AYohDeadfall) | - -### [Milestone 4.0.11](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.11) - -Contributor | Assigned issues | ----------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -[@manandre](https://github.com/manandre) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.11+is%3Aclosed+assignee%3Amanandre) | -[@roji](https://github.com/roji) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.11+is%3Aclosed+assignee%3Aroji) | -[@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.11+is%3Aclosed+assignee%3AYohDeadfall) | - -### [Milestone 4.0.10](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.10) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@kYann](https://github.com/kYann) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.10+is%3Aclosed+assignee%3AkYann) -[@roji](https://github.com/roji) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.10+is%3Aclosed+assignee%3Aroji) - -### [Milestone 4.0.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.1) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.1+is%3Aclosed+assignee%3Aroji) -[@austindrenski](https://github.com/austindrenski) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.1+is%3Aclosed+assignee%3Aaustindrenski) -[@YohDeadfall](https://github.com/YohDeadfall) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0.1+is%3Aclosed+assignee%3AYohDeadfall) - -### [Milestone 4.0](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0) - -Contributor | Assigned issues --------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [34](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0+is%3Aclosed+assignee%3Aroji) -[@YohDeadfall](https://github.com/YohDeadfall) | [6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0+is%3Aclosed+assignee%3AYohDeadfall) -[@Brar](https://github.com/Brar) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0+is%3Aclosed+assignee%3ABrar) -[@funny-falcon](https://github.com/funny-falcon) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.0+is%3Aclosed+assignee%3Afunny-falcon) diff --git a/conceptual/Npgsql/release-notes/4.1.md b/conceptual/Npgsql/release-notes/4.1.md deleted file mode 100644 index bd8971ed..00000000 --- a/conceptual/Npgsql/release-notes/4.1.md +++ /dev/null @@ -1,121 +0,0 @@ -# Npgsql 4.1 Release Notes - -Npgsql 4.1 is out and available at nuget.org. - -## New Features - -The major new features of 4.1 are: - -* Support for reading and writing your types as JSON via the new, high-perf System.Text.Json API ([#2306](https://github.com/npgsql/npgsql/issues/2306)). -* Support for the new async methods introduced in .NET Standard 2.1 ([#2481](https://github.com/npgsql/npgsql/issues/2481)). -* Expose performance statistics via [the new .NET event counters](https://devblogs.microsoft.com/dotnet/introducing-diagnostics-improvements-in-net-core-3-0/) ([#1725](https://github.com/npgsql/npgsql/issues/1725)). -* Async support for binary imports and exports ([#1632](https://github.com/npgsql/npgsql/issues/1632)). -* Easier and PostgreSQL standard ways to provide client certificates for authentication ([#2129](https://github.com/npgsql/npgsql/issues/2129)). - -Many other small improvements and performance optimizations have been introduced as well - you can track progress [here](https://github.com/npgsql/npgsql/issues?utf8=%E2%9C%93&q=milestone%3A4.1.0). - -## Breaking changes from 4.0 - -* .NET Framework 4.5, 4.5.1 and 4.5.2 are no longer supported. .NET Framework 4.6.1 and .NET Standard 2.0 are the lowest supported versions. -* The spatial plugin, Npgsql.NetTopologySuite, has been updated to depend on NetTopologySuite 2.0.0, which is a major version introducing breaking changes. Specifically, EF Core 3.0 is the first version supporting NetTopologySuite 2.0.0; it is not possible to use EF Core 2.x with the new version of Npgsql.NetTopologySuite. -* The `UseSslStream` property of `NpgsqlConnectionStringBuilder` is now marked as `Obselete`. `SslStream` is always used. -* A fix was done to Npgsql's snake case naming converter ([#2152](https://github.com/npgsql/npgsql/issues/2152)); this could break code that relies on the previous conversion logic. - -## Contributors - -Thank you very much to the following people who have contributed to the individual 4.1.x. releases. - -### [Milestone 4.1.12](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.12) - -| Contributor | Assigned issues | -| -------------------------------- | --------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.12+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 4.1.9](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.9) - -| Contributor | Assigned issues -| ---------------------------------------------- | ---------------:| -| [@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.9+is%3Aclosed+assignee%3AYohDeadfall) - -### [Milestone 4.1.8](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.8) - -| Contributor | Assigned issues -| ---------------------------------------------- | ---------------:| -| [@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.8+is%3Aclosed+assignee%3AYohDeadfall) - -### [Milestone 4.1.7](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.7) - -| Contributor | Assigned issues -| ---------------------------------------------- | ---------------:| -| [@YohDeadfall](https://github.com/YohDeadfall) | [3](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.7+is%3Aclosed+assignee%3AYohDeadfall) -| [@vonzshik](https://github.com/vonzshik) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.7+is%3Aclosed+assignee%3Avonzshik) - -### [Milestone 4.1.6](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.6) - -| Contributor | Assigned issues -| ---------------------------------------------- | ---------------:| -| [@loop-evgeny](https://github.com/loop-evgeny) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.6+is%3Aclosed+assignee%3Aloop-evgeny) -| [@mm3141](https://github.com/mm3141) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.6+is%3Aclosed+assignee%3Amm3141) -| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.6+is%3Aclosed+assignee%3Aroji) -| [@vonzshik](https://github.com/vonzshik) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.6+is%3Aclosed+assignee%3Avonzshik) -| [@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.6+is%3Aclosed+assignee%3AYohDeadfall) - -### [Milestone 4.1.5](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A4.1.5) - -Contributor | Assigned issues ------------------------------------------------------- |----------------:| -[@calexander3](https://github.com/calexander3) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.5+is%3Aclosed+assignee%3Acalexander3) -[@roji](https://github.com/roji) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.5+is%3Aclosed+assignee%3Aroji) -[@romanov-is-here](https://github.com/romanov-is-here) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.5+is%3Aclosed+assignee%3Aromanov-is-here) -[@vonzshik](https://github.com/vonzshik) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.5+is%3Aclosed+assignee%3Avonzshik) -[@warcha](https://github.com/warcha) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.5+is%3Aclosed+assignee%3Awarcha) -[@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.5+is%3Aclosed+assignee%3AYohDeadfall) - -### [Milestone 4.1.4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.4) - -Contributor | Assigned issues ---------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.4+is%3Aclosed+assignee%3Aroji) -[@YohDeadfall](https://github.com/YohDeadfall) | [6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.4+is%3Aclosed+assignee%3AYohDeadfall) -[@warcha](https://github.com/warcha) | [3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.4+is%3Aclosed+assignee%3Awarcha) -[@dwat001](https://github.com/dwat001) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.4+is%3Aclosed+assignee%3Adwat001) -[@elipatov](https://github.com/elipatov) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.4+is%3Aclosed+assignee%3Aelipatov) -[@manandre](https://github.com/manandre) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.4+is%3Aclosed+assignee%3Amanandre) -[@williamdenton](https://github.com/williamdenton) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.4+is%3Aclosed+assignee%3Awilliamdenton) - -### [Milestone 4.1.3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.3) - -Contributor | Assigned issues ---------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [5](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.3+is%3Aclosed+assignee%3Aroji) -[@YohDeadfall](https://github.com/YohDeadfall) | [4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.3+is%3Aclosed+assignee%3AYohDeadfall) -[@NinoFloris](https://github.com/NinoFloris) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.3+is%3Aclosed+assignee%3ANinoFloris) -[@nycdotnet](https://github.com/nycdotnet) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.3+is%3Aclosed+assignee%3Anycdotnet) - -### [Milestone 4.1.2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.2) - -Contributor | Assigned issues ---------------------------------------------------- | ----------------:| -[@YohDeadfall](https://github.com/YohDeadfall) | [4](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.2+is%3Aclosed+assignee%3AYohDeadfall) -[@NinoFloris](https://github.com/NinoFloris) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.2+is%3Aclosed+assignee%3ANinoFloris) -[@austindrenski](https://github.com/austindrenski) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.2+is%3Aclosed+assignee%3Aaustindrenski) - -### [Milestone 4.1.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.1) - -Contributor | Assigned issues ---------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [7](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.1+is%3Aclosed+assignee%3Aroji) - -### [Milestone 4.1.0](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.0) - -Contributor | Assigned issues ---------------------------------------------------- | ----------------:| -[@roji](https://github.com/roji) | [27](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.0+is%3Aclosed+assignee%3Aroji) -[@YohDeadfall](https://github.com/YohDeadfall) | [6](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.0+is%3Aclosed+assignee%3AYohDeadfall) -[@austindrenski](https://github.com/austindrenski) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.0+is%3Aclosed+assignee%3Aaustindrenski) -[@NinoFloris](https://github.com/NinoFloris) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.0+is%3Aclosed+assignee%3ANinoFloris) -[@afkos](https://github.com/afkos) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.0+is%3Aclosed+assignee%3Aafkos) -[@baronfel](https://github.com/baronfel) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.0+is%3Aclosed+assignee%3Abaronfel) -[@shortspider](https://github.com/shortspider) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.0+is%3Aclosed+assignee%3Ashortspider) -[@williamdenton](https://github.com/williamdenton) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.0+is%3Aclosed+assignee%3Awilliamdenton) -[@zabulus](https://github.com/zabulus) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A4.1.0+is%3Aclosed+assignee%3Azabulus) diff --git a/conceptual/Npgsql/release-notes/5.0.md b/conceptual/Npgsql/release-notes/5.0.md deleted file mode 100644 index 6a08c360..00000000 --- a/conceptual/Npgsql/release-notes/5.0.md +++ /dev/null @@ -1,181 +0,0 @@ -# Npgsql 5.0 Release Notes - -Npgsql 5.0 is out and available at nuget.org. - -## New features - -The full list of issues for this release is [available here](https://github.com/npgsql/efcore.pg/milestone/24?closed=1). - -### PostgreSQL logical and physical replication - -PostgreSQL replication creating programs which receive a continuous, live stream of all updates happening in a PostgreSQL database or set of tables. It can be used for auditing purposes, continuously exporting certain (or all) changes to another database or format, or various other purposes. [See the documentation for more details](../replication.md). - -This major feature was developed by [@Brar](https://github.com/Brar), many thanks! - -Issue: [#1520](https://github.com/npgsql/npgsql/issues/1520) - -### Improved support for cancellation and timeout - -When the user requests cancellation (via a cancellation token or ), or when the [Command Timeout](http://www.npgsql.org/doc/connection-string-parameters.html#timeouts-and-keepalive) expires, Npgsql now takes the following steps: - -1. Contact PostgreSQL and attempt to cancel the running command. If successful, PostgreSQL immediately stops processing the command and is free to do other work. In previous versions, queries were sometimes left running on the server. -2. If PostgreSQL cancellation isn't successful within a short time window, the network is likely down. Npgsql forcibly closes the physical connection and raises an exception, making sure the application isn't blocked. - -Previous support was inconsistent across cancellation and timeout, and async I/O was only partially supported. - -Thanks to [@vonzshik](https://github.com/vonzshik) for all their valuable work on this! - -Issue: [#3166](https://github.com/npgsql/npgsql/issues/3166) - -### Connection multiplexing - -Multiplexing is an experimental new way for the driver to handle commands and connections: user code no longer receives an exclusive physical connection from Npgsql's internal pool, but rather submits commands to be executed on any available connection. This is a much more efficient use of connections, which can lead to: - -1. Significant reduction to the number of required PostgreSQL physical connection requirements, and removing load from the server. -2. Continued uptime even when the maximum allowed connection count has been reached. -3. A potentially substantial performance boost on the [TechEmpower benchmark](https://www.techempower.com/benchmarks/) (next round to be published). - -Multiplexing is disabled by default, is considered experimental and must be explicitly opted into. Full documentation will be available soon. - -Issue: [#1982](https://github.com/npgsql/npgsql/issues/1982) - -### Nullable references - -All Npgsql APIs are now fully annotated for *C# nullable references* ([#3120](https://github.com/npgsql/npgsql/issues/3120)), in line with the new annotations in System.Data released in .NET 5.0. - -### Support for arrays of nullable value types - -It is now possible to read PostgreSQL arrays as CLR *arrays of nullable value types*. For example, a PostgreSQL `integer[]` column can now be read as follows: - -```csharp -var array = reader.GetFieldValue(0); -``` - -Previously, only non-nullable value arrays were supported, and nulls were translated to the default value (e.g. 0). - -Thanks to [@Brar](https://github.com/Brar) for developing this feature. - -Issue: [#443](https://github.com/npgsql/npgsql/issues/443) - -### Close connections past a certain age - -The `Connection Lifetime` connection string parameter can now be used to unconditionally close connections which have reached a certain age. Once such a connection is returned to the pool, it is destroyed and a new connection will be created if needed. This is useful in clustered configurations to force load balancing between a running server and a server just brought online, or to mitigate certain resource leaks. - -Thanks to [@FlorianRainer](https://github.com/FlorianRainer) for collaborating on this feature. - -Issue: [#1810](https://github.com/npgsql/npgsql/issues/1810) - -## Breaking changes - -* Npgsql no longer targets .NET Framework 4.6.1. Since .NET Standard 2.0 is targeted, it is still possible to use Npgsql from .NET Framework applications; however, we no longer run regression tests on .NET Framework and will only fix bugs on a best-effort basis. In addition, the Visual Studio extension (VSIX) and the MSI GAC installer have been discontinued. [#3269](https://github.com/npgsql/npgsql/issues/3269). -* Npgsql targets the `netcoreapp3.1` TFM instead of `netcoreapp3.0`, which is out of support ([#3160](https://github.com/npgsql/npgsql/issues/3160)). -* When command timeout occurs, Npgsql now raises an wrapping a [TimeoutException](https://docs.microsoft.com/dotnet/api/system.timeoutexception) ([#3132](https://github.com/npgsql/npgsql/issues/3132)). Previously, an NpgsqlException wrapping an IOException was raised. -* Similarly, when cancellation occurs, Npgsql now raises an [OperationCanceledException](https://docs.microsoft.com/dotnet/api/system.operationcanceledexception) when a command is cancelled (both via an async cancellation token, and via ). Previously, NpgsqlCommand.Cancel caused a to be raised instead. -* When reading PostgreSQL arrays, if a null value is being read into a CLR arrays of a non-nullable value type, an exception is now thrown ([#443](https://github.com/npgsql/npgsql/issues/443)). Previously, the default value was populated instead. It is now possible to read arrays of nullable value types instead. -* The `NpgsqlTransaction.IsCompleted` property has been removed. The application must itself track when a transaction is committed or rolled back. -* Support for unmapped PostgreSQL composite types has been removed ([#2403](https://github.com/npgsql/npgsql/issues/2403)). -* The ordering in which Npgsql checks alternative password sources has changed ([#2695](https://github.com/npgsql/npgsql/issues/2695), [#2657](https://github.com/npgsql/npgsql/pull/2657)). This only affects applications which omit the password from the connection string. -* If the connection string specifies a PGPASS file, Npgsql now throws if that file doesn't exist ([#2694](https://github.com/npgsql/npgsql/issues/2694)). -* The *TcpKeepAliveTime* and *TcpKeepAliveInterval* connection string parameters are now expressed in seconds instead of milliseconds ([#1936](https://github.com/npgsql/npgsql/issues/1936)). -* The API now returns all indexes in the database ([2958](https://github.com/npgsql/npgsql/issues/2958)). Previously, only indexes in the `search_path` were returned. -* now inherits from . -* has been changed to return a `ulong` reporting the number of imported rows ([#2112](https://github.com/npgsql/npgsql/issues/2112)). -* The [Npgsql.RawPostgis](https://www.nuget.org/packages/Npgsql.RawPostgis/) plugin has been discontinued ([#3201](https://github.com/npgsql/npgsql/issues/3201)). Npgsql now allows any field to be read as raw binary data, so the plugin is no longer necessary. -* ~Support for non-standard-conforming strings has been dropped ([#2931](https://github.com/npgsql/npgsql/issues/2931)).~ Support for non-standard-confirming strings has been restored in 5.0.1 (except for multiplexing). -* Npgsql no longer supports SASL authentication with PgBouncer below 1.12. - -## Contributors - -Thank you very much to the following people who have contributed to the individual 5.0.x. releases. - -### [Milestone 5.0.14](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.14) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@vonzshik](https://github.com/vonzshik) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.14+is%3Aclosed+assignee%3Avonzshik) | - -### [Milestone 5.0.11](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.11) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@vonzshik](https://github.com/vonzshik) | [4](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.11+is%3Aclosed+assignee%3Avonzshik) | -| [@aromaa](https://github.com/aromaa) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.11+is%3Aclosed+assignee%3Aaromaa) | -| [@kislovs](https://github.com/kislovs) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.11+is%3Aclosed+assignee%3Akislovs) | -| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.11+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 5.0.10](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.10) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@vonzshik](https://github.com/vonzshik) | [11](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.10+is%3Aclosed+assignee%3Avonzshik) | -| [@roji](https://github.com/roji) | [5](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.10+is%3Aclosed+assignee%3Aroji) | -| [@Brar](https://github.com/Brar) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.10+is%3Aclosed+assignee%3ABrar) | - -### [Milestone 5.0.7](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.7) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@vonzshik](https://github.com/vonzshik) | [8](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.7+is%3Aclosed+assignee%3Avonzshik) | -| [@roji](https://github.com/roji) | [4](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.7+is%3Aclosed+assignee%3Aroji) | -| [@Brar](https://github.com/Brar) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.7+is%3Aclosed+assignee%3ABrar) | -| [@chrisdcmoore](https://github.com/chrisdcmoore) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.7+is%3Aclosed+assignee%3Achrisdcmoore) | - -### [Milestone 5.0.5](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.5) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@vonzshik](https://github.com/vonzshik) | [6](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.5+is%3Aclosed+assignee%3Avonzshik) | -| [@roji](https://github.com/roji) | [3](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.5+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 5.0.4](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.4) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@vonzshik](https://github.com/vonzshik) | [5](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.4+is%3Aclosed+assignee%3Avonzshik) | -| [@roji](https://github.com/roji) | [2](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.4+is%3Aclosed+assignee%3Aroji) | -| [@Brar](https://github.com/Brar) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.4+is%3Aclosed+assignee%3ABrar) | -| [@neyromant](https://github.com/neyromant) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.4+is%3Aclosed+assignee%3Aneyromant) | -| [@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.4+is%3Aclosed+assignee%3AYohDeadfall) | - -### [Milestone 5.0.3](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.3) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@baal2000](https://github.com/baal2000) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.3+is%3Aclosed+assignee%3Abaal2000) | -| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.3+is%3Aclosed+assignee%3Aroji) | -| [@vonzshik](https://github.com/vonzshik) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.3+is%3Aclosed+assignee%3Avonzshik) | - -### [Milestone 5.0.2](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.2) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@vonzshik](https://github.com/vonzshik) | [4](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.2+is%3Aclosed+assignee%3Avonzshik) | -| [@roji](https://github.com/roji) | [2](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.2+is%3Aclosed+assignee%3Aroji) | -| [@Brar](https://github.com/Brar) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.2+is%3Aclosed+assignee%3ABrar) | -| [@cime](https://github.com/cime) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.2+is%3Aclosed+assignee%3Acime) | -| [@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.2+is%3Aclosed+assignee%3AYohDeadfall) | - -### [Milestone 5.0.1.1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.1.1) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@vonzshik](https://github.com/vonzshik) | [3](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.1.1+is%3Aclosed+assignee%3Avonzshik) | -| [@roji](https://github.com/roji) | [2](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.1.1+is%3Aclosed+assignee%3Aroji) | -| [@YohDeadfall](https://github.com/YohDeadfall) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.1.1+is%3Aclosed+assignee%3AYohDeadfall) | - -### [Milestone 5.0.0](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A5.0.0) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [34](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Aroji) | -| [@vonzshik](https://github.com/vonzshik) | [19](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Avonzshik) | -| [@YohDeadfall](https://github.com/YohDeadfall) | [16](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3AYohDeadfall) | -| [@Brar](https://github.com/Brar) | [7](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3ABrar) | -| [@warcha](https://github.com/warcha) | [5](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Awarcha) | -| [@manandre](https://github.com/manandre) | [2](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Amanandre) | -| [@ch-asimakopoulos](https://github.com/ch-asimakopoulos) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Ach-asimakopoulos) | -| [@chrisdcmoore](https://github.com/chrisdcmoore) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Achrisdcmoore) | -| [@FlorianRainer](https://github.com/FlorianRainer) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3AFlorianRainer) | -| [@NinoFloris](https://github.com/NinoFloris) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3ANinoFloris) | -| [@russellfoster](https://github.com/russellfoster) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3Arussellfoster) | -| [@TwentyFourMinutes](https://github.com/TwentyFourMinutes) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A5.0.0+is%3Aclosed+assignee%3ATwentyFourMinutes) | diff --git a/conceptual/Npgsql/release-notes/6.0.md b/conceptual/Npgsql/release-notes/6.0.md deleted file mode 100644 index 3caa3bd8..00000000 --- a/conceptual/Npgsql/release-notes/6.0.md +++ /dev/null @@ -1,373 +0,0 @@ -# Npgsql 6.0 Release Notes - -Npgsql version 6.0 has been released and is available on nuget. - -Npgsql 6.0 brings some major breaking changes and is not a simple in-place upgrade. Carefully read the breaking change notes below and upgrade with care. - -## New features - -The full list of issues for this release is [available here](https://github.com/npgsql/npgsql/milestone/71?closed=1). - -### Multiple hosts, load balancing and failover - -Npgsql now includes first-class support for managing connections to multiple PostgreSQL servers, unlocking both load balancing for better performance and failover for better reliability ([#732](https://github.com/npgsql/npgsql/issues/732)). This long-awaited feature is an important part of using PostgreSQL in scalable and mission-critical environments. - -For example, consider the following connection string: - -```connection_string -Host=server1,server2,server3,server4,server5;Username=test;Password=test;Load Balance Hosts=true;Target Session Attributes=prefer-standby -``` - -This will make Npgsql load balance connections across 5 different servers, in round-robbin fashion; connections to read-only standby servers is preferred in order to offload as much read-only load from the primary server, but if only the primary server is up it will still be used. - -The multiple hosts feature is highly configurable, [see the full documentation for more details](../failover-and-load-balancing.md). - -### Tracing with OpenTelemetry - -Npgsql can now report tracing data via OpenTelemetry; this can provide invaluable data on the queries your application is running, how long they're taking, and situate them in the larger context of your application. For example, you can visualize what percentage of your HTTP requests are spent waiting for your database query. - -The following is a sample timeline visualization of Npgsql-reported trace data, using [Zipkin](https://zipkin.io/): - -![Zipkin UI Sample](/img/zipkin.png) - -See the full documentation in the [diagnostics page](/doc/diagnostics/tracing.html). - -### Timestamp rationalization and improvements - -Support for `timestamp with time zone` and `timestamp without time zone` has been rationalized and simplified, and aligned with PostgreSQL best practices. In particular, the "UTC everywhere" pattern is much better supported via the PostgreSQL `timestamp with time zone` type, which is the recommended way to handle timestamps. A detailed explanation is available in [this blog post](https://www.roji.org/postgresql-dotnet-timestamp-mapping), below is a summary of the main improvements. - -* UTC timestamps have been cleanly separated from non-UTC timestamps, aligning with the PostgreSQL types. The former are represented by `timestamp with time zone` and DateTime with Kind UTC, the latter by `timestamp without time zone` and DateTime with Kind Local or Unspecified. It is recommended to use UTC timestamps where possible. -* Npgsql no longer performs any implicit timezone conversions when reading or writing any timestamp value - the value in the database is what you get, and the machine timezone no longer plays any role when reading/writing values. -* Npgsql no longer supports date/time representations which cannot be fully round-tripped to the database. If it can't be fully stored as-is, you can't write it. -* A compatibility switch enables opting out of the new behavior, to maintain backwards compatibility. - -This change introduces significant breaking changes (see below), although a compatibility flag can be used to opt out and revert to the previous behavior. - -Other date/time improvements include: - -* Support for the new [.NET DateOnly and TimeOnly types](https://devblogs.microsoft.com/dotnet/date-time-and-time-zone-enhancements-in-net-6/) ([#3616](https://github.com/npgsql/npgsql/issues/3616)). -* PostgreSQL `tstzrange` is now mapped to NodaTime [Interval](https://nodatime.org/3.0.x/api/NodaTime.Interval.html), and PostgreSQL `daterange` is now mapped to NodaTime [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html). Most methods on these types are translated ([#3973](https://github.com/npgsql/npgsql/issues/3973), [#4070](https://github.com/npgsql/npgsql/issues/4070)). -* `DateTime.MinValue` and `MaxValue` are now mapped to PostgreSQL `-infinity` and `infinity` by default. - -### Raw SQL mode and new batching API - -It is now possible to use PostgreSQL positional parameters, allowing Npgsql to skip rewriting your SQL and send it directly to PostgreSQL ([#1042](https://github.com/npgsql/npgsql/issues/1042)): - -```sql -SELECT * FROM blogs WHERE b.name = @p; -- Before Npgsql 6.0 -SELECT * FROM blogs WHERE b.name = $1; -- Npgsql 6.0 -``` - -This is more efficient, is safer (since Npgsql doesn't have to parse SQL), and aligns your SQL with the actual PostgreSQL SQL. Note that named parameters are still supported for backwards compatibility. - -In addition, Npgsql now supports [the new ADO.NET batching API](https://github.com/dotnet/runtime/issues/28633) introduced in .NET 6.0 as an alternative to packing multiple statements into a single NpgsqlCommand, delimited by semicolons ([#3860](https://github.com/npgsql/npgsql/pull/3860)): - -```csharp -// Before Npgsql 6.0 -var command = new NpgsqlCommand("SELECT 1; SELECT 2", connection); -var reader = await command.ExecuteReaderAsync(); - -// Npgsql 6.0 -var batch = new NpgsqlBatch(connection) -{ - BatchCommands = { new("SELECT 1"), new("SELECT 2") } -}; -var reader = await batch.ExecuteReaderAsync(); -``` - -As with positional parameters, this allow Npgsql to avoid parsing and splitting your SQL which is safer and more efficient. - -To learn more about positional parameters and batching, [see this blog post](https://www.roji.org/parameters-batching-and-sql-rewriting). - -### SSL/TLS improvements - -Npgsql 6.0 contains some considerable improvements to encryption support, here are some highlights ([#4006](https://github.com/npgsql/npgsql/issues/4006)): - -* The [`Ssl Mode`](https://www.npgsql.org/doc/connection-string-parameters.html#security-and-encryption) connection string parameter has been aligned with the standard PostgreSQL [`ssl_mode`](https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-SSLMODE-STATEMENTS) setting, and allows for more fine-grained choice in what to validate (see breaking change note below for `SSL Mode=Require`). -* Support has been added for PEM client certificates when running on .NET 5.0 and above. -* Support for specifying a root CA certificate that isn't installed in the machine store. - -See the updated [security and encryption docs](/doc/security.html) for more details. - -### Improved logical replication support - -The recently-released PostgreSQL 14 made significant improvements to logical replication, and Npgsql 6.0 already supports them! Here's a summary of the main changes ([#4050](https://github.com/npgsql/npgsql/issues/4050), thanks @Brar): - -* PG14 binary logical replication - you can now read the standard .NET types from replication data; only text was possible previously ([#4049](https://github.com/npgsql/npgsql/issues/4049)). -* PG14 streaming replication - incremental updates for large in-progress transactions ([#4047](https://github.com/npgsql/npgsql/issues/4047)) -* The replication API now fully streams all data, including even columns; the previous API buffered rows, leading to lots of heap allocations for big rows ([#4068](https://github.com/npgsql/npgsql/issues/4068)). - -Unfortunately, some of the above required an API redesign, leading to some breaking changes. - -### Other new features - -* Support for the new [.NET DateOnly and TimeOnly types](https://devblogs.microsoft.com/dotnet/date-time-and-time-zone-enhancements-in-net-6/) ([#3616](https://github.com/npgsql/npgsql/issues/3616)). -* Full support for the PostgreSQL 14 [multirange type](https://www.postgresql.org/docs/14/rangetypes.html), mapped to arrays or lists of `NpgsqlRange` ([#3868](https://github.com/npgsql/npgsql/issues/3868)). -* PostgreSQL `decimal` can now be mapped to .NET [BigInteger](https://docs.microsoft.com/dotnet/api/system.numerics.biginteger) ([#3665](https://github.com/npgsql/npgsql/issues/3665)). -* Bulk import/export now includes a fully asynchronous API ([#3309](https://github.com/npgsql/npgsql/issues/3309)). -* Improved array nullability via [a new connection string parameter](/doc/connection-string-parameters.html#misc) ([#3386](https://github.com/npgsql/npgsql/issues/3386)). -* Composite types and records can now be read by getting a nested DbDataReader through `NpgsqlDataReader.GetData()` ([#3558](https://github.com/npgsql/npgsql/issues/3558), thanks [@Emill](https://github.com/Emill)). This allows for efficient access without having to map composite types to .NET POCOs. -* Considerable work has gone in to make Npgsql more friendly to trimming/AOT, removing reflection ([#3300](https://github.com/npgsql/npgsql/issues/3300)). Npgsql still isn't fully trimming-friendly, but it's getting close. - -## Breaking changes - -### Changes to SSL configuration (SSL Mode=Require) - -* To validate server certificates, use `SSL Mode=VerifyFull` (or alternatively SSL `VerifyCA`) instead of `Require`. -* To not validate server certificates (e.g. self-signed certificates), use `SSL Mode=Require` and `Trust Server Certificate=true`. - -In previous versions, specifying `SSL Mode=Require` made Npgsql validate the server certificate, but the standard PostgreSQL [`ssl_mode`](https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-SSLMODE-STATEMENTS) setting does not. As part of aligning Npgsql with other PostgreSQL drivers and tools, 6.0 now has `SSL Mode=VerifyFull` which corresponds to the previous `Require` behavior. Stopping validation for `Require` would align Npgsql with the PostgreSQL behavior, but would silently turn off validation for current users and expose them to potential security issues. As a result, we now require `Trust Server Certificate=true` to be specified with `Require`: this forces users to explicitly opt out of validation. In a future version, we'll remove the requirement to specify `Trust Server Certificate` for `Require` (and possibly the parameter itself). - -### Major changes to timestamp mapping - -> [!NOTE] -> It is possible to opt out of these changes to maintain backwards compatibility, see below. - -#### Quick summary - -* In many cases, is makes sense to store UTC timestamps in the database. To do this, migrate your `timestamp without time zone` columns to `timestamp with time zone` ([see migration notes below](#migrating-columns-from-timestamp-to-timestamptz)), and always use either DateTime with Kind=Utc or DateTimeOffset with offset 0. - * If using NodaTime (recommended), use either [Instant](https://nodatime.org/3.0.x/api/NodaTime.Instant.html) or [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html) with time zone UTC. -* To store non-UTC timestamps, use DateTime with Kind=Unspecified. - * If using NodaTime (recommended), use [LocalDateTime](https://nodatime.org/3.0.x/api/NodaTime.LocalDateTime.html) (no explicit column configuration is required). -* If you're using Dapper, use version 2.0.123 or above. Earlier versions will fail when trying to send a UTC DateTime. - -#### Detailed notes - -The below notes will use the PostgreSQL aliases `timestamptz` to refer to `timestamp with time zone`, and `timestamp` to refer to `timestamp without time zone`. Note that `timestamp with time zone` represents a UTC timestamp and does **not** store a timezone in the database. - -* UTC DateTime is now strictly mapped to `timestamptz`, while Local/Unspecified DateTime is now strictly mapped to `timestamp`. - * DateTime with Kind=UTC are now written as PostgreSQL `timestamptz`; previously, DateTime was always written as `timestamp`. - * It is no longer possible to write UTC DateTime as `timestamp`, or Local/Unspecified DateTime as `timestamptz`. This was previously allowed, with Npgsql performing implicit timezone conversions. - * Note that if you write a UTC DateTime to a PostgreSQL `timestamp` column, PostgreSQL will implicitly convert the `timestamptz` value sent by Npgsql, performing a timezone conversion based on the `TimeZone` parameter. -* `timestamptz` values are now read back as DateTime with Kind=UTC, without any conversions; these were previously returned as local DateTime, converted to the local machine's timezone. When reading `timestamptz` values as [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset), UTC values (offset 0) are always returned. -* [DbType.DateTime](https://docs.microsoft.com/dotnet/api/system.data.dbtype#System_Data_DbType_DateTime) now maps to `timestamptz`, not `timestamp`. [DbType.DateTime2](https://docs.microsoft.com/dotnet/api/system.data.dbtype#System_Data_DbType_DateTime2) continues to map to `timestamp`, and [DbType.DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.data.dbtype#System_Data_DbType_DateTimeOffset) continues to map to `timestamptz`, as before. Unless you're writing cross-database applications, consider using [NpgsqlDbType](https://www.npgsql.org/doc/basic-usage.html#parameter-types) instead of `DbType` to specify precise PostgreSQL types, or simply let Npgsql infer the types by not setting either. -* It is no longer possible to write [DateTimeOffset](https://docs.microsoft.com/dotnet/api/system.datetimeoffset) with offsets other than 0 (UTC), since these cannot be represented in PostgreSQL. These were previously implicitly converted to UTC before sending. -* It is no longer possible to read or write `timetz` as DateTime or TimeSpan, as these don't have a timezone. This was previously allowed, with the offset being stripped. - -See the [EF Core provider docs](/efcore/release-notes/6.0.html) for additional changes at the EF level. - -#### NodaTime changes - -* [Instant](https://nodatime.org/3.0.x/api/NodaTime.Instant.html) is now sent as a `timestamptz` value, and not as a `timestamp`, since they represent a universally agreed-upon point in time. To send a `timestamp`, use [LocalDateTime](https://nodatime.org/3.0.x/api/NodaTime.LocalDateTime.html). -* When reading `timestamptz` as [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html) or [OffsetDateTime](https://nodatime.org/3.0.x/api/NodaTime.OffsetDateTime.html), UTC values are always returned. Previously, local values based on the PostgreSQL `TimeZone` parameter were returned. - -> [!NOTE] -> In most cases, storing UTC timestamps is the recommended practice. If this is what you're doing, it's strongly recommended to migrate all relevant columns from `timestamp` columns to `timestamptz`. See below for how to do this. - -#### Migrating columns from timestamp to timestamptz - -Migrating `timestamp` columns to `timestamptz` is a simple procedure, but care must be taken, depending on the current contents of your column. - -As a starting point, let's assume your existing `timestamp` column has the timestamp `2020-01-01 12:00:00`: - -```sql -SELECT "created_on", pg_typeof("created_on") AS type FROM "Blogs"; -``` - -Results in: - -```output - created_on | type ----------------------+----------------------------- - 2020-01-01 12:00:00 | timestamp without time zone -``` - -The following SQL will change the column's type to `timestamptz`: - -```sql -ALTER TABLE blogs ALTER COLUMN created_on TYPE timestamp with time zone; -``` - -When converting the `timestamp without time zone` column to `timestamp with time zone`, PostgreSQL will assume that existing values are local timestamps, and will convert them to UTC based on the `TimeZone` parameter. Performing the above query will result in something like: - -```output - CreatedOn | type -------------------------+-------------------------- - 2020-01-01 12:00:00+02 | timestamp with time zone -``` - -This means that your new `timestamptz` column now contains 10:00 UTC, which is probably not what you want: if the original values were in fact UTC values, you need them to be preserved as-is, changing only the column type. To do this, set `TimeZone` to `UTC` before executing the `ALTER TABLE`: - -```sql -SET TimeZone='UTC'; -ALTER TABLE blogs ALTER COLUMN created_on TYPE timestamp with time zone; -``` - -This will ensure that no time zone conversions will be applied when converting the columns: - -```output - CreatedOn | type -------------------------+-------------------------- - 2020-01-01 14:00:00+02 | timestamp with time zone -``` - -#### Opting out of the new timestamp mapping logic - -The changes described above are far-reaching, and may break applications in various ways. You can upgrade to version 6.0 but opt out of the new mapping by enabling the `Npgsql.EnableLegacyTimestampBehavior` [AppContext switch](https://docs.microsoft.com/en-us/dotnet/api/system.appcontext). To do this and revert to the legacy timestamp behavior, add the following at the start of your application, before any Npgsql operations are invoked: - -```csharp -AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); -``` - -### NodaTime: tstzrange and daterange are mapped to Interval and DateInterval by default - -When using NodaTime, reading a PostgreSQL `tstzrange` returns [Interval](https://nodatime.org/3.0.x/api/NodaTime.Interval.html) instead of `NpgsqlRange` ([#4070](https://github.com/npgsql/npgsql/issues/4070)), and reading a PostgreSQL `daterange` returns [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html) instead of `NpgsqlRange` ([#3973](https://github.com/npgsql/npgsql/issues/3973)). It is still possible to read `NpgsqlRange` by via `reader.GetFieldValue>` and `reader.GetFieldValue>`. - -### Date/time min/max values are now converted to PostgreSQL infinity values by default - -PostgreSQL has special `infinity` and `-infinity` values for timestamps and dates, which are later and earlier than other value. Npgsql has supported mapping `DateTime.MaxValue` and `MinValue` to these infinity values via an `Convert Infinity DateTime` connection string parameter, which was disabled by default. This behavior is now on by default, since `DateTime.MaxValue` and `MinValue` are very rarely used as actual timestamps/dates, and the `Convert Infinity DateTime` parameter has been removed. To disable infinity conversions, add the following at the start of your application: - -```csharp -AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true); -``` - -[See the date/time documentation](/doc/types/datetime.html#infinity-values) for more details. - -### PG intervals with months/years can no longer be read as TimeSpan - -The PostgreSQL interval type can contain months and years, which are time units without a fixed, absolute duration (different months have different numbers of days). In contrast, .NET TimeSpan is always an absolute duration, and does not support months or years. Previously, when reading intervals as TimeSpan, Npgsql read months as 30-day units, which was incorrect and could yield wrong results. - -To read intervals with month/year components, consider using NodaTime's [Period](https://nodatime.org/3.0.x/api/NodaTime.Period.html) type, which is perfectly suited for representing intervals and is supported by Npgsql. Otherwise, you can read intervals as , provides direct, raw access to the PostgreSQL data which Npgsql receives. Finally, if you want to continue treating months as 30-day units, consider changing your interval data in the database, so that e.g. '1 month 20 days' becomes '50 days'. - -### NpgsqlStatement and PostgresException.Statement have been removed - -Npgsql versions before 6.0 exposed an `NpgsqlStatement` type, which contained information on individual statements within an `NpgsqlCommand` batch. Npgsql introduces support for the new standardized ADO.NET `DbBatch` type, which has numerous advantages compared to the previous support. While executing multiple statements in a single `NpgsqlCommand` is still supported for backwards compatibility, `NpgsqlCommand` no longer exposes per-statement information via `NpgsqlStatement` as before. Consider using the new `NpgsqlBatch` for all batched executions instead: it exposes the `BatchCommands` property which is similar to the previous `Statements` property. Accordingly, `PostgresException.Statement` has been removed, and replaced by `BatchCommand` which is only populated when executing via `NpgsqlBatch`. - -### The default SSL Mode is now Prefer - -When `SSL Mode` isn't specified on the connection string, it used to default to `Disable`; it is now `Prefer`. This means that SSL will be used when the server supports it, and if a custom certificate validation callback is set, failure to validate would cause the connection to fail. - -See the [Security and encryption page](/doc/security.html) for more details. - -### The logical replication API has been redone - -As part of the redesign around logical replication support, some major changes to the API had to be done. Applications will have to be changed to use the new API. - -### Arrays/lists over ranges are mapped to PG14 multiranges - -PostgreSQL 14 introduced [a new multirange type](https://www.postgresql.org/docs/14/rangetypes.html), which is very similar to an array of ranges but supports various range-related operations efficiently. The provider now maps arrays and lists of `NpgsqlRange` to these new types by default. You can still read old-style arrays over ranges by explicitly specifying the type: - -```csharp -var arrayOverRange = reader.GetFieldValue[]>(0); -``` - -You can also write arrays over ranges by explicitly specifying the `NpgsqlDbType`: - -```csharp -var parameter = new NpgsqlParameter -{ - Value = new NpgsqlRange[] { ... }, - NpgsqlDbType = NpgsqlDbType.IntegerRange | NpgsqlDbType.Array -}; -``` - -### DBNull no longer permitted in arrays - -Previously, it was possible to write an `object[]` containing `DBNull` as a way of indicating null; this is no longer supported. Instead, use C# null. - -### Parameter name matching changed around case-sensitivity - -When using named parameter placeholders, Npgsql now only does a single pass to match placeholders to parameters, taking the first parameter whose name passes a case-insensitive match. Npgsql previously did two passes - a case-insensitive pass, followed by a case-sensitive one if the first pass failed to match; this was detrimental to performance in some scenarios. This behavioral change is only visible when using two parameters with names that are identical except for case; this is generally discouraged. - -To revert to the legacy two-pass behavior, add the following at the start of your application, before any Npgsql operations are invoked: - -```csharp -AppContext.SetSwitch("Npgsql.EnableLegacyCaseInsensitiveDbParameters", true); -``` - -Note: version 6.0.0 and 6.0.1 changed parameter matching to be case-sensitive. This change was rolled back in 6.0.2 since it could lead to data loss in some scenarios. - -### The provider-specific date/time types have been obsoleted - -Npgsql contains provider-specific `NpgsqlDateTime`, `NpgsqlDate` and `NpgsqlTimeSpan` types, which were designed to provide the same APIs as the corresponding built-in BCL types, but to support the full range of the PostgreSQL types. These types were buggy and inefficient in many ways, and have been obsoleted; they will be removed in Npgsql 7.0. - -Instead of the obsoleted types, use the following techniques: - -* NodaTime can be used to interact with values which are out-of-range for the BCL types. -* To support values which are out-of-range for NodaTime, PostgreSQL timestamps can now be read/written as long, and dates can be read/written as int. These are the raw PostgreSQL representations, with no operations - they simply provide an "escape hatch" in case users need to interact with out-of-range values. -* For interval, a new `NpgsqlInterval` type has been introduced, which again contains the raw PostgreSQL data (months, days, time). - -### Npgsql.LegacyPostgis has been removed - -The Npgsql.LegacyPostgis plugin, which mapped legacy Npgsql types to PostGIS, has been removed and no longer ships ([#3962](https://github.com/npgsql/npgsql/issues/3962)). Use [Npgsql.NetTopologySuite](/doc/types/nts.html) to work with PostGIS. - -## Contributors - -Thank you very much to the following people who have contributed to the individual 6.0.x. releases. - -### [Milestone 6.0.8](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.8) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.8+is%3Aclosed+assignee%3Aroji) | -| [@vonzshik](https://github.com/vonzshik) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.8+is%3Aclosed+assignee%3Avonzshik) | - -### [Milestone 6.0.7](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.7) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@vonzshik](https://github.com/vonzshik) | [4](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.7+is%3Aclosed+assignee%3Avonzshik) | -| [@roji](https://github.com/roji) | [2](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.7+is%3Aclosed+assignee%3Aroji) | -| [@Brar](https://github.com/Brar) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.7+is%3Aclosed+assignee%3ABrar) | - -### [Milestone 6.0.6](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.6) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@vonzshik](https://github.com/vonzshik) | [3](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.6+is%3Aclosed+assignee%3Avonzshik) | - -### [Milestone 6.0.5](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.5) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [4](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.5+is%3Aclosed+assignee%3Aroji) | -| [@alitas](https://github.com/alitas) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.5+is%3Aclosed+assignee%3Aalitas) | -| [@davidhunt135](https://github.com/davidhunt135) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.5+is%3Aclosed+assignee%3Adavidhunt135) | -| [@vonzshik](https://github.com/vonzshik) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.5+is%3Aclosed+assignee%3Avonzshik) | - -### [Milestone 6.0.4](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.4) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [13](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.4+is%3Aclosed+assignee%3Aroji) | -| [@vonzshik](https://github.com/vonzshik) | [10](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.4+is%3Aclosed+assignee%3Avonzshik) | - -### [Milestone 6.0.3](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.3) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [8](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.3+is%3Aclosed+assignee%3Aroji) | -| [@vonzshik](https://github.com/vonzshik) | [3](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.3+is%3Aclosed+assignee%3Avonzshik) | -| [@Brar](https://github.com/Brar) | [2](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.3+is%3Aclosed+assignee%3ABrar) | -| [@NinoFloris](https://github.com/NinoFloris) | [2](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.3+is%3Aclosed+assignee%3ANinoFloris) | - -### [Milestone 6.0.2](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.2) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [3](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.2+is%3Aclosed+assignee%3Aroji) | -| [@NinoFloris](https://github.com/NinoFloris) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.2+is%3Aclosed+assignee%3ANinoFloris) | - -### [Milestone 6.0.1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.1) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@vonzshik](https://github.com/vonzshik) | [5](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.1+is%3Aclosed+assignee%3Avonzshik) | -| [@roji](https://github.com/roji) | [4](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.1+is%3Aclosed+assignee%3Aroji) | -| [@NinoFloris](https://github.com/NinoFloris) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.1+is%3Aclosed+assignee%3ANinoFloris) | -| [@zitmen](https://github.com/zitmen) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.1+is%3Aclosed+assignee%3Azitmen) | - -### [Milestone 6.0.0](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.0) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [42](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Aroji) | -| [@vonzshik](https://github.com/vonzshik) | [34](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Avonzshik) | -| [@Brar](https://github.com/Brar) | [7](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3ABrar) | -| [@NinoFloris](https://github.com/NinoFloris) | [3](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3ANinoFloris) | -| [@Emill](https://github.com/Emill) | [2](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3AEmill) | -| [@manandre](https://github.com/manandre) | [2](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Amanandre) | -| [@mdalepiane](https://github.com/mdalepiane) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Amdalepiane) | -| [@mintsoft](https://github.com/mintsoft) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3Amintsoft) | -| [@Seltzer](https://github.com/Seltzer) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3ASeltzer) | -| [@TwentyFourMinutes](https://github.com/TwentyFourMinutes) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A6.0.0+is%3Aclosed+assignee%3ATwentyFourMinutes) | diff --git a/conceptual/Npgsql/release-notes/7.0.md b/conceptual/Npgsql/release-notes/7.0.md deleted file mode 100644 index b0151826..00000000 --- a/conceptual/Npgsql/release-notes/7.0.md +++ /dev/null @@ -1,180 +0,0 @@ -# Npgsql 7.0 Release Notes - -Npgsql version 7.0 has been released and is available on nuget. - -## New features - -The full list of issues for this release is [available here](https://github.com/npgsql/npgsql/milestone/85?closed=1). - -### DbDataSource - -A major improvement in Npgsql 7.0 is , which implements the new [DbDataSource](https://learn.microsoft.com/dotnet/api/system.data.common.dbdatasource) abstraction in .NET System.Data. A data source represents your PostgreSQL database, and can hand out connections to it or support direct execution of SQL to it. - -Instead of directly instantiating an `NpgsqlConnection` and then executing commands against it, you now create a data source once, and then use that throughout your application: - -```csharp -await using var dataSource = NpgsqlDataSource.Create(connectionString); - -// Execute a command directly against the data source, no NpgsqlConnection needed: -await using var command = dataSource.CreateCommand("INSERT INTO some_table (some_field) VALUES (8)"); -await command.ExecuteNonQueryAsync(); - -// Open a connection in order to e.g. start a transaction on it: -await using var connection = await dataSource.OpenConnectionAsync(); -``` - -Since the data source encapsulates all the necessary configuration for connecting to a database (e.g. the connection string, authentication callbacks...), it can be registered in dependency injection or passed around as needed, without needing any additional information. The new also provides the ideal API point for various configuration when building a data source: - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder("Host=localhost;Username=test;Password=test"); -dataSourceBuilder - .UseLoggerFactory(loggerFactory) // Configure logging - .UsePeriodicPasswordProvider() // Automatically rotate the password periodically - .UseNodaTime(); // Use NodaTime for date/time types -await using var dataSource = dataSourceBuilder.Build(); -``` - -If you're using dependency injection (e.g. in an ASP.NET application), see the [Npgsql.DependencyInjection](https://www.nuget.org/packages/Npgsql.DependencyInjection#readme-body-tab) package for an easy way to set up your data source. - -### Improved logging with Microsoft.Extensions.Logging - -Previous versions had a custom logging implementation which required special adapters and was hard to use. Npgsql 7.0 fully supports the standard .NET [Microsoft.Extensions.Logging](https://learn.microsoft.com/dotnet/core/extensions/logging) - just provide Npgsql with your `ILoggerFactory` and you're ready to go. - -If you using ASP.NET, things are even easier with the new [Npgsql.DependencyInjection](https://www.nuget.org/packages/Npgsql.DependencyInjection), which takes care of seamlessly picking up the ASP.NET logging configuration from DI: - -```csharp -var builder = WebApplication.CreateBuilder(args); -builder.Logging.AddConsole(); -builder.Services.AddNpgsqlDataSource("Host=localhost;Username=test;Password=test"); -``` - -For more details, see the updated [logging documentation page](../diagnostics/logging.md). - -### Support for version 3 of the logical replication protocol - -PostgreSQL 15 introduced improvements to logical replication, in particular around streaming large, in-progress transactions. Npgsql 7.0 adds support for improvements - see [#4216](https://github.com/npgsql/npgsql/issues/4216) for more information (thanks [@Brar](https://github.com/Brar)!). - -## Breaking changes - -### CommandType.StoredProcedure now invokes procedures instead of functions - -When [`NpgsqlCommand.CommandType`](https://www.npgsql.org/doc/api/Npgsql.NpgsqlCommand.html#Npgsql_NpgsqlCommand_CommandType) is set to [`CommandType.StoredProcedure`](https://learn.microsoft.com/dotnet/api/system.data.commandtype#system-data-commandtype-storedprocedure), Npgsql now generates SQL for invoking a PostgreSQL [stored procedure](https://www.postgresql.org/docs/current/sql-createprocedure.html), and not a [function](https://www.postgresql.org/docs/current/sql-createfunction.html), as before. To opt out of this breaking change and continue to invoke functions as before, enable the `Npgsql.EnableStoredProcedureCompatMode` [AppContext switch](https://docs.microsoft.com/dotnet/api/system.appcontext) as follows: - -```csharp -AppContext.SetSwitch("Npgsql.EnableStoredProcedureCompatMode", true); -``` - -For context, PostgreSQL originally only supported functions, and did not support the standard SQL concept of stored procedures; because of this, [`CommandType.StoredProcedure`](https://learn.microsoft.com/dotnet/api/system.data.commandtype#system-data-commandtype-storedprocedure) was implemented to invoke functions. PostgreSQL 11 then introduced stored procedures, which have various advantages over functions in some scenarios (e.g. the ability to use transactions). The 7.0 release changes [`CommandType.StoredProcedure`](https://learn.microsoft.com/dotnet/api/system.data.commandtype#system-data-commandtype-storedprocedure) to invoke procedures as its naming suggests, and aligns Npgsql with other database providers for better compatibility. - -Note that with Npgsql, there is no advantage in using [`CommandType.StoredProcedure`](https://learn.microsoft.com/dotnet/api/system.data.commandtype#system-data-commandtype-storedprocedure) over simply invoking your function or procedure via SQL. Doing so is in fact recommended: - -```csharp -// Invoke a procedure -using var command1 = new NpgsqlCommand("CALL some_procedure($1, $2)", connection) -{ - new() { Value = "some_value" }, - new() { Value = "some_other_value" } -}; - -// Invoke a function -using var command2 = new NpgsqlCommand("SELECT * FROM some_function($1, $2)", connection) -{ - new() { Value = "some_value" }, - new() { Value = "some_other_value" } -}; -``` - -For more information on calling procedures and functions, see [this doc section](../basic-usage.md#stored-functions-and-procedures). - -### Managing type mappings at the connection level is no longer supported - -Previous versions of Npgsql allowed mapping custom types (enums/composites) and configuring plugins (NetTopologySuite, NodaTime) at the connection level; the type mapping change would persist only for the lifetime of the connection, and would be reverted when the connection closed. This mechanism was inefficient - connections get opened and closed a lot - and added significant maintenance burden internally. - -With the introduction of `NpgsqlDataSource`, Npgsql now has a natural API point for managing type mappings: - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder("Host=localhost;Username=test;Password=test"); -dataSourceBuilder.MapEnum(); -dataSourceBuilder.UseNodaTime(); -await using var dataSource = dataSourceBuilder.Build(); -``` - -All connections handed out by the data source will use the configured type mappings. - -Note that managing type mappings globally via `NpgsqlConnection.GlobalTypeMapper` is supported as before, but has been marked as obsolete; although we do not plan on removing global type mappings any time soon, is now the recommended way to manage type mappings. - -### Global type mappings must now be done before any usage - -Previously, any type mapping configuration done via `NpgsqlConnection.GlobalTypeMapper` would take effect for any new connection opened after the change. Starting with 7.0, global type mappings must be done before the data source or pool is created. To ensure correct functioning, do any global type mappings at the very start of your program, before using any other Npgsql API. - -### NpgsqlDataReader.Dispose no longer swallows exceptions - -Previously, when an unconsumed was disposed, any exceptions that occurred while consuming the remaining results were swallowed and `Dispose` completed successfully. These exceptions are no longer swallowed, and are thrown from Dispose. This also affects scenarios where is used in a C# `using` statement. - -In most cases in .NET, throwing from `Dispose` is discouraged. If the instance being disposed is used in a `using` statement and some exception is thrown, that exception triggers `Dispose` being called (as per `using`), and if `Dispose` throws an exception of its own, then that exception bubbles up. As a result, the original exception is hidden, making it difficult to understand exactly what happened. As a result, it is common for `Dispose` to catch any exceptions internally and swallow them, allowing the original exception to bubble up. - -However, in the Npgsql case, swallowing exceptions in `Dispose` can have very problematic consequences. A reader can be disposed before it's entirely consumed, after only part of the result set has been read; when this happens, Npgsql consumes the rest of the result set as part of the disposal. If any errors occur past this point, then those exceptions were previously swallowed; this meant that the application could be unaware that part of the command failed, since no exception was raised. Throwing these exceptions from dispose ensures that the application is aware of any failures that occurred. - -For more context on this change, see the discussion in [#4377](https://github.com/npgsql/npgsql/issues/4377). - -### The logging API has been replaced by Microsoft.Extensions.Logging - -Npgsql previously had its own logging API, requiring special adapters to the standard logging libraries. This API has been removed in 7.0, and replaced with support for the standard Microsoft.Extensions.Logging package. See [Logging](../diagnostics/logging.md) for more information. - -### The obsoleted NpgsqlDateTime, NpgsqlDate and NpgsqlTimeSpan have been removed - -`NpgsqlDateTime`, `NpgsqlDate` and `NpgsqlTimeSpan` were "provider-specific" types, designed to expose the full range of the PostgreSQL date/time types, which can represent values beyond the built-in .NET types (e.g. `DateTime`). However, these types were problematic in many ways, and were seldom used. The types were obsoleted in Npgsql 6.0, and have been removed in 7.0. - -To deal with date/time values outside the range of the corresponding .NET types, see [Date and Time Handling](../types/datetime.md). - -### NpgsqlConnection.Settings has been removed - -The connection's connection string is still exposed via ; this can be parsed with . - -### Replication APIs now return UTC DateTime - -Previously, replication APIs returned `DateTime` instances of Kind `Unspecified`; this has been changed to `Utc` to reflect the actual type of data sent by PostgreSQL. - -## Contributors - -Thank you very much to the following people who have contributed to the individual 7.0.x. releases. - -### [Milestone 7.0.6](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.6) - -| Contributor | Assigned issues | -| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------:| -| [@vonzshik](https://github.com/vonzshik) | [10](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.6+is%3Aclosed+assignee%3Avonzshik) | -| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.6+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 7.0.4](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.4) - -| Contributor | Assigned issues | -| ---------------------------------------- | -----------------------------------------------------------------------------------------------------------:| -| [@vonzshik](https://github.com/vonzshik) | [3](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.4+is%3Aclosed+assignee%3Avonzshik) | -| [@roji](https://github.com/roji) | [2](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.4+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 7.0.2](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.2) - -| Contributor | Assigned issues | -| ---------------------------------------- | -----------------------------------------------------------------------------------------------------------:| -| [@vonzshik](https://github.com/vonzshik) | [5](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.2+is%3Aclosed+assignee%3Avonzshik) | -| [@manandre](https://github.com/manandre) | [2](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.2+is%3Aclosed+assignee%3Amanandre) | -| [@roji](https://github.com/roji) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.2+is%3Aclosed+assignee%3Aroji) | - -### [Milestone 7.0.1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A7.0.1) - -| Contributor | Assigned issues | -| ---------------------------------------- | -----------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [3](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A7.0.1+is%3Aclosed+assignee%3Aroji) | -| [@Brar](https://github.com/Brar) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A7.0.1+is%3Aclosed+assignee%3ABrar) | -| [@vonzshik](https://github.com/vonzshik) | [1](https://github.com/npgsql/npgsql/issues?q=is%3Aissue+milestone%3A7.0.1+is%3Aclosed+assignee%3Avonzshik) | - -### [Milestone 7.0.0](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.0) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------------------- | -----------------------------------------------------------------------------------------------------------------------:| -| [@roji](https://github.com/roji) | [37](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.0+is%3Aclosed+assignee%3Aroji) | -| [@Brar](https://github.com/Brar) | [9](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.0+is%3Aclosed+assignee%3ABrar) | -| [@vonzshik](https://github.com/vonzshik) | [4](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.0+is%3Aclosed+assignee%3Avonzshik) | -| [@0xced](https://github.com/0xced) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.0+is%3Aclosed+assignee%3A0xced) | -| [@baal2000](https://github.com/baal2000) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A7.0.0+is%3Aclosed+assignee%3Abaal2000) | diff --git a/conceptual/Npgsql/release-notes/8.0.md b/conceptual/Npgsql/release-notes/8.0.md deleted file mode 100644 index 40fb6dd8..00000000 --- a/conceptual/Npgsql/release-notes/8.0.md +++ /dev/null @@ -1,156 +0,0 @@ -# Npgsql 8.0 Release Notes - -Npgsql version 8.0 is out and available on [nuget.org](https://www.nuget.org/packages/Npgsql/8.0.0). - -> [!NOTE] -> Npgsql 8.0 will be the last version to support .NET Framework (via .NET Standard 2.0). Starting with 9.0, Npgsql will only target .NET TFMs supported at release time (i.e. `net6.0`). - -## NativeAOT and trimming support - -Npgsql 8.0 now has 1st-class support for NativeAOT and trimming; the entire library has been properly annotated and is safe for use in applications. The majority of features have been made compatible with NativeAOT/trimming and can be used without issues, and most applications using Npgsql can be used as-is with NativeAOT/trimming without any changes. A few features which are incompatible require an explicit code opt-in, which generates a warning if used with NativeAOT/trimming enabled ([see breaking change note](#dynamic-optin)). - -Considerable effort has gone into reducing Npgsql's size footprint; a minimal Npgsql application using NativeAOT and trimming now takes only around 5MB of disk space. To allow users to achieve a minimal size footprint, has been introduced; unlike the standard , this builder includes only the very minimum of functionality by default, and allows adding additional features via opt-ins. This allows a pay-per-play approach to application size, where developers can choose only the features they actually need for optimal size. For more information, see . - -Making Npgsql NativeAOT/trimming-compatible was a far-reaching effort, affecting many parts of the driver and involving a rewrite of large parts of Npgsql's internals (leading to many other internal improvements). This huge task was done mainly by [Nino Floris](http://github.com/ninofloris), with considerable contributions by [Nikita Kazmin](https://github.com/vonzshik). - -## OpenTelemetry metrics - -Npgsql has emitted metrics for several versions, which provided aggregated metrics on various Npgsql interals; for example, it was possible to follow the state of the connection pool, or to track how many commands are being executed per second. Npgsql 8.0 improves on that by switching from the older EventCounter API to the newer System.Diagnostics.Metrics API, implementing OpenTelemetry metrics. To understand more about the different kinds of metrics APIs in .NET, [see these docs](https://learn.microsoft.com/en-us/dotnet/core/diagnostics/compare-metric-apis). - -The new metrics have several advantages over the old one; for one thing, they allow associating multiple *dimensions* to metrics, e.g. allowing Npgsql to cleanly emit pool-related metrics separately for each data source (or connection string) used in the application. The Npgsql metrics implement the experimental [OpenTelemetry semantic conventions for database metrics](https://opentelemetry.io/docs/specs/semconv/database/database-metrics/) - adding some additional useful ones - and will evolve as that specification stabilizes. - -For more information, see the [doc page on metrics](../diagnostics/metrics.md). - -## Register NpgsqlDataSource as a keyed DI service - -.NET 8.0 introduced [keyed services for dependency injection](https://learn.microsoft.com/dotnet/core/extensions/dependency-injection#keyed-services), allowing multiple services with the same CLR type to be registered in a single DI service provider. This is particularly useful when needing to contact multiple databases from your DI-enabled application: - -```csharp -var builder = WebApplication.CreateBuilder(args); - -builder.Services - .AddNpgsqlDataSource("Host=localhost;Database=CustomersDB;Username=test;Password=test", serviceKey: DatabaseType.CustomerDb) - .AddNpgsqlDataSource("Host=localhost;Database=OrdersDB;Username=test;Password=test", serviceKey: DatabaseType.OrdersDb); - -var app = builder.Build(); - -app.MapGet("/", async ([FromKeyedServices(DatabaseType.OrdersDb)] NpgsqlConnection connection) - => connection.ConnectionString); - -app.Run(); - -enum DatabaseType -{ - CustomerDb, - OrdersDb -} -``` - -In this ASP.NET Minimal API application, two Npgsql data sources are registered in DI - one for a customers database, and another for an orders database. When a data source - or connections - needs to be injected somewhere, an enum is used as the service key, to distinguish which database is being requested (note that connections to both databases can be requested by the same function!). - -For more information on registering Npgsql services in DI, see the documentation for [Npgsql.DependencyInjection](https://www.nuget.org/packages/Npgsql.DependencyInjection#readme-body-tab). - -## Other features - -* Allow using nullable value types with the generic `NpgsqlParameter`, e.g. `NpgsqlParameter`. -* Introduce a non-caching password provider callback via . -* Allow customizing System.Text.Json JsonSerializationOptions via . -* Improvements and cleanup for networking type mappings: - * In addition to .NET , PostgreSQL `inet` can also mapped to be mapped to , which is an immutable struct containing both IP and netmask components. - * PostgreSQL `cidr` is now mapped to the newly-introduced . The mapping to `ValueTuple` has been removed. -* Allow providing the root certificate programmatically via the new - -Version 8.0 contains many other smaller features and bug fixes, [see the 8.0.0 milestone](https://github.com/npgsql/npgsql/milestone/97?closed=1) for the full list of issues. - -## Breaking changes - -### JSON POCO and other dynamic features now require an explicit opt-in - -Npgsql 8.0 is fully compatible with NativeAOT and trimming (see above). While most driver capabilities have been made to work in those profiles, certain features involve dynamic coding practices and are incompatible with NativeAOT and/or trimming - at least for now. As a result, these features now require explicit opt-ins (annotated to be incompatible with NativeAOT/trimming), which you must add either on your or on : - -PostgreSQL type | Default .NET type ----------------------------------------- | -------------------------- -JSON POCO mapping, JsonNode and subtypes | -Unmapped enums, ranges, multiranges | -Read PostgreSQL records as .NET tuples | - -Existing code using the above features will start throwing exceptions after upgrading to Npgsql 8.0; the exceptions provide explicit guidance on how to add the opt-ins. - -### `SSL Mode=Require` no longer validates certificates - -tl;dr use `SSL Mode=VerifyCA` or `VerifyFull` in order to validate certificates provided by PostgreSQL. - -In versions of Npgsql older than 6.0, specifying `SSL Mode=Require` made Npgsql validate the SSL/TLS certificate provided by PostgreSQL. This did not align with the meaning of "require" in PostgreSQL and other clients, where it simply means that SSL/TLS is required, but without certificate validation. To align with the standard PostgreSQL meaning, starting with Npgsql 6.0 `VerifyCA` or `VerifyFull` must be specified to validate the certificate. - -To prevent existing usage of `Require` to silently stop validating, Npgsql 6.0 and 7.0 forced `Trust Server Certificate=true` to be specified; this made users aware of the change, guiding them to either switch to `VerifyCA`/`VerifyFull` (if they want validation) or to add `Trust Server Certificate=true` (if they don't). After two major versions, we are now removing the requirement to specify `Trust Server Certificate=true` with `SSL Mode=Require`; the latter will behave in the standard PostgreSQL way and will not verify certificates. - -For more context, see [#3988](https://github.com/npgsql/npgsql/issues/3988#issuecomment-933011009). - -### IList\ mapping now requires a generic NpgsqlParameter\ - -Previous versions of Npgsql allowed writing arbitrary list types as PostgreSQL array, as long as they implemented the `IList` interface: - -```csharp -await using var command = new NpgsqlCommand("SELECT $1", conn) -{ - Parameters = { new NpgsqlParameter { Value = new ReadOnlyCollection(new List { 1, 2, 3 }) } } -}; -await using var reader = await command.ExecuteReaderAsync(); -``` - -This capability has been removed; supporting it required a costly reflection check, which also would be difficult to implement with trimming enabled, potentially increasing binary size in an unacceptable way. As a mitigation, you can instead use the generic `NpgsqlParameter` - typed with `IList` - to do the same: - -```csharp -await using var command = new NpgsqlCommand("SELECT $1", conn) -{ - Parameters = { new NpgsqlParameter> { Value = new ReadOnlyCollection(new List { 1, 2, 3 }) } } -}; -await using var reader = await command.ExecuteReaderAsync(); -``` - -### `cidr` now maps to `NpgsqlCidr` instead of `ValueTuple` - -As part of improving Npgsql's support for the PostgreSQL network mappings (see above), the PostgreSQL `cidr` type now maps to the newly-introduced , and can no longer be mapped to `ValueTuple`. - -### Obsoletions and obsolete API removals - -* The `Integrated Security` connection parameter has been removed. It was never actually necessary - simply stop setting it. -* `NpgsqlTsVector.Parse()` and `NpgsqlTsQuery.Parse()` are now obsolete. These methods attempted to mimic the behavior of the PostgreSQL `to_tsvector` and `to_tsquery` functions, but could only do so partially and in problematic ways. Use the PostgreSQL functions instead. -* The parsing functions on the built-in geometry types (NpgsqlPoint, NpgsqlBox etc.) have been removed; similarly, they partially replicated PostgreSQL parsing functionality client-side and had issues. -* `NpgsqlLargeObjectManager` and `NpsgqlLargeObjectStream` are now obsolete. These types were very rarely-used, provided only a thin wrapper over easily-accessible PostgreSQL large-object functions, and limited usage in various ways (e.g. they didn't allow batching). Call the PostgreSQL large-object functions directly. -* The `Internal Command Timeout` connection string parameter has been obsoleted. -* `NpgsqlDbType.TimestampTZ` and `NpgsqlDbType.TimeTZ` were obsoleted many releases ago, and were finally removed. Use `NpgsqlDbType.TimestampTz` and `NpgsqlDbType.TimeTz` instead. - -### Executing a void-returning function returns .NET null instead of DBNull - -Previously, executing a void-returning returned `DBNull.Value`: - -```csharp -var command = new NpgsqlCommand("SELECT pg_sleep(10)", connection); -var result = await command.ExecuteScalarAsync(); -``` - -Before 8.0, `result` had the value `DBNull.Value`; this has been changed in 8.0 to be .NET `null`. This is more correct (as there are no results, rather than a result containing NULL), aligns with ADO.NET standard practices and with other drivers. - -### Plugin APIs have been changed for NativeAOT/trimming support - -As part of the effort to make Npgsql compatible with NativeAOT and trimming, the plugin API was changed in fundamental, breaking ways. Although this API never had the stability guarantees of a true public API (it was and still is in an Internal namespace), external plugins which were developed with it will require adjustments. - -## Contributors - -Thank you very much to the following people who have contributed to the individual 8.0.x. releases. - -### [Milestone 8.0.0](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A8.0.0) - -| Contributor | Assigned issues | -| ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------:| -| [@NinoFloris](https://github.com/NinoFloris) | [43](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3ANinoFloris) | -| [@vonzshik](https://github.com/vonzshik) | [23](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3Avonzshik) | -| [@roji](https://github.com/roji) | [20](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3Aroji) | -| [@manandre](https://github.com/manandre) | [4](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3Amanandre) | -| [@BogdanYarotsky](https://github.com/BogdanYarotsky) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3ABogdanYarotsky) | -| [@Brar](https://github.com/Brar) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3ABrar) | -| [@erikdesj](https://github.com/erikdesj) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3Aerikdesj) | -| [@SoftStoneDevelop](https://github.com/SoftStoneDevelop) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3ASoftStoneDevelop) | -| [@sonquer](https://github.com/sonquer) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3Asonquer) | -| [@yucelkivanc-hepsiburada](https://github.com/yucelkivanc-hepsiburada) | [1](https://github.com/Npgsql/Npgsql/issues?q=is%3Aissue+milestone%3A8.0.0+is%3Aclosed+assignee%3Ayucelkivanc-hepsiburada) | diff --git a/conceptual/Npgsql/release-notes/9.0.md b/conceptual/Npgsql/release-notes/9.0.md deleted file mode 100644 index 566c76ed..00000000 --- a/conceptual/Npgsql/release-notes/9.0.md +++ /dev/null @@ -1,82 +0,0 @@ -# Npgsql 9.0 Release Notes - -Npgsql version 9.0 is out and available on [nuget.org](https://www.nuget.org/packages/Npgsql). - -## Tracing improvements - -Several quality-of-life improvements have been implemented for Npgsql's OpenTelemetry tracing support. You can now do the following via the new API: - -* Specify a filter which determines which commands get traced -* Set the the tracing span name (e.g. use the command's SQL as the span name) -* Add arbitrary tags to the tracing span, based on the command -* Disable the time-to-first-read event that's emitted in spans - -See the [tracing documentation](/doc/diagnostics/tracing.html) for more information. - -## Mapping improvements - -### Support System.Text.Json polymorphism with PostgreSQL `jsonb` - -> [!NOTE] -> If you're using EF Core, the below pertains to the EF provider's [legacy POCO mapping](https://www.npgsql.org/efcore/mapping/json.html?tabs=data-annotations%2Cjsondocument#legacy-poco-mapping-deprecated), and not to the recommended [ToJson mapping](https://www.npgsql.org/efcore/mapping/json.html?tabs=data-annotations%2Cjsondocument#poco-mapping). Unfortunately, the latter does not yet support polymorphic serialization (support for this may be added in EF 10). - -System.Text.Json has supported [polymorphic serialization](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/polymorphism) for a while, using a JSON `$type` property as the type discriminator. However, it was required that the `$type` property be at the top of the JSON document; this causes problems serializing to the PostgreSQL `jsonb` type, since that type does **not** preserve property order in JSON objects. - -System.Text.Json 9.0 brings support for [out-of-order metadata reads](https://devblogs.microsoft.com/dotnet/system-text-json-in-dotnet-9/#out-of-order-metadata-reads), which is an opt-in feature allowing the `$type` property to be anywhere in the JSON object. When using Npgsql, you can opt into this when configuring your as follows: - -```c# -var builder = new NpgsqlDataSourceBuilder(""); -builder - .EnableDynamicJson() - .ConfigureJsonOptions(new JsonSerializerOptions { AllowOutOfOrderMetadataProperties = true }); -await using var dataSource = builder.Build(); -``` - -Once that's done, you can use JSON polymorphism with `jsonb`. If you're still targeting .NET 8.0, you can take a reference on System.Text.Json 9.0 in order to use `AllowOutOfOrderMetadataProperties`. - -### Add support for cidr <-> IPNetwork mapping - -.NET 8 added a new type [IPNetwork](https://learn.microsoft.com/en-us/dotnet/api/system.net.ipnetwork?view=net-8.0) which represents an IP network with an [IPAddress](https://learn.microsoft.com/en-us/dotnet/api/system.net.ipaddress?view=net-8.0) containing the network prefix and an `int` defining the prefix length. This type seems to be a perfect fit for PostgreSQL's `cidr` type, which is why we added support to read and write it. The default when reading a `cidr` is still `NpgsqlCidr` in 9.0, though this will likely change in Npgsql 10.0. See [this issue](https://github.com/npgsql/npgsql/issues/5821) for more info. - -### Add support for interval's infinity values via NodaTime's Period.MinValue/Period.MaxValue - -PostgreSQL 17 added support for infinity values with `interval` type. In turn, Npgsql 9.0 adds native support to read and write them via NodaTime's `Period.MinValue` and `Period.MaxValue`. Note that while using this feature with previous versions of PostgreSQL, instead of infinity values you'll get the minimum and maximum values for `interval` type due to the way infinity values are implemented by PostgreSQL. See [this issue](https://github.com/npgsql/npgsql/issues/5696) for more info. - -## Security-related improvements - -* PostgreSQL 17 added support for **direct SSL**. Direct SSL allows clients to skip sending an SSL support request, which saves a roundtrip while opening a physical connection. This behavior is disabled by default (as it's not supported with previous versions of PostgreSQL), but you can enable it via the `SslNegotiation` property in connection string or environment variable `PGSSLNEGOTIATION`. See [this issue](https://github.com/npgsql/npgsql/issues/5677) for more info. -* The new callback is called while connecting to PostgreSQL via `SslStream`, and allows users to modify [SslClientAuthenticationOptions](https://learn.microsoft.com/en-us/dotnet/api/system.net.security.sslclientauthenticationoptions?view=net-8.0), e.g. to change the supported TLS ciphers. See [this issue](https://github.com/npgsql/npgsql/issues/5478) for more info. -* The new callback is called while performing GSSAPI authentication (such as Kerberos), and allows users to modify [NegotiateAuthenticationClientOptions](https://learn.microsoft.com/en-us/dotnet/api/system.net.security.negotiateauthenticationclientoptions?view=net-8.0), e.g. to change the `Credential` property to implement password-based Kerberos authentication. See [this](https://github.com/npgsql/npgsql/issues/5181) issue for more info. - -## Replication improvements - -* Parallel in-progress transactions with logical streaming replication protocol V4 allow clients to handle multiple in-progress transactions in parallel instead of sequentially. See [this issue](https://github.com/npgsql/npgsql/issues/5760) for more info. -* `ReplicationValue.GetFieldName` allows clients to receive the name of changed column while reading rows from replication stream. See [this issue](https://github.com/npgsql/npgsql/issues/5718) for more info. - -## Breaking changes - -### .NET Standard 2.0 (and .NET Framework) are no longer supported - -Npgsql 9.0 drops support for .NET Standard 2.0, and in turn .NET Framework. Npgsql is a constantly evolving driver, which makes it problematic to add new features which use APIs that do not exist on older versions of .NET. This doesn't mean you can't use Npgsql with .NET Standard 2.0: we're still committed to supporting Npgsql 8.0 (which does support .NET Standard 2.0). See [this issue](https://github.com/npgsql/npgsql/issues/5296) for more info. - -### Multiple SSL-related callbacks on NpgsqlDataSourceBuilder are deprecated - -With the new `UseSslClientAuthenticationOptionsCallback` callback, users have much more control over the way Npgsql connects to PostgreSQL via `SslStream`. This makes other callbacks, like `UseUserCertificateValidationCallback` and `UseClientCertificate` less useful, which is why we're obsoleting them. See [this issue](https://github.com/npgsql/npgsql/issues/5478) for more info. - -### Obsoleted the Server Compatibility Mode and Load Table Composites connection string parameters - -Npgsql has supported disabling its initial type loading, as well as tweaking whether table composites are loaded, via the connection string. These have been obsoleted, and configuration APIs on NpgsqlDataSourceBuilder have been introduced. For example, to disable type loading, use the following code: - -```c# -var builder = new NpgsqlDataSourceBuilder("Host=localhost;Username=test;Password=test"); -builder.ConfigureTypeLoading(x => x.EnableTypeLoading(false)); -await using var dataSource = builder.Build(); -``` - -### ConnectionLifetime now defaults to 1 hour - -The `Connection Lifetime` connection string property determines the total maximum lifetime of connections. Previously, the default value of this property was set to 0, which made connections last indefinitely. The old behavior was problematic because each physical connection on PostgreSQL's side holds on certain caches, which can only grow over time. See [this pull request](https://github.com/npgsql/npgsql/pull/5662) for more info. - -### Changes on PgOutputReplicationOptions - -In order to support the new logical streaming replication protocol V4, the `ProtocolVersion` and `StreamingMode` properties on the `PgOutputReplicationOptions` were changed to an enum. See [this issue](https://github.com/npgsql/npgsql/issues/5760) for more info. diff --git a/conceptual/Npgsql/replication.md b/conceptual/Npgsql/replication.md deleted file mode 100644 index 93720b8b..00000000 --- a/conceptual/Npgsql/replication.md +++ /dev/null @@ -1,132 +0,0 @@ -# Logical and Physical Replication - -Replication allows a client to receive a continuous stream of updates from a PostgreSQL database, providing a near-realtime view of all changes as they occur. While this feature was originally developed to keep PostgreSQL standby replicas in sync with a primary, it can be used by arbitrary client applications. - -Replication can be used anywhere where a constant change feed of database changes is required; for example, an external application can be notified in near-realtime of any changes that occurred in a particular database table. This can be useful for external auditing purposes, for replicating certain data somewhere else, for implement the outbox pattern (see [Additional resources](#additional-resources) below), and various other usages. - -Npgsql provides a 1st-class API for writing .NET replication clients, detailed below. While PostgreSQL supports both logical and physical replication, in the majority of cases .NET applications will want to use logical replication. - -## Logical replication - -Logical replication is a means to stream messages generated by PostgreSQL [logical decoding](https://www.postgresql.org/docs/current/logicaldecoding.html) plugins to a client. -The default implementation that is used by PostgreSQL itself to perform logical server to server replication is the Logical Streaming Replication Protocol which uses the `pgoutput` plugin, but PostgreSQL supports streaming messages generated by other plugins too and Npgsql supports receiving those. - -### General setup - -To set up logical replication, follow the [quick setup instructions](https://www.postgresql.org/docs/current/logical-replication-quick-setup.html) in the PostgreSQL docs (note that a SUBSCRIPTION isn't required since the client isn't PostgreSQL): - -Enable logical replication in your `postgresql.conf` file: - -```ini -wal_level = logical -``` - -Set up a replication user in your [`pg_hba.conf`](https://www.postgresql.org/docs/current/auth-pg-hba-conf.html) file: - -```text -host replication repuser 0.0.0.0/0 md5 -``` - -The user `repuser` must exist in your cluster and either be a superuser or have the replication attribute set. See [CREATE ROLE docs](https://www.postgresql.org/docs/current/sql-createrole.html). - -### Logical Streaming Replication Protocol (pgoutput plugin) - -The modern, recommended way to perform logical replication was introduced in PostgreSQL 10 - [see the PostgreSQL documentation](https://www.postgresql.org/docs/current/logical-replication.html). This method, using the built-in pgoutput replication plugin, streams efficient, binary messages to represent database updates such as INSERT, UPDATE and DELETE ([see the full list](https://www.postgresql.org/docs/current/protocol-logicalrep-message-formats.html)); Npgsql exposes these messages as an `IAsyncEnumerable` which can easily be enumerated and consumed. - -[Create a publication](https://www.postgresql.org/docs/current/sql-createpublication.html), which defines the group of tables in the database you wish to replicate: - -```sql -CREATE PUBLICATION blog_pub FOR TABLE blogs; -``` - -Create a replication slot, which will hold the state of the replication stream: - -```sql -SELECT * FROM pg_create_logical_replication_slot('blog_slot', 'pgoutput'); -``` - -If your application goes down, the slot persistently records the last data streamed to it, and allows resuming the application at the point where it left off. - -At this point, everything is ready to start replicating! Create this simple .NET program with Npgsql: - -```csharp -await using var conn = new LogicalReplicationConnection(""); -await conn.Open(); - -var slot = new PgOutputReplicationSlot("blog_slot"); - -// The following will loop until the cancellation token is triggered, and will print message types coming from PostgreSQL: -var cancellationTokenSource = new CancellationTokenSource(); -await foreach (var message in conn.StartReplication( - slot, new PgOutputReplicationOptions("blog_pub", 1), cancellationTokenSource.Token)) -{ - Console.WriteLine($"Received message type: {message.GetType().Name}"); - - // Always call SetReplicationStatus() or assign LastAppliedLsn and LastFlushedLsn individually - // so that Npgsql can inform the server which WAL files can be removed/recycled. - conn.SetReplicationStatus(message.WalEnd); -} -``` - -For example, if you insert a new row into your `blogs` table, you should see the following output: - -```output -Received message type: BeginMessage -Received message type: RelationMessage -Received message type: InsertMessage -Received message type: CommitMessage -``` - -> [!WARNING] -> Npgsql internally recycles the message instances it hands out. It is an error to use a message received from `StartReplication` once the next message has been read. - -The above was just a minimal "getting started" guide for logical replication - many additional configuration options and modes exist as well. Consult the PostgreSQL documentation for more details. - -### Test decoding (test_decoding plugin) - -An additional logical replication plugin which Npgsql supports is `test_decoding`. This plugin outputs textual representations of events, which are less efficient and need to be parsed; it is meant for testing that replication works rather than for building robust production apps. However, it can still be useful in some scenarios, especially in older PostgreSQL versions where `pgoutput` wasn't yet introduced. - -To use `test_decoding`, first create a logical replication slot with `test_decoding` as the plugin type. - -```sql -SELECT * FROM pg_create_logical_replication_slot('blog_slot', 'test_decoding'); -``` - -After that use the following: - -```csharp -await using var conn = new LogicalReplicationConnection("Host=localhost;Username=test;Password=test"); -await conn.Open(); - -var slot = new TestDecodingReplicationSlot("blog_slot"); - -// The following will loop until the cancellation token is triggered, and will print message types coming from PostgreSQL: -var cancellationTokenSource = new CancellationTokenSource(); -await foreach (var message in conn.StartReplication(slot, cancellationTokenSource.Token)) -{ - Console.WriteLine($"Message: {message.Data}"); - - // Always call SetReplicationStatus() or assign LastAppliedLsn and LastFlushedLsn individually - // so that Npgsql can inform the server which WAL files can be removed/recycled. - conn.SetReplicationStatus(message.WalEnd); -} -``` - -Inserting a row will produce the following string messages: - -```output -Message: BEGIN 230413 -Message: table public.blogs: INSERT: id[integer]:2 name[text]:'blog1' -Message: COMMIT 230413 -``` - -> [!WARNING] -> Npgsql internally recycles the message instances it hands out. It is an error to use a message received from `StartReplication` once the next message has been read. - -## Physical replication - -Finally, PostgreSQL also supports physical replication, which streams raw block data rather than logical events on changes. While useful for synchronizing PostgreSQL replicas and supported by Npgsql, this mode is unlikely to be useful for a typical .NET program client. - -## Additional resources - -* See [here](https://event-driven.io/en/push_based_outbox_pattern_with_postgres_logical_replication/) for a great post on implementing the outbox pattern via PostgreSQL logical replication. The outbox pattern guarantees delivery of an event from the database to e.g. a queue. diff --git a/conceptual/Npgsql/security.md b/conceptual/Npgsql/security.md deleted file mode 100644 index 908e3fd0..00000000 --- a/conceptual/Npgsql/security.md +++ /dev/null @@ -1,115 +0,0 @@ -# Security and Encryption - -## Password management - -The simplest way to log into PostgreSQL is by specifying a `Username` and a `Password` in your connection string. Depending on how your PostgreSQL is configured (in the `pg_hba.conf` file), Npgsql will send the password via SASL (SCRAM-SHA-256), in MD5 or in clear-text (not recommended). - -If a `Password` is not specified and your PostgreSQL is configured to request a password, Npgsql will look for a [standard PostgreSQL password file](https://www.postgresql.org/docs/current/static/libpq-pgpass.html). If you specify the `Passfile` connection string parameter, the file it specifies will be used. If that parameter isn't defined, Npgsql will look under the path taken from `PGPASSFILE` environment variable. If the environment variable isn't defined, Npgsql will fall back to the system-dependent default directory which is `$HOME/.pgpass` for Unix and `%APPDATA%\postgresql\pgpass.conf` for Windows. - -### Auth token rotation and dynamic password - -In some cloud scenarios, logging into PostgreSQL is done with an auth token that is rotated every time interval (e.g. one hour). Npgsql has a built-in periodic password provider mechanism, which allows using an up-to-date access token with zero effort: - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder(...); -dataSourceBuilder.UsePasswordProvider( - passwordProvider: _ => throw new NotSupportedException(), - passwordProviderAsync: (builder, token) => /* code to fetch the new access token */); -await using var dataSource = dataSourceBuilder.Build(); -``` - -Every time a new physical connection needs to be opened to PostgreSQL, either the synchronous `passwordProvider` or the asynchronous `passwordProviderAsync` will be called (depending whether you used `Open()` or `OpenAsync()`). Since modern .NET applications are encouraged to always use asynchronous I/O, it's good practice to simply throw in the synchronous password provider, as above. - -Note that since the password provider is invoked *every* time a physical connection is opened, it shouldn't take too long; typically, this would call into a cloud provider API (e.g. Azure Managed Identity), which itself implements a caching mechanism. However, if no such caching is done and the code could take a while, you can instead instruct Npgsql to cache the auth token for a given amount of time: - -```csharp -dataSourceBuilder.UsePeriodicPasswordProvider( - (settings, cancellationToken) => /* async code to fetch the new access token */, - TimeSpan.FromMinutes(55), // Interval for refreshing the token - TimeSpan.FromSeconds(5)); // Interval for retrying after a refresh failure -``` - -Finally, if you already have code running when the auth token changes, you can simply inject it manually at any time into a working data source: - -```csharp -dataSource.Password = ; -``` - -Any physical connection that's opened after this point will use the newly-injected password. - -## GSS session encryption (GSS-API) - -Connections to PostgreSQL are unencrypted by default, but you can turn on session encryption if you wish. Npgsql 10 supports GSS-API for session encryption, and defaults to it if PostgreSQL is set up to support GSS-API (GSS-API is preferred over SSL/TLS). - -To use GSS-API, configure your PostgreSQL for GSS-API session encryption ([docs](https://www.postgresql.org/docs/current/gssapi-enc.html)). Once that's done, you can use `GSS Encryption Mode` in your connection string to configure support (this is similar to the PG [`gccencmode`](https://www.postgresql.org/docs/16/libpq-connect.html#LIBPQ-CONNECT-GSSENCMODE) parameter): - -GSS Encryption Mode | Meaning -------------------- | --------- -Disable | Only try a non-GSSAPI-encrypted connection. -Prefer (default) | If there are GSSAPI credentials present (i.e., in a credentials cache), first try a GSSAPI-encrypted connection; if that fails or there are no credentials, try a non-GSSAPI-encrypted connection. -Require | Only try a GSSAPI-encrypted connection. - -The default mode is `Prefer`, which allows GSS-API session encryption but does not require it. - -> [!NOTE] -> Some Linux environments do not have Kerberos installed; since Npgsql 10.0 defaults to `Prefer`, it will attempt to get GSSAPI credentials, and may generate an error such as the following: -> Cannot load library libgssapi_krb5.so.2: cannot open shared object file: No such file or directory -> Npgsql internally handles this and falls back to connecting without GSSAPI, so the error is harmless. You can specify `GSS Encryption Mode=Disable` to stop Npgsql from trying to use GSSAPI and remove the error. - -## Encryption (SSL/TLS) - -As an alternative to GSS-API, you can use SSL/TLS. First, you have to set up your PostgreSQL to receive SSL/TLS connections [as described here](http://www.postgresql.org/docs/current/static/ssl-tcp.html). Once that's done, specify `SSL Mode` in your connection string as detailed below. - -The following `SSL Mode` values are supported (see the [PostgreSQL docs](https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-SSLMODE-STATEMENTS) for more details): - -SSL Mode | Eavesdropping protection | Man-in-the-middle protection | Statement -------------------- | ------------------------ | ---------------------------- | --------- -Disable | No | No | I don't care about security, and I don't want to pay the overhead of encryption. -Allow | Maybe | No | I don't care about security, but I will pay the overhead of encryption if the server insists on it. -Prefer (default) | Maybe | No | I don't care about encryption, but I wish to pay the overhead of encryption if the server supports it. -Require1 | Yes | No | I want my data to be encrypted, and I accept the overhead. I trust that the network will make sure I always connect to the server I want. -VerifyCA | Yes | Depends on CA policy | I want my data encrypted, and I accept the overhead. I want to be sure that I connect to a server that I trust. -VerifyFull | Yes | Yes | I want my data encrypted, and I accept the overhead. I want to be sure that I connect to a server I trust, and that it's the one I specify. - -The default mode is `Prefer`, which allows SSL but does not require it, and does not validate certificates. - -### SSL Negotiation - -Starting with Npgsql 9.0, you can control how SSL encryption is negotiated while connecting to PostgreSQL via the `SSL Negotiation` connection string parameter, or via the `PGSSLNEGOTIATION` environment variable. In the default `postgres` mode, the client first asks the server if SSL is supported. In `direct` mode, the client starts the standard SSL handshake directly after establishing the TCP/IP connection. - -Enabling this option (by changing it to `direct` mode) can improve latency while opening a physical connection by removing one round trip. - -This option is only supported with PostgreSQL 17 and above. - -### Advanced server certificate validation - -If the root CA of the server certificate isn't installed in your machine's CA store, validation will fail. Either install the certificate in your machine's CA store, or point to it via the `Root Certificate` connection string parameter or via the `PGSSLROOTCERT` environment variable. - -Note that Npgsql does not perform certificate revocation validation by default, since this is an optional extension not implemented by all providers and CAs. To turn on certificate revocation validation, specify `Check Certificate Revocation=true` on the connection string. - -Finally, if the above options aren't sufficient for your scenario, you can call to provide your custom server certificate validation logic (this gets set on the underlying .NET [`SslStream`](https://docs.microsoft.com/dotnet/api/system.net.security.sslstream.-ctor#System_Net_Security_SslStream__ctor_System_IO_Stream_System_Boolean_System_Net_Security_RemoteCertificateValidationCallback_System_Net_Security_LocalCertificateSelectionCallback_)). - -### Client certificates - -PostgreSQL may be configured to require valid certificates from connecting clients for authentication. Npgsql automatically sends client certificates specified in the following places: - -* The `SSL Certificate` connection string parameter. -* The `PGSSLCERT` environment variable. -* The default locations of `~/.postgresql/postgresql.crt` (on Unix) or `%APPDATA%\postgresql\postgresql.crt` (on Windows) - -To provide a password for a client certificate, set either the `SSL Password` (6.0 and higher) or `Client Certificate Key` (5.0 and lower) connection string parameter. - -Finally, you can call , or to programmatically provide a certificate, multiple certificates or a callback which returns certificates (this works like on the underlying .NET [`SslStream`](https://docs.microsoft.com/dotnet/api/system.net.security.sslstream.-ctor#System_Net_Security_SslStream__ctor_System_IO_Stream_System_Boolean_System_Net_Security_RemoteCertificateValidationCallback_System_Net_Security_LocalCertificateSelectionCallback_)). - -> [!NOTE] -> Npgsql supports .PFX and .PEM certificates starting with 6.0. Previously, only .PFX certificates were supported. - -## Password-less authentication (GSS/SSPI/Kerberos) - -Logging in with a username and password may not be ideal, since your application must have access to your password, and raise questions around secret management. An alternate way of authenticating is to use GSS or SSPI to negotiate Kerberos. The advantage of this method is that authentication is handed off to your operating system, using your already-open login session. Your application never needs to handle a password. You can use this method for a Kerberos login, Windows Active Directory or a local Windows session. - -Instructions on setting up Kerberos and SSPI are available in the [PostgreSQL auth methods docs](http://www.postgresql.org/docs/current/static/auth-methods.html). Some more instructions for SSPI are [available here](https://wiki.postgresql.org/wiki/Configuring_for_single_sign-on_using_SSPI_on_Windows). - -Once your PostgreSQL is configured correctly, it will require GSS/SSPI authentication from Npgsql at login, and you can simply drop the `Password` parameter from the connection string. However, Npgsql must still send a username to PostgreSQL. If you specify a `Username` connection string parameter, Npgsql will send that as usual. If you omit it, Npgsql will attempt to detect your system username, including the Kerberos realm. Note that by default, PostgreSQL expects your Kerberos realm to be sent in your username (e.g. `username@REALM`); you can have Npgsql detect the realm by setting `Include Realm` to true in your connection string. Alternatively, you can disable add `include_realm=0` in your PostgreSQL's pg_hba.conf entry, which will make it strip the realm. You always have the possibility of explicitly specifying the username sent to PostgreSQL yourself. - -Note that in versions of Npgsql prior to 8.0, use of GSS/SSPI authentication requires that `Integrated Security=true` be specified on the connection string. This requirement has been removed in Npgsql 8.0. diff --git a/conceptual/Npgsql/toc.yml b/conceptual/Npgsql/toc.yml deleted file mode 100644 index 1e524fda..00000000 --- a/conceptual/Npgsql/toc.yml +++ /dev/null @@ -1,98 +0,0 @@ -- name: Getting Started - href: index.md -- name: Release notes - items: - - name: "11.0" - href: release-notes/11.0.md - - name: "10.0" - href: release-notes/10.0.md - - name: "9.0" - href: release-notes/9.0.md - - name: "8.0" - href: release-notes/8.0.md - - name: Out of support - items: - - name: "7.0" - href: release-notes/7.0.md - - name: "6.0" - href: release-notes/6.0.md - - name: "5.0" - href: release-notes/5.0.md - - name: "4.1" - href: release-notes/4.1.md - - name: "4.0" - href: release-notes/4.0.md - - name: "3.2" - href: release-notes/3.2.md - - name: "3.1" - href: release-notes/3.1.md - - name: "3.0" - href: release-notes/3.0.md -- name: Installation - href: installation.md -- name: Basic usage - href: basic-usage.md -- name: Connection string parameters - href: connection-string-parameters.md -- name: Security and encryption - href: security.md -- name: Type mapping - items: - - name: Basic type mapping - href: types/basic.md - - name: Date and time - href: types/datetime.md - - name: Enums and composites - href: types/enums_and_composites.md - - name: Spatial - items: - - name: NetTopologySuite - href: types/nts.md - - name: GeoJSON - href: types/geojson.md - - name: JSON - href: types/json.md - - name: NodaTime - href: types/nodatime.md -- name: Diagnostics - items: - - name: Overview - href: diagnostics/overview.md - - name: Tracing - href: diagnostics/tracing.md - - name: Logging - href: diagnostics/logging.md - - name: Metrics - href: diagnostics/metrics.md - - name: Exceptions and notices - href: diagnostics/exceptions_notices.md -- name: Performance - href: performance.md -- name: Prepared statements - href: prepare.md -- name: Advanced topics - items: - - name: Failover and load balancing - href: failover-and-load-balancing.md - - name: Bulk copy - href: copy.md - - name: Waiting for notifications - href: wait.md - - name: Keepalive - href: keepalive.md - - name: Replication - href: replication.md -- name: Compatibility notes - href: compatibility.md -- name: FAQ - href: faq.md -- name: API reference - href: "https://www.npgsql.org/doc/api/Npgsql.html" -- name: Developer notes - items: - - name: Release checklist - href: dev/release-checklist.md - - name: Tests - href: dev/tests.md - - name: Type representations - href: dev/type-representations.md diff --git a/conceptual/Npgsql/types/basic.md b/conceptual/Npgsql/types/basic.md deleted file mode 100644 index e458317b..00000000 --- a/conceptual/Npgsql/types/basic.md +++ /dev/null @@ -1,151 +0,0 @@ -# Supported Types and their Mappings - -The following lists the built-in mappings when reading and writing CLR types to PostgreSQL types. - -Note that in addition to the below, enum and composite mappings are documented [in a separate page](enums_and_composites.md). Note also that several plugins exist to add support for more mappings (e.g. spatial support for PostGIS), these are listed in the Types menu. - -## Read mappings - -The following shows the mappings used when reading values. - -* The default type is returned when using `NpgsqlCommand.ExecuteScalar()`, `NpgsqlDataReader.GetValue()` and similar methods. -* You can read as other types by calling `NpgsqlDataReader.GetFieldValue()`. - -PostgreSQL type | Default .NET type | Non-default .NET types ---------------------------- | -------------------------- | ---------------------- -boolean | bool | -smallint | short | byte, sbyte, int, long, float, double, decimal -integer | int | byte, short, long, float, double, decimal -bigint | long | long, byte, short, int, float, double, decimal -real | float | double -double precision | double | -numeric | decimal | byte, short, int, long, float, double, BigInteger (6.0+) -money | decimal | -text | string | char[], byte[]1 -character varying | string | char[], byte[]1 -character | string | char[], byte[]1 -citext | string | char[], byte[]1 -json | string | char[], byte[]1 -jsonb | string | char[], byte[]1 -xml | string | char[], byte[]1 -uuid | Guid | -bytea | byte[]1 | -timestamp without time zone | DateTime (Unspecified) | -timestamp with time zone | DateTime (Utc2) | DateTimeOffset (Offset=0)2 -date | DateTime | DateOnly (6.0+) -time without time zone | TimeSpan | TimeOnly (6.0+) -time with time zone | DateTimeOffset | -interval | TimeSpan3 | -cidr | 4 | -inet | IPAddress | -macaddr | PhysicalAddress | -tsquery | NpgsqlTsQuery | -tsvector | NpgsqlTsVector | -bit(1) | bool | BitArray -bit(n) | BitArray | -bit varying | BitArray | -point | NpgsqlPoint | -lseg | NpgsqlLSeg | -path | NpgsqlPath | -polygon | NpgsqlPolygon | -line | NpgsqlLine | -circle | NpgsqlCircle | -box | NpgsqlBox | -cube | NpgsqlCube5 | -hstore | Dictionary | -oid | uint | -xid | uint | -cid | uint | -oidvector | uint[] | -name | string | char[] -(internal) char | char | byte, short, int, long -geometry (PostGIS) | PostgisGeometry | -record | object[] | -composite types | T | -range types | NpgsqlRange\ | -multirange types (PG14) | NpgsqlRange\[] | -enum types | TEnum | -array types | Array (of element type) | - -1Types which can be read as `byte[]` can also be written as `ReadOnlyMemory` and `Stream`, and if they could be big, consider using `CommandBehavior.SequentialAccess` and `NpgsqlDataReader.GetStream()` to stream the row and column instead of buffering them. Note that if you're reading string data (e.g. `jsonb`) as binary, it's your responsibility to perform UTF8 decoding (or whatever encoding is configured for your database). - -2 In versions prior to 6.0 (or when `Npgsql.EnableLegacyTimestampBehavior` is enabled), reading a `timestamp with time zone` returns a Local DateTime instead of Utc, and reading it as a DateTimeOffset returns a local offset based on the timezone of the server where Npgsql is running. [See the breaking change note for more info](../release-notes/6.0.md#major-changes-to-timestamp-mapping). - -3 PostgreSQL intervals with month or year components cannot be read as `TimeSpan`. Consider using NodaTime's [Period](https://nodatime.org/3.0.x/api/NodaTime.Period.html) type, or . - -4 Prior to version 8.0, the default mapping for `cidr` was `ValueTuple`. - -5 Introduced in Npgsql 10.0.0. Requires the PostgreSQL [`cube`](https://www.postgresql.org/docs/current/cube.html) extension. - -## Write mappings - -There are three rules that determine the PostgreSQL type sent for a parameter: - -1. If the parameter's `NpgsqlDbType` is set, it is used. -2. If the parameter's `DataType` is set, it is used. -3. If the parameter's `DbType` is set, it is used. -4. If none of the above is set, the backend type will be inferred from the CLR value type. - -PostgreSQL type | Default .NET types | Non-default .NET types | NpgsqlDbType | DbType ---------------------------- | ------------------------------------------ | ---------------------------------------- | --------------------- | ------ -boolean | bool | | Boolean | Boolean -smallint | short, byte, sbyte | | Smallint | Int16 -integer | int | | Integer | Int32 -bigint | long | | Bigint | Int64 -real | float | | Real | Single -double precision | double | | Double | Double -numeric | decimal, BigInteger (6.0+) | | Numeric | Decimal, VarNumeric -money | | decimal | Money | Currency -text | string, char[], char | byte[], ReadOnlyMemory\ | Text | String, StringFixedLength, AnsiString, AnsiStringFixedLength -character varying | | string, char[], char, byte[]3 | Varchar | -character | | string, char[], char, byte[]3 | Char | -citext | | string, char[], char, byte[]3 | Citext | -json | | string, char[], char, byte[]3 | Json | -jsonb | | string, char[], char, byte[]3 | Jsonb | -xml | | string, char[], char, byte[]3 | Xml | -uuid | Guid | | Uuid | -bytea | byte[] | ArraySegment\, Stream (7.0+) | Bytea | Binary -timestamp with time zone | DateTime (Utc)1, DateTimeOffset | | TimestampTz | DateTime2, DateTimeOffset -timestamp without time zone | DateTime (Local/Unspecified)1 | | Timestamp | DateTime2 -date | DateOnly (6.0+) | DateTime | Date | Date -time without time zone | TimeOnly (6.0+) | TimeSpan | Time | Time -time with time zone | | DateTimeOffset | TimeTz | -interval | TimeSpan | | Interval | -cidr | | ValueTuple\, IPAddress | Cidr | -inet | IPAddress | ValueTuple\ | Inet | -macaddr | PhysicalAddress | | MacAddr | -tsquery | NpgsqlTsQuery | | TsQuery | -tsvector | NpgsqlTsVector | | TsVector | -bit | | bool, BitArray, string | Bit | -bit varying | BitArray | bool, BitArray, string | Varbit | -point | NpgsqlPoint | | Point | -lseg | NpgsqlLSeg | | LSeg | -path | NpgsqlPath | | Path | -polygon | NpgsqlPolygon | | Polygon | -line | NpgsqlLine | | Line | -circle | NpgsqlCircle | | Circle | -box | NpgsqlBox | | Box | -cube | NpgsqlCube4 | | Cube | -hstore | IDictionary\ | | Hstore | -oid | | uint | Oid | -xid | | uint | Xid | -cid | | uint | Cid | -oidvector | | uint[] | Oidvector | -name | | string, char[], char | Name | -(internal) char | | byte | InternalChar | -composite types | Pre-mapped type | | Composite | -range types | NpgsqlRange\ | | Range \| NpgsqlDbType | -enum types | Pre-mapped type | | Enum | -array types | T[], List\ | | Array \| NpgsqlDbType | - -1 UTC DateTime is written as `timestamp with time zone`, Local/Unspecified DateTimes are written as `timestamp without time zone`. In versions prior to 6.0 (or when `Npgsql.EnableLegacyTimestampBehavior` is enabled), DateTime is always written as `timestamp without time zone`. - -2In versions prior to 6.0 (or when `Npgsql.EnableLegacyTimestampBehavior` is enabled), `DbType.DateTime` is mapped to `timestamp without time zone`. - -3Types which can be read as `byte[]` can also be written as `ReadOnlyMemory` and `Stream`. - -4 Introduced in Npgsql 10.0.0. Requires the PostgreSQL [`cube`](https://www.postgresql.org/docs/current/cube.html) extension. - -Notes when using Range and Array, bitwise-or NpgsqlDbType.Range or NpgsqlDbType.Array with the child type. For example, to construct the NpgsqlDbType for a `int4range`, write `NpgsqlDbType.Range | NpgsqlDbType.Integer`. To construct the NpgsqlDbType for an `int[]`, write `NpgsqlDbType.Array | NpgsqlDbType.Integer`. - -For information about enums, [see the Enums and Composites page](enums_and_composites.md). diff --git a/conceptual/Npgsql/types/datetime.md b/conceptual/Npgsql/types/datetime.md deleted file mode 100644 index 6718df18..00000000 --- a/conceptual/Npgsql/types/datetime.md +++ /dev/null @@ -1,81 +0,0 @@ -# Date and Time Handling - -> [!WARNING] -> Npgsql 6.0 introduced some important changes to how timestamps are mapped, [see the release notes for more information](../release-notes/6.0.md). - -> [!NOTE] -> The recommended way of working with date/time types is [the NodaTime plugin](nodatime.md): the NodaTime types are much better-designed, avoid the flaws in the built-in BCL types, and are fully supported by Npgsql. - -Handling date and time values usually isn't hard, but you must pay careful attention to differences in how the .NET types and PostgreSQL represent dates. It's worth reading the [PostgreSQL date/time type documentation](http://www.postgresql.org/docs/current/static/datatype-datetime.html) to familiarize yourself with PostgreSQL's types. - -## .NET types and PostgreSQL types - -The .NET and PostgreSQL types differ in the resolution and range they provide; the .NET type usually have a higher resolution but a lower range than the PostgreSQL types: - -PostgreSQL type | Precision/Range | .NET Native Type | Precision/Range -----------------------------|-------------------------------------------|------------------------------|---------------- -timestamp with time zone | 1 microsecond, 4713BC-294276AD | DateTime (UTC) | 100 nanoseconds, 1AD-9999AD -timestamp without time zone | 1 microsecond, 4713BC-294276AD | DateTime (Unspecified) | 100 nanoseconds, 1AD-9999AD -date | 1 day, 4713BC-5874897AD | DateOnly (6.0+), DateTime | 100 nanoseconds, 1AD-9999AD -time without time zone | 1 microsecond, 0-24 hours | TimeOnly (6.0+), TimeSpan | 100 nanoseconds, -10,675,199 - 10,675,199 days -time with time zone | 1 microsecond, 0-24 hours | DateTimeOffset (ignore date) | 100 nanoseconds, 1AD-9999AD -interval | 1 microsecond, -178000000-178000000 years | TimeSpan | 100 nanoseconds, -10,675,199 - 10,675,199 days - -For almost all applications, the range of the .NET native types (or the NodaTime types) are more than sufficient. In the rare cases where you need to access values outside these ranges, timestamps can be accessed as `long`, dates as `int`, and intervals as `NpgsqlInterval`. These are the raw PostgreSQL binary representations of these type, so you'll have to deal with encoding/decoding yourself. - -## Timestamps and timezones - -> [!Warning] -> A common mistake is for users to think that the PostgreSQL `timestamp with time zone` type stores the timezone in the database. This is not the case: only a UTC timestamp is stored. There is no single PostgreSQL type that stores both a date/time and a timezone, similar to [.NET DateTimeOffset](https://msdn.microsoft.com/en-us/library/system.datetimeoffset(v=vs.110).aspx). To store a timezone in the database, add a separate text column containing the timezone ID. - -In PostgreSQL, `timestamp with time zone` represents a UTC timestamp, while `timestamp without time zone` represents a local or unspecified time zone. Starting with 6.0, Npgsql maps UTC DateTime to `timestamp with time zone`, and Local/Unspecified DateTime to `timestamp without time zone`; trying to send a non-UTC DateTime as `timestamptz` will throw an exception, etc. Npgsql also supports reading and writing DateTimeOffset to `timestamp with time zone`, but only with Offset=0. Prior to 6.0, `timestamp with time zone` would be converted to a local timestamp when read - see below for more details. The precise improvements and breaking changes are detailed in the [6.0 breaking changes](../release-notes/6.0.md#timestamp-rationalization-and-improvements); to revert to the pre-6.0 behavior, add the following at the start of your application, before any Npgsql operations are invoked: - -```csharp -AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); -``` - -Use of the `time with time zone` type is discouraged, [see the PostgreSQL documentation](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-TIMEZONES). You can use a `DateTimeOffset` to read and write values - the date component will be ignored. - -## Infinity values - -PostgreSQL supports the special values `-infinity` and `infinity` for the timestamp and date types ([see docs](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-DATETIME-SPECIAL-VALUES)); these can be useful to represent a value which is earlier or later than any other value. Starting with Npgsql 6.0, these special values are mapped to the `MinValue` and `MaxValue` value on the corresponding .NET types (`DateTime` and `DateOnly`, NodaTime `Instant` and `LocalDate`). To opt out of this behavior, set the following AppContext switch at the start of your application: - -```csharp -AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true); -``` - -Note: in versions prior to 6.0, the connection string parameter `Convert Infinity DateTime` could be used to opt into these infinity conversions. That connection string parameter has been removed. - -## Detailed Behavior: Reading values from the database - -PostgreSQL type | Default .NET type | Non-default .NET types ---------------------------- | ---------------------------- | ---------------------- -timestamp with time zone | DateTime (Utc1) | DateTimeOffset (Offset=0)2 -timestamp without time zone | DateTime (Unspecified) | -date | DateOnly (10.0+)3 | DateTime -time without time zone | TimeOnly (10.0+)3 | TimeSpan -time with time zone | DateTimeOffset | -interval | TimeSpan (4) | - -1 In versions prior to 6.0 (or when `Npgsql.EnableLegacyTimestampBehavior` is enabled), reading a `timestamp with time zone` returns a Local DateTime instead of Utc. [See the breaking change note for more info](../release-notes/6.0.md#major-changes-to-timestamp-mapping). - -2 In versions prior to 6.0 (or when `Npgsql.EnableLegacyTimestampBehavior` is enabled), reading a `timestamp with time zone` as a DateTimeOffset returns a local offset based on the timezone of the server where Npgsql is running. - -3 In versions prior to 10.0, reading `date` and `time` returned .NET `DateTime` and `TimeSpan` by default (although reading `DateOnly` and `TimeOnly` was possible). To switch back to the old behavior, see the [10.0 breaking change note](../release-notes/10.0.md#date-and-time-are-now-mapped-to-dateonly-and-timeonly). - -4 PostgreSQL intervals with month or year components cannot be read as TimeSpan. Consider using NodaTime's [Period](https://nodatime.org/3.0.x/api/NodaTime.Period.html) type, or . - -## Detailed Behavior: Sending values to the database - -PostgreSQL type | Default .NET types | Non-default .NET types | NpgsqlDbType | DbType ---------------------------- | ------------------------------------------ | --------------------------------------- | --------------------- | ------ -timestamp with time zone | DateTime (Utc)1, DateTimeOffset | | TimestampTz | DateTime2, DateTimeOffset -timestamp without time zone | DateTime (Local/Unspecified)1 | | Timestamp | DateTime2 -date | DateOnly (6.0+) | DateTime | Date | Date -time without time zone | TimeOnly (6.0+) | TimeSpan | Time | Time -time with time zone | | DateTimeOffset | TimeTz | -interval | TimeSpan | | Interval | - -1 UTC DateTime is written as `timestamp with time zone`, Local/Unspecified DateTimes are written as `timestamp without time zone`. In versions prior to 6.0 (or when `Npgsql.EnableLegacyTimestampBehavior` is enabled), DateTime is always written as `timestamp without time zone`. - -2In versions prior to 6.0 (or when `Npgsql.EnableLegacyTimestampBehavior` is enabled), `DbType.DateTime` is mapped to `timestamp without time zone`. diff --git a/conceptual/Npgsql/types/enums_and_composites.md b/conceptual/Npgsql/types/enums_and_composites.md deleted file mode 100644 index 5bea4d6a..00000000 --- a/conceptual/Npgsql/types/enums_and_composites.md +++ /dev/null @@ -1,155 +0,0 @@ -# PostgreSQL enums and composites - -PostgreSQL supports [enum types](http://www.postgresql.org/docs/current/static/datatype-enum.html) and [composite types](http://www.postgresql.org/docs/current/static/rowtypes.html) as database columns, and Npgsql supports reading and writing these. This allows you to seamlessly read and write enum and composite values to the database without worrying about conversions. - -## Creating your types - -Let's assume you've created some enum and composite types in PostgreSQL: - -```sql -CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy'); - -CREATE TYPE inventory_item AS ( - name text, - supplier_id integer, - price numeric -); -``` - -To use these types with Npgsql, you must first define corresponding CLR types that will be mapped to the PostgreSQL types: - -```csharp -public enum Mood -{ - Sad, - Ok, - Happy -} - -public class InventoryItem -{ - public string Name { get; set; } = ""; - public int SupplierId { get; set; } - public decimal Price { get; set; } -} -``` - -## Mapping your CLR types - -Once your types are defined both in PostgreSQL and in C#, you can now configure the mapping between them with Npgsql. - -### [NpgsqlDataSource](#tab/datasource) - -> [!NOTE] -> `NpgsqlDataSource` was introduced in Npgsql 7.0, and is the recommended way to manage type mapping. If you're using an older version, see the other methods. - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder(...); -dataSourceBuilder.MapEnum(); -dataSourceBuilder.MapComposite(); -await using var dataSource = dataSourceBuilder.Build(); -``` - -### [Global mapping](#tab/global) - -If you're using an older version of Npgsql which doesn't yet support `NpgsqlDataSource`, you can configure mappings globally for all connections in your application: - -```csharp -NpgsqlConnection.GlobalTypeMapper.MapEnum(); -NpgsqlConnection.GlobalTypeMapper.MapComposite(); -``` - -For this to work, you must place this code at the beginning of your application, before any other Npgsql API is called. Note that in Npgsql 7.0, global type mappings are obsolete (but still supported) - `NpgsqlDataSource` is the recommended way to manage type mappings. - -### [Connection mapping](#tab/connection) - -> [!NOTE] -> This mapping method has been removed in Npgsql 7.0. - -Older versions of Npgsql supported configuring a type mapping on an individual connection, as follows: - -```csharp -var conn = new NpgsqlConnection(...); -conn.TypeMapper.MapEnum(); -conn.TypeMapper.MapComposite(); -``` - -*** - -Whatever the method used, your CLR types `Mood` and `InventoryItem` are now mapped to the PostgreSQL types `mood` and `inventory_item`. - -## Using your mapped types - -Once your mapping is in place, you can read and write your CLR types as usual: - -```csharp -// Writing -await using (var cmd = new NpgsqlCommand("INSERT INTO some_table (my_enum, my_composite) VALUES ($1, $2)", conn)) -{ - cmd.Parameters.Add(new() { Value = Mood.Happy }); - cmd.Parameters.Add(new() - { - Value = new InventoryItem { ... } - }); - cmd.ExecuteNonQuery(); -} - -// Reading -await using (var cmd = new NpgsqlCommand("SELECT my_enum, my_composite FROM some_table", conn)) -await using (var reader = cmd.ExecuteReader()) { - reader.Read(); - var enumValue = reader.GetFieldValue(0); - var compositeValue = reader.GetFieldValue(1); -} -``` - -Note that your PostgreSQL enum and composites types (`mood` and `inventory_data` in the sample above) must be defined in your database before the first connection is created (see `CREATE TYPE`). If you're creating PostgreSQL types within your program, call `NpgsqlConnection.ReloadTypes()` to make sure Npgsql becomes properly aware of them. - -[When preparing commands](../prepare.md), you need to specify the database type of parameters without specifying an actual parameter value. This is usually done via the enum; but since enums and composites are user-defined types, they have no labels in that enum. Instead, set the property on the parameter to the name of your type ([see these docs for more information on parameter types](../basic-usage.md#parameter-types)). - -## Name translation - -CLR type and field names are usually Pascal case (e.g. `InventoryData`), whereas in PostgreSQL they are snake case (e.g. `inventory_data`). To help make the mapping for enums and composites seamless, pluggable name translators are used translate all names. The default translation scheme is `NpgsqlSnakeCaseNameTranslator`, which maps names like `SomeType` to `some_type`, but you can specify others. The default name translator can be set for all your connections via `NpgsqlConnection.GlobalTypeMapper.DefaultNameTranslator`, or for a specific connection for `NpgsqlConnection.TypeMapper.DefaultNameTranslator`. You also have the option of specifying a name translator when setting up a mapping: - -```csharp -NpgsqlConnection.GlobalTypeMapper.MapComposite("inventory_data", new NpgsqlNullNameTranslator()); -``` - -Finally, you may control mappings on a field-by-field basis via the `[PgName]` attribute. This overrides the name translator. - -```csharp -public enum Mood -{ - [PgName("depressed")] - Sad, - Ok, - [PgName("ebullient")] - Happy -} -``` - -## Reading and writing unmapped enums - -In some cases, it may be desirable to interact with PostgreSQL enums without a pre-existing CLR enum type - this is useful mainly if your program doesn't know the database schema and types in advance, and needs to interact with any enum/composite type. - -Npgsql allows reading and writing enums as simple strings: - -```csharp -// Writing enum as string -await using (var cmd = new NpgsqlCommand("INSERT INTO some_table (my_enum) VALUES ($1)", conn)) -{ - cmd.Parameters.Add(new() - { - Value = "Happy" - DataTypeName = "mood" - }); - cmd.ExecuteNonQuery(); -} - -// Reading enum as string -await using (var cmd = new NpgsqlCommand("SELECT my_enum FROM some_table", conn)) -await using (var reader = cmd.ExecuteReader()) { - reader.Read(); - var enumValue = reader.GetFieldValue(0); -} -``` diff --git a/conceptual/Npgsql/types/geojson.md b/conceptual/Npgsql/types/geojson.md deleted file mode 100644 index 070c54e7..00000000 --- a/conceptual/Npgsql/types/geojson.md +++ /dev/null @@ -1,87 +0,0 @@ -# PostGIS/GeoJSON Type Plugin - -The [Npgsql.GeoJSON](https://nuget.org/packages/Npgsql.GeoJSON) plugin makes Npgsql read and write PostGIS spatial types as [GeoJSON (RFC7946) types](http://geojson.org/), via the [GeoJSON.NET](https://github.com/GeoJSON-Net/GeoJSON.Net) library. - -As an alternative, you can use [Npgsql.NetTopologySuite](nts.md), which is a full-fledged .NET spatial library with many features. - -## Setup - -To avoid forcing a dependency on the GeoJSON library for users not using spatial, GeoJSON support is delivered as a separate plugin. To use the plugin, simply add a dependency on [Npgsql.GeoJSON](https://www.nuget.org/packages/Npgsql.GeoJSON) and set it up in one of the following ways: - -### [NpgsqlDataSource](#tab/datasource) - -> [!NOTE] -> `NpgsqlDataSource` was introduced in Npgsql 7.0, and is the recommended way to manage type mapping. If you're using an older version, see the other methods. - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder(...); -dataSourceBuilder.UseGeoJson(); -await using var dataSource = dataSourceBuilder.Build(); -``` - -### [Global mapping](#tab/global) - -If you're using an older version of Npgsql which doesn't yet support `NpgsqlDataSource`, you can configure mappings globally for all connections in your application: - -```csharp -NpgsqlConnection.GlobalTypeMapper.UseGeoJson(); -``` - -For this to work, you must place this code at the beginning of your application, before any other Npgsql API is called. Note that in Npgsql 7.0, global type mappings are obsolete (but still supported) - `NpgsqlDataSource` is the recommended way to manage type mappings. - -### [Connection mapping](#tab/connection) - -> [!NOTE] -> This mapping method has been removed in Npgsql 7.0. - -Older versions of Npgsql supported configuring a type mapping on an individual connection, as follows: - -```csharp -var conn = new NpgsqlConnection(...); -conn.TypeMapper.UseGeoJson(); -``` - -*** - -## Reading and Writing Geometry Values - -When reading PostGIS values from the database, Npgsql will automatically return the appropriate GeoJSON types: `Point`, `LineString`, and so on. Npgsql will also automatically recognize GeoJSON's types in parameters, and will automatically send the corresponding PostGIS type to the database. The following code demonstrates a roundtrip of a GeoJSON `Point` to the database: - -```csharp -conn.ExecuteNonQuery("CREATE TEMP TABLE data (geom GEOMETRY)"); - -await using (var cmd = new NpgsqlCommand("INSERT INTO data (geom) VALUES ($1)", conn)) -{ - cmd.Parameters.Add(new() { Value = new Point(new Position(51.899523, -2.124156)) }); - await cmd.ExecuteNonQueryAsync(); -} - -await using (var cmd = new NpgsqlCommand("SELECT geom FROM data", conn)) -await using (var reader = await cmd.ExecuteReaderAsync()) -{ - await reader.ReadAsync(); - var point2 = reader.GetFieldValue(0); -} -``` - -You may also explicitly specify a parameter's type by setting `NpgsqlDbType.Geometry`. - -## Geography (geodetic) Support - -PostGIS has two types: `geometry` (for Cartesian coordinates) and `geography` (for geodetic or spherical coordinates). You can read about the geometry/geography distinction [in the PostGIS docs](https://postgis.net/docs/manual-2.4/using_postgis_dbmanagement.html#PostGIS_Geography) or in [this blog post](http://workshops.boundlessgeo.com/postgis-intro/geography.html). In a nutshell, `geography` is much more accurate when doing calculations over long distances, but is more expensive computationally and supports only a small subset of the spatial operations supported by `geometry`. - -Npgsql uses the same GeoJSON types to represent both `geometry` and `geography` - the `Point` type represents a point in either Cartesian or geodetic space. You usually don't need to worry about this distinction because PostgreSQL will usually cast types back and forth as needed. However, it's worth noting that Npgsql sends Cartesian `geometry` by default, because that's the usual requirement. You have the option of telling Npgsql to send `geography` instead by specifying `NpgsqlDbType.Geography`: - -```csharp -using (var cmd = new NpgsqlCommand("INSERT INTO data (geog) VALUES ($1)", conn)) -{ - cmd.Parameters.Add(new() { Value = point, NpgsqlDbType = NpgsqlDbType.Geography }); - await cmd.ExecuteNonQueryAsync(); -} -``` - -If you prefer to use `geography` everywhere by default, you can also specify that when setting up the plugin: - -```csharp -dataSourceBuilder.UseGeoJson(geographyAsDefault: true); -``` diff --git a/conceptual/Npgsql/types/json.md b/conceptual/Npgsql/types/json.md deleted file mode 100644 index fc1a4db3..00000000 --- a/conceptual/Npgsql/types/json.md +++ /dev/null @@ -1,226 +0,0 @@ -# Mapping JSON - -> [!NOTE] -> If you're using EF Core, please read the page on [JSON support in the EF provider](../../EFCore.PG/mapping/json.md). EF has specialized support for JSON beyond what is supported at the lower-level Npgsql layer. - -PostgreSQL has rich, built-in support for storing JSON columns and efficiently performing complex queries operations on them. Newcomers can read more about the PostgreSQL support on [the JSON types page](https://www.postgresql.org/docs/current/datatype-json.html), and on the [functions and operators page](https://www.postgresql.org/docs/current/functions-json.html). Note that the below mapping mechanisms support both the `jsonb` and `json` types, although the former is almost always preferred for efficiency and functionality reasons. - -Npgsql allows you to map PostgreSQL JSON columns in three different ways: - -1. As simple strings -2. As strongly-typed user-defined types (POCOs) -3. As System.Text.Json DOM types (JsonDocument or JsonElement, [see docs](https://learn.microsoft.com/dotnet/standard/serialization/system-text-json/use-dom#use-jsondocument)) -4. High-performance JSON parsing with [Utf8JsonReader](https://learn.microsoft.com/dotnet/standard/serialization/system-text-json/use-utf8jsonreader) -5. Newtonsoft Json.NET - -## String mapping - -The simplest form of mapping to JSON is as a regular .NET string: - -```csharp -// Write a string to a json column: -await using var command1 = new NpgsqlCommand("INSERT INTO test (data) VALUES ($1)", conn) -{ - Parameters = { new() { Value = """{ "a": 8, "b": 9 }""", NpgsqlDbType = NpgsqlDbType.Jsonb } } -}; -await command1.ExecuteNonQueryAsync(); - -// Read jsonb data as a string: -await using var command2 = new NpgsqlCommand("SELECT data FROM test", conn); -await using var reader = await command2.ExecuteReaderAsync(); -while (await reader.ReadAsync()) -{ - Console.WriteLine(reader.GetString(0)); -} -``` - -> [!NOTE] -> Note that when writing a string parameter as `jsonb`, you must specify `NpgsqlDbType.Jsonb`, otherwise Npgsql sends a `text` parameter which is incompatible with JSON. - -With this mapping style, you're fully responsible for serializing/deserializing the JSON data yourself (e.g. with System.Text.Json) - Npgsql simply passes your strings to and from PostgreSQL. - -## POCO mapping - -> [!WARNING] -> As of Npgsql 8.0, POCO mapping is incompatible with NativeAOT. We plan to improve this, [please upvote this issue if you're interested](https://github.com/npgsql/npgsql/issues/5355). - -If your column JSON contains documents with a stable schema, you can map them to your own .NET types (or POCOs). The provider will use System.Text.Json APIs under the hood to serialize instances of your types to JSON documents before sending them to the database, and to deserialize documents coming back from the database. This effectively allows mapping an arbitrary .NET type - or object graph - to a single column in the database. - -Starting with Npgsql 8.0, to use this feature, you must first enable it by calling on your , or, if you're not yet using data sources, on `NpgsqlConnection.GlobalTypeMapper`: - -### [NpgsqlDataSource](#tab/datasource) - -> [!NOTE] -> `NpgsqlDataSource` was introduced in Npgsql 7.0, and is the recommended way to manage type mapping. If you're using an older version, see the other methods. - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder(...); -dataSourceBuilder.EnableDynamicJson(); -await using var dataSource = dataSourceBuilder.Build(); -``` - -### [Global mapping](#tab/global) - -If you're not yet using `NpgsqlDataSource`, you can configure mappings globally for all connections in your application: - -```csharp -NpgsqlConnection.GlobalTypeMapper.EnableDynamicJson(); -``` - -For this to work, you must place this code at the beginning of your application, before any other Npgsql API is called. Note that in Npgsql 7.0, global type mappings are obsolete (but still supported) - `NpgsqlDataSource` is the recommended way to manage type mappings. - -*** - -Once you've enabled the feature, you can simply read and write instances of your POCOs directly; when writing, specify `NpgsqlDbType.Jsonb` to let Npgsql know you intend for it to get sent as JSON data: - -```csharp -// Write a POCO to a jsonb column: -var myPoco1 = new MyPoco { A = 8, B = 9 }; - -await using var command1 = new NpgsqlCommand("INSERT INTO test (data) VALUES ($1)", conn) -{ - Parameters = { new() { Value = myPoco1, NpgsqlDbType = NpgsqlDbType.Jsonb } } -}; -await command1.ExecuteNonQueryAsync(); - -// Read jsonb data as a POCO: -await using var command2 = new NpgsqlCommand("SELECT data FROM test", conn); -await using var reader = await command2.ExecuteReaderAsync(); -while (await reader.ReadAsync()) -{ - var myPoco2 = reader.GetFieldValue(0); - Console.WriteLine(myPoco2.A); -} - -class MyPoco -{ - public int A { get; set; } - public int B { get; set; } -} -``` - -This mapping method is quite powerful, allowing you to read and write nested graphs of objects and arrays to PostgreSQL without having to deal with serialization yourself. - -### Polymorphic JSON mapping - -Npgsql uses System.Text.Json to perform the actual serialization and deserialization of your POCO types to JSON. System.Text.Json support [`polymorphioc serialization`](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/polymorphism), which allows serializing type hierarchies, using a JSON `$type` property as the type discriminator. - -If you're using the `json` type, you can use System.Text.Json's polymorphic serialization without any extra steps. However, if you're using `jsonb` (which is generally recommended), then you'll run into trouble: System.Text.Json requires that the `$type` property be at the top of the JSON document, but `jsonb` does **not** preserve property order in JSON objects. - -System.Text.Json 9.0 brings support for [out-of-order metadata reads](https://devblogs.microsoft.com/dotnet/system-text-json-in-dotnet-9/#out-of-order-metadata-reads), which is an opt-in feature allowing the `$type` property to be anywhere in the JSON object. When using Npgsql, you can opt into this when configuring your as follows: - -```c# -var builder = new NpgsqlDataSourceBuilder(""); -builder - .EnableDynamicJson() - .ConfigureJsonOptions(new JsonSerializerOptions { AllowOutOfOrderMetadataProperties = true }); -await using var dataSource = builder.Build(); -``` - -Once that's done, you can use JSON polymorphism with `jsonb`. If you're still targeting .NET 8.0, you can take a reference on System.Text.Json 9.0 in order to use `AllowOutOfOrderMetadataProperties`. - -## System.Text.Json DOM types - -There are cases in which mapping JSON data to POCOs isn't appropriate; for example, your JSON column may not contain a fixed schema and must be inspected to see what it contains; for these cases, Npgsql supports mapping JSON data to [JsonDocument](https://docs.microsoft.com/dotnet/api/system.text.json.jsondocument) or [JsonElement](https://docs.microsoft.com/dotnet/api/system.text.json.jsonelement) ([see docs](https://learn.microsoft.com/dotnet/standard/serialization/system-text-json/use-dom#use-jsondocument)): - -```csharp -var jsonDocument = JsonDocument.Parse("""{ "a": 8, "b": 9 }"""); - -// Write a JsonDocument: -await using var command1 = new NpgsqlCommand("INSERT INTO test (data) VALUES ($1)", conn) -{ - Parameters = { new() { Value = jsonDocument } } -}; -await command1.ExecuteNonQueryAsync(); - -// Read jsonb data as a JsonDocument: -await using var command2 = new NpgsqlCommand("SELECT data FROM test", conn); -await using var reader = await command2.ExecuteReaderAsync(); -while (await reader.ReadAsync()) -{ - var document = reader.GetFieldValue(0); - Console.WriteLine(document.RootElement.GetProperty("a").GetInt32()); -} -``` - -## High-performance JSON parsing with Utf8JsonReader - -If you're writing a very performance-sensitive application, using System.Text.Json to deserialize to POCOs or JsonDocument may incur too much overhead. If that's the case, you can use System.Text.Json's [Utf8JsonReader](https://learn.microsoft.com/dotnet/standard/serialization/system-text-json/use-utf8jsonreader) to parse JSON data from the database. Utf8JsonReader provides a low-level, forward-only API to parse the JSON data, one token at a time. - -Utf8JsonReader requires JSON data as raw, UTF8-encoded binary data; fortunately, Npgsql allows reading `jsonb` as binary data, and if your PostgreSQL `client_encoding` is set to UTF8 (the default), you can feed data directly from PostgreSQL to Utf8JsonReader: - -```csharp -await using var command2 = new NpgsqlCommand("SELECT data FROM test", conn); -await using var reader = await command2.ExecuteReaderAsync(); -while (await reader.ReadAsync()) -{ - ParseJson(reader.GetFieldValue(0)); -} - -void ParseJson(byte[] utf8Data) -{ - var jsonReader = new Utf8JsonReader(utf8Data); - // ... parse the data with jsonReader -} -``` - -Note that the above works well for small JSON columns; if you have large columns (above ~8k), consider streaming the JSON data instead. This can be done by passing `CommandBehavior.SequentialAccess` to `ExecuteReaderAsync`, and then calling `reader.GetStream()` on NpgsqlDataReader instead of `GetFieldValue`. To process streaming data with Utf8JsonReader, [see these docs](https://learn.microsoft.com/dotnet/standard/serialization/system-text-json/use-utf8jsonreader#read-from-a-stream-using-utf8jsonreader). - -## Newtonsoft.JSON - -System.Text.Json is the built-in, standard way to handle JSON in modern .NET. However, some users still prefer using Newtonoft Json.NET, and Npgsql includes support for that. - -To use Json.NET, add the [Npgsql.Json.NET package](https://www.nuget.org/packages/Npgsql.Json.NET) to your project, and enable the plugin as follows: - -### [NpgsqlDataSource](#tab/datasource) - -> [!NOTE] -> `NpgsqlDataSource` was introduced in Npgsql 7.0, and is the recommended way to manage type mapping. If you're using an older version, see the other methods. - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder(...); -dataSourceBuilder.UseJsonNet(); -await using var dataSource = dataSourceBuilder.Build(); -``` - -### [Global mapping](#tab/global) - -If you're using an older version of Npgsql which doesn't yet support `NpgsqlDataSource`, you can configure mappings globally for all connections in your application: - -```csharp -NpgsqlConnection.GlobalTypeMapper.UseJsonNet(); -``` - -For this to work, you must place this code at the beginning of your application, before any other Npgsql API is called. Note that in Npgsql 7.0, global type mappings are obsolete (but still supported) - `NpgsqlDataSource` is the recommended way to manage type mappings. - -*** - -Once you've enabled the feature, you can simply read and write instances of your POCOs directly; when writing, specify `NpgsqlDbType.Jsonb` to let Npgsql know you intend for it to get sent as JSON data: - -```csharp -// Write a POCO to a jsonb column: -var myPoco1 = new MyPoco { A = 8, B = 9 }; - -await using var command1 = new NpgsqlCommand("INSERT INTO test (data) VALUES ($1)", conn) -{ - Parameters = { new() { Value = myPoco1, NpgsqlDbType = NpgsqlDbType.Jsonb } } -}; -await command1.ExecuteNonQueryAsync(); - -// Read jsonb data as a POCO: -await using var command2 = new NpgsqlCommand("SELECT data FROM test", conn); -await using var reader = await command2.ExecuteReaderAsync(); -while (await reader.ReadAsync()) -{ - var myPoco2 = reader.GetFieldValue(0); - Console.WriteLine(myPoco2.A); -} - -class MyPoco -{ - public int A { get; set; } - public int B { get; set; } -} -``` - -The plugin also allows you to read JObject/JArray for weakly-typed DOM mapping. diff --git a/conceptual/Npgsql/types/nodatime.md b/conceptual/Npgsql/types/nodatime.md deleted file mode 100644 index bd72f0cd..00000000 --- a/conceptual/Npgsql/types/nodatime.md +++ /dev/null @@ -1,104 +0,0 @@ -# NodaTime Type Plugin - -Npgsql provides a plugin that allows mapping the [NodaTime](http://nodatime.org) date/time library; this is the recommended way to interact with PostgreSQL date/time types, rather than the built-in .NET types. - -## What is NodaTime - -By default, [the PostgreSQL date/time types](https://www.postgresql.org/docs/current/static/datatype-datetime.html) are mapped to the built-in .NET types (`DateTime`, `TimeSpan`). Unfortunately, these built-in types are flawed in many ways. The [NodaTime library](http://nodatime.org/) was created to solve many of these problems, and if your application handles dates and times in anything but the most basic way, you should consider using it. To learn more [read this blog post by Jon Skeet](http://blog.nodatime.org/2011/08/what-wrong-with-datetime-anyway.html). - -Beyond NodaTime's general advantages, some specific advantages NodaTime for PostgreSQL date/time mapping include: - -* NodaTime's types map very cleanly to the PostgreSQL types. For example `Instant` corresponds to `timestamptz`, and `LocalDateTime` corresponds to `timestamp without time zone`. The BCL's DateTime can correspond to both, depending on its type; this can create confusion and errors. -* `Period` is much more suitable for mapping PostgreSQL `interval` than `TimeSpan`. -* NodaTime types can fully represent PostgreSQL's microsecond precision, and can represent dates outside the BCL's date limit (1AD-9999AD). - -## Setup - -To avoid forcing a dependency on the NodaTime library for users not using it, NodaTime support is delivered as a separate plugin. To use the plugin, simply add a dependency on [Npgsql.NodaTime](https://www.nuget.org/packages/Npgsql.NodaTime) and set it up in one of the following ways: - -### [NpgsqlDataSource](#tab/datasource) - -> [!NOTE] -> `NpgsqlDataSource` was introduced in Npgsql 7.0, and is the recommended way to manage type mapping. If you're using an older version, see the other methods. - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder(...); -dataSourceBuilder.UseNodaTime(); -await using var dataSource = dataSourceBuilder.Build(); -``` - -### [Global mapping](#tab/global) - -If you're using an older version of Npgsql which doesn't yet support `NpgsqlDataSource`, you can configure mappings globally for all connections in your application: - -```csharp -NpgsqlConnection.GlobalTypeMapper.UseNodaTime(); -``` - -For this to work, you must place this code at the beginning of your application, before any other Npgsql API is called. Note that in Npgsql 7.0, global type mappings are obsolete (but still supported) - `NpgsqlDataSource` is the recommended way to manage type mappings. - -### [Connection mapping](#tab/connection) - -> [!NOTE] -> This mapping method has been removed in Npgsql 7.0. - -Older versions of Npgsql supported configuring a type mapping on an individual connection, as follows: - -```csharp -var conn = new NpgsqlConnection(...); -conn.TypeMapper.UseNodaTime(); -``` - -*** - -## Reading and Writing Values - -Once the plugin is set up, you can transparently read and write NodaTime objects: - -```csharp -// Write NodaTime Instant to PostgreSQL "timestamp with time zone" (UTC) -await using (var cmd = new NpgsqlCommand(@"INSERT INTO mytable (my_timestamptz) VALUES ($1)", conn)) -{ - cmd.Parameters.Add(new() { Value = Instant.FromUtc(2011, 1, 1, 10, 30) }); - await cmd.ExecuteNonQueryAsync(); -} - -// Read timestamp back from the database as an Instant -await using (var cmd = new NpgsqlCommand(@"SELECT my_timestamptz FROM mytable", conn)) -await using (var reader = await cmd.ExecuteReaderAsync()) -{ - await reader.ReadAsync(); - var instant = reader.GetFieldValue(0); -} -``` - -## Mapping Table - -> [!Warning] -> A common mistake is for users to think that the PostgreSQL `timestamp with time zone` type stores the timezone in the database. This is not the case: only a UTC timestamp is stored. There is no single PostgreSQL type that stores both a date/time and a timezone, similar to [.NET DateTimeOffset](https://msdn.microsoft.com/en-us/library/system.datetimeoffset(v=vs.110).aspx). To store a timezone in the database, add a separate text column containing the timezone ID. - -PostgreSQL Type | Default NodaTime Type | Additional NodaTime Type | Notes -------------------------------- | --------------------------------------------------------------------------------------- | ----------------------------- | ------ -timestamp with time zone | [Instant](https://nodatime.org/3.0.x/api/NodaTime.Instant.html) | [ZonedDateTime](https://nodatime.org/3.0.x/api/NodaTime.ZonedDateTime.html)1, [OffsetDateTime](https://nodatime.org/3.0.x/api/NodaTime.OffsetDateTime.html)1 | A UTC timestamp in the database. Only UTC ZonedDateTime and OffsetDateTime are supported. -timestamp without time zone | [LocalDateTime](https://nodatime.org/3.0.x/api/NodaTime.LocalDateTime.html)2 | | A timestamp in an unknown or implicit time zone. -date | [LocalDate](https://nodatime.org/3.0.x/api/NodaTime.LocalDate.html) | | A simple date with no timezone or offset information. -time without time zone | [LocalTime](https://nodatime.org/3.0.x/api/NodaTime.LocalTime.html) | | A simple time-of-day, with no timezone or offset information. -time with time zone | [OffsetTime](https://nodatime.org/3.0.x/api/NodaTime.OffsetTime.html) | | A type that stores a time and an offset. It's use is generally discouraged. -interval | [Period](https://nodatime.org/3.0.x/api/NodaTime.Period.html) | [Duration](https://nodatime.org/3.0.x/api/NodaTime.Duration.html) | An interval of time, from sub-second units to years. NodaTime `Duration` is supported for intervals with days and smaller, but not with years or months (as these have no absolute duration). `Period` can be used with any interval unit. -tstzrange | [Interval](https://nodatime.org/3.0.x/api/NodaTime.Interval.html) | `NpgsqlRange` etc. | An interval between two instants in time (start and end). -tsrange | `NpgsqlRange` | | An interval between two timestamps in an unknown or implicit time zone. -daterange | [DateInterval](https://nodatime.org/3.0.x/api/NodaTime.DateInterval.html) | `NpgsqlRange` etc. | An interval between two dates. - -1 In versions prior to 6.0 (or when `Npgsql.EnableLegacyTimestampBehavior` is enabled), writing or reading ZonedDateTime or OffsetDateTime automatically converted to or from UTC. [See the breaking change note for more info](../release-notes/6.0.md#major-changes-to-timestamp-mapping). - -2 In versions prior to 6.0 (or when `Npgsql.EnableLegacyTimestampBehavior` is enabled), `timestamp without time zone` was mapped to Instant by default, instead of LocalDateTime. [See the breaking change note for more info](../release-notes/6.0.md#major-changes-to-timestamp-mapping). - -## Infinity values - -PostgreSQL supports the special values `-infinity` and `infinity` for the timestamp and date types ([see docs](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-DATETIME-SPECIAL-VALUES)); these can be useful to represent a value which is earlier or later than any other value. Starting with Npgsql 6.0, these special values are mapped to the `MinValue` and `MaxValue` value on the corresponding .NET types (`Instant` and `LocalDate`). To opt out of this behavior, set the following AppContext switch at the start of your application: - -```csharp -AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true); -``` - -Note: in versions prior to 6.0, the connection string parameter `Convert Infinity DateTime` could be used to opt into these infinity conversions. That connection string parameter has been removed. diff --git a/conceptual/Npgsql/types/nts.md b/conceptual/Npgsql/types/nts.md deleted file mode 100644 index 0b40cb5e..00000000 --- a/conceptual/Npgsql/types/nts.md +++ /dev/null @@ -1,107 +0,0 @@ -# PostGIS/NetTopologySuite Type Plugin - -PostgreSQL supports spatial data and operations via [the PostGIS extension](https://postgis.net/), which is a mature and feature-rich database spatial implementation. .NET doesn't provide a standard spatial library, but [NetTopologySuite](https://github.com/NetTopologySuite/NetTopologySuite) is a leading spatial library. Npgsql has a plugin which allows you to map the NTS types PostGIS columns, and even translate many useful spatial operations to SQL. This is the recommended way to interact with spatial types in Npgsql. - -PostgreSQL provides support for spatial types (geometry/geography) via the powerful [PostGIS](https://postgis.net/) extension; this allows you to store points and other spatial constructs in the database, and efficiently perform operations and searches on them. Npgsql supports the PostGIS types via [NetTopologySuite](https://github.com/NetTopologySuite/NetTopologySuite), which is the leading spatial library in the .NET world: the NTS types can be read and written directly to their corresponding PostGIS types. This is the recommended way to work with spatial types in Npgsql. - -## Setup - -To avoid forcing a dependency on the NetTopologySuite library for users not using spatial, NTS support is delivered as a separate plugin. To use the plugin, simply add a dependency on [Npgsql.NetTopologySuite](https://www.nuget.org/packages/Npgsql.NetTopologySuite) and set it up in one of the following ways: - -### [NpgsqlDataSource](#tab/datasource) - -> [!NOTE] -> `NpgsqlDataSource` was introduced in Npgsql 7.0, and is the recommended way to manage type mapping. If you're using an older version, see the other methods. - -```csharp -var dataSourceBuilder = new NpgsqlDataSourceBuilder(...); -dataSourceBuilder.UseNetTopologySuite(); -await using var dataSource = dataSourceBuilder.Build(); -``` - -### [Global mapping](#tab/global) - -If you're using an older version of Npgsql which doesn't yet support `NpgsqlDataSource`, you can configure mappings globally for all connections in your application: - -```csharp -NpgsqlConnection.GlobalTypeMapper.UseNetTopologySuite(); -``` - -For this to work, you must place this code at the beginning of your application, before any other Npgsql API is called. Note that in Npgsql 7.0, global type mappings are obsolete (but still supported) - `NpgsqlDataSource` is the recommended way to manage type mappings. - -### [Connection mapping](#tab/connection) - -> [!NOTE] -> This mapping method has been removed in Npgsql 7.0. - -Older versions of Npgsql supported configuring a type mapping on an individual connection, as follows: - -```csharp -var conn = new NpgsqlConnection(...); -conn.TypeMapper.UseNetTopologySuite(); -``` - -*** - -By default the plugin handles only ordinates provided by the `DefaultCoordinateSequenceFactory` of `GeometryServiceProvider.Instance`. If `GeometryServiceProvider` is initialized automatically the X and Y ordinates are handled. To change the behavior specify the `handleOrdinates` parameter like in the following example: - -```csharp -dataSourceBuilder.UseNetTopologySuite(handleOrdinates: Ordinates.XYZ); -``` - -To process the M ordinate, you must initialize `GeometryServiceProvider.Instance` to a new `NtsGeometryServices` instance with `coordinateSequenceFactory` set to a `DotSpatialAffineCoordinateSequenceFactory`. Or you can specify the factory when calling `UseNetTopologySuite`. - -```csharp -// Place this at the beginning of your program to use the specified settings everywhere (recommended) -GeometryServiceProvider.Instance = new NtsGeometryServices( - new DotSpatialAffineCoordinateSequenceFactory(Ordinates.XYM), - new PrecisionModel(PrecisionModels.Floating), - -1); - -// Or specify settings for Npgsql only -dataSourceBuilder.UseNetTopologySuite.UseNetTopologySuite( - new DotSpatialAffineCoordinateSequenceFactory(Ordinates.XYM)); -``` - -## Reading and Writing Geometry Values - -When reading PostGIS values from the database, Npgsql will automatically return the appropriate NetTopologySuite types: `Point`, `LineString`, and so on. Npgsql will also automatically recognize NetTopologySuite's types in parameters, and will automatically send the corresponding PostGIS type to the database. The following code demonstrates a roundtrip of a NetTopologySuite `Point` to the database: - -```csharp -await conn.ExecuteNonQueryAsync("CREATE TEMP TABLE data (geom GEOMETRY)"); - -await using (var cmd = new NpgsqlCommand("INSERT INTO data (geom) VALUES ($1)", conn)) -{ - cmd.Parameters.Add(new() { Value = new Point(new Coordinate(1d, 1d)) }); - await cmd.ExecuteNonQueryAsync(); -} - -await using (var cmd = new NpgsqlCommand("SELECT geom FROM data", conn)) -await using (var reader = await cmd.ExecuteReaderAsync()) -{ - await reader.ReadAsync(); - var point = reader.GetFieldValue(0); -} -``` - -You may also explicitly specify a parameter's type by setting `NpgsqlDbType.Geometry`. - -## Geography (geodetic) Support - -PostGIS has two types: `geometry` (for Cartesian coordinates) and `geography` (for geodetic or spherical coordinates). You can read about the geometry/geography distinction [in the PostGIS docs](https://postgis.net/docs/manual-2.4/using_postgis_dbmanagement.html#PostGIS_Geography) or in [this blog post](http://workshops.boundlessgeo.com/postgis-intro/geography.html). In a nutshell, `geography` is much more accurate when doing calculations over long distances, but is more expensive computationally and supports only a small subset of the spatial operations supported by `geometry`. - -Npgsql uses the same NetTopologySuite types to represent both `geometry` and `geography` - the `Point` type represents a point in either Cartesian or geodetic space. You usually don't need to worry about this distinction because PostgreSQL will usually cast types back and forth as needed. However, it's worth noting that Npgsql sends Cartesian `geometry` by default, because that's the usual requirement. You have the option of telling Npgsql to send `geography` instead by specifying `NpgsqlDbType.Geography`: - -```csharp -await using (var cmd = new NpgsqlCommand("INSERT INTO data (geog) VALUES ($1)", conn)) -{ - cmd.Parameters.Add(new() { Value = point, NpgsqlDbType = NpgsqlDbType.Geography }); - await cmd.ExecuteNonQueryAsync(); -} -``` - -If you prefer to use `geography` everywhere by default, you can also specify that when setting up the plugin: - -```csharp -dataSourceBuilder.UseNetTopologySuite(geographyAsDefault: true); -``` diff --git a/conceptual/Npgsql/wait.md b/conceptual/Npgsql/wait.md deleted file mode 100644 index b8303bf0..00000000 --- a/conceptual/Npgsql/wait.md +++ /dev/null @@ -1,45 +0,0 @@ -# Waiting for Notifications - -Note: *This functionality replaces Npgsql 3.0's "Continuous processing mode"*. - -## PostgreSQL Asynchronous messages - -PostgreSQL has a feature whereby arbitrary notification messages can be sent between clients. For example, one client may wait until it is -notified by another client of a task that it is supposed to perform. Notifications are, by their nature, asynchronous - they can arrive -at any point. For more detail about this feature, see the PostgreSQL [NOTIFY command](http://www.postgresql.org/docs/current/static/sql-notify.html). -Some other asynchronous message types are notices (e.g. database shutdown imminent) and parameter changes, see the -[PostgreSQL protocol docs](http://www.postgresql.org/docs/current/static/protocol-flow.html#PROTOCOL-ASYNC) for more details. - -Note that despite the word "asynchronous", this page has nothing to do with ADO.NET async operations (e.g. ExecuteReaderAsync). - -## Processing of Notifications - -Npgsql exposes notification messages via the `Notification` event on NpgsqlConnection. - -Since asynchronous notifications are rarely used and processing can be complex, Npgsql only processes notification messages as -part of regular (synchronous) query interaction. That is, if an asynchronous notification is sent, Npgsql will only process it and emit an -event to the user the next time a command is sent and processed. - -To receive notifications outside a synchronous request-response cycle, call `NpgsqlConnection.Wait()`. This will make your thread block -until a single notification is received (note that a version with a timeout as well as an async version exist). Note that the notification -is still delivered via the `Notification` event as before. - -```csharp -var conn = new NpgsqlConnection(ConnectionString); -conn.Open(); -conn.Notification += (o, e) => Console.WriteLine("Received notification"); - -using (var cmd = new NpgsqlCommand("LISTEN channel_name", conn)) { - cmd.ExecuteNonQuery(); -} - -while (true) { - conn.Wait(); // Thread will block here -} -``` - ---- - -## Keepalive - -You may want to turn on [keepalives](keepalive.md). diff --git a/docfx.json b/docfx.json index 5363f813..0079b6dd 100644 --- a/docfx.json +++ b/docfx.json @@ -29,7 +29,7 @@ "dest": "obj/api/EFCore.PG", "properties": { - "TargetFramework": "net10.0" + "TargetFramework": "net11.0" } } ], @@ -54,12 +54,12 @@ }, { "files": [ "**.md", "toc.yml" ], - "src": "conceptual/Npgsql", + "src": "Npgsql/docs", "dest": "doc" }, { "files": [ "**.md", "toc.yml" ], - "src": "conceptual/EFCore.PG", + "src": "EFCore.PG/docs", "dest": "efcore" }, { diff --git a/toc.yml b/toc.yml index 0f6b2a94..40002b47 100644 --- a/toc.yml +++ b/toc.yml @@ -1,8 +1,8 @@ - name: Home href: index.md - name: Npgsql - href: conceptual/Npgsql/ + href: Npgsql/docs/ - name: Entity Framework Core - href: conceptual/EFCore.PG/ + href: EFCore.PG/docs/ - name: Entity Framework 6 href: conceptual/EF6.PG/