You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm a member of a project that is going to be using code-first EFC with Postgres and need to utilise table partitioning. It would be great if the data connector supported this natively so we don't have to resort to hacking SQL into the migrations manually or switching to schema-first.
I've taken a quick gander at your codebase and have some ideas, but I suspect quite strongly I'll not get anywhere so thought I'd ask politely here as well as with the improvements in PG12 (i.e. foreign key support) more people may decide to utilise partitioning.
Thanks!
Reacted by DarkFlame, Austin Drenski, Vito Macchia, Aaron Hudon, Markus Schaber, gparmigiani, sh03, Cubelaster, Shubham Bothara, Burak Büyükatlı and 99 more
@roji - I found a potentially better way that's simpler; I use table inheritance to create the master table using EF Core, then create inherited tables as necessary using raw sql with a Rule to redirect inserts into the inherited table. The one problem I've found is inserting into the master table; EF Core throws a concurrency error since rows weren't actually inserted into the master table.
I'm guessing this is due to how postgres rules change the actual query...for instance
CREATE TABLE Inherited (
CHECK (ColA = 'Foo')
) INHERITS (Master);
CREATE RULE Inherited_Insert AS
ON INSERT TO Master WHERE
(ColA = 'Foo')
DO INSTEAD
INSERT INTO Inhertied VALUES (NEW.*);
Inserting data into Master causes a concurrency exception since EF tries to get values back for tracking but the insert rule necessary for inherited tables doesn't return one.
Do you know of any way around this outside of writing manual SQL to insert?
Hmm... If you examine the INSERTs sent by EF Core, you should see a RETURNING clause which instructs PostgreSQL to send back the generated columns in the new row. As long as you replicate the same clause in your INSTEAD rule, things should be transparent to EF Core and everything should work.
Hope I've understood your issue, note that there's an issue open on having EF Core support PostgreSQL table inheritance, although it's unlikely we'll get around to doing anything soon.
I don't think a DO INSTEAD rule with a WHERE clause can have a RETURNING statement...I tried that and Postgres complained. Is there a way to ignore the RETURNING clause on insert?
@jonmill no, EF Core really does require those keys in order to work correctly (in at least some scenarios). For example, if you add a new entity and then update it, EF Core needs to have the (generated) key from the earlier INSERT statement to properly generate the later UPDATE statement.
Note this paragraph in the PG docs which seems to indicate that RETURNING is supported in INSERT rules, but apparently on unconditional ones (e.g. no WHERE clause)? I'm guessing this is the problem you're running into?
In a rule for INSERT, UPDATE, or DELETE on a view, you can add a RETURNING clause that emits the view's columns. This clause will be used to compute the outputs if the rule is triggered by an INSERT RETURNING, UPDATE RETURNING, or DELETE RETURNING command respectively. When the rule is triggered by a command without RETURNING, the rule's RETURNING clause will be ignored. The current implementation allows only unconditional INSTEAD rules to contain RETURNING; furthermore there can be at most one RETURNING clause among all the rules for the same event. (This ensures that there is only one candidate RETURNING clause to be used to compute the results.) RETURNING queries on the view will be rejected if there is no RETURNING clause in any available rule.
@roji - gotcha; yes, that is the issue I'm running into. I got around it by just doing a manual INSERT statement instead of using EF. The items I'm inserting won't be tracked or (immediately) used after insertion, so the RETURNING clause is extra work that's unnecessary for me.
It'd be great if this was possible without writing a manual INSERT clause, but I couldn't find a way
The items I'm inserting won't be tracked or (immediately) used after insertion, so the RETURNING clause is extra work that's unnecessary for me.
Unfortunately EF Core doesn't know that you don't need tracking (and so don't need the RETURNING) - what you're asking for is dotnet/efcore#9118. Right now I don't think there's a solution for what you're trying to do.
Hi all!
Have found some workaround for table partitioning using ef core and npgsql.
Create shadow property e.g. "Partitioned" for entity
Create BEFORE INSERT TRIGGER function that create partition (if not exists) and inserts row in this partition.
And returns NEW row (it's important for ef core, otherwise there will be exception)
But this returned row will be inserted in master table too.
In BEFORE INSERT TRIGGER I've made next steps:
BEFORE inserting in partition set Partitioned column to true
NEW."Partitioned" = true;
BEFORE returning row set set Partitioned column to false
NEW."Partitioned" = false;
Create AFTER INSERT TRIGGER function that deletes from master table rows by condition "Partitioned = false"
Hi @roji, we got all the tables migration happening using EF Core. For enabling the partition by range, I'm not sure how I can change the Migration File? ( to achieve something like below )
CREATE TABLE people (
id int not null,
birth_date date not null,
country_code character(2) not null,
name text
) PARTITION BY RANGE (birth_date);
reg child partition table, I can add by migrationBuilder.Sql(sql);. but not sure how I can create the master table with the partition definition using the EF Core Migration.
@mathavanmani EF Core (and the PostgreSQL provider) doesn't currently support table partitioning. However, it's perfectly fine to generate migrations, and then edit the generated files and introduce raw SQL. So you can use EF Core migrations to generate a plain vanilla CreateTable operation, then edit the migration and replace that with a raw SQL operation that contains your PARTITION BY clauses etc. See these docs for more info on raw SQL in migrations.
Reacted by mathavanmani, Ertavf and Bill de la Vega
Thanks for posting - the PG maintainers usually do fix regressions quite diligently, I'd be surprised if this isn't addressed. In any case, the EF Core PG provider doesn't do table partitioning on its own in any way.
It's important for my team. I can help you for this, I have custom realisation for 'FOR UPDATE' 'FOR SHARE', but I can't realisation 'Partition By' without change ef core provider for PostgreSQL
@Sin333 the intention is indeed to support this in the provider - there just hasn't been enough time (or user requests) up to now, and this isn't as trivial as some other features.
Some quick thoughts:
We'd basically exposed APIs to define declarative partitioning as shown in these PG docs.
We'd add metadata which allows migrations to generate the PARTITION BY RANGE (logdate) clause on CREATE TABLE.
We could also allow specifying the partitions themselves, although that seems a bit more complicated (not fully compatible with the general CREATE TABLE syntax, no columns), and may be of lower value (people can put raw SQL into migrations instead).
@Sin333 I think you're talking about creation of tables, but there is a problem with using partitioned tables, when you use xmin as concurrency token (it does not work):
[Timestamp]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[Column("xmin", TypeName = "xid")]
public uint Rowversion { get; set; }
@freerider7777 even if there's a PostgreSQL limitation around the use of xmin with partitioned tables, that doesn't invalidate using partitioned tables in general (users don't necessarily always need xmin). I suggest we keep this issue about creation of partitioned tables.
@freerider7777 For use Partition By (timestamp) in PostgreSQL with ef core you can use pg extensions: 'timescaledb', 'pg_pathman', 'pg_partman', it's good and simple way.
But it's not working in my case. I need use Partition By with 'Enum', 'Guid' column
Hi @roji !
Is there a way to change insert/update for partitioned table to contain not "returning xmin" (which is still not working) but "returning txid_current()" ?
@freerider7777 can you explain what would be the purpose of doing RETURNING txid_current()? txid_current simply returns the ID of the current transaction, whereas the point of xmin is to serve as a concurrency token, i.e. something stored on the table's row which serves to detect whether a change occurred since it was loaded.
If PostgreSQL xmin doesn't work with table partitioning, then I don't see what else could be used as an (automatic) concurrency token...
Create schema
CREATE TABLE "tmp"
(
id bigint generated always as identity,
date timestamptz not null,
foo int not null,
PRIMARY KEY ("id", "date")
)
PARTITION BY RANGE ("date");
CREATE TABLE "tmp_2020" PARTITION OF "tmp" FOR VALUES FROM ('2020-01-01') TO
('2022-01-01');
Execute query
INSERT INTO "tmp" ("date", "foo")
VALUES (NOW(), 1)
RETURNING id, xmin; -- it still breaks here in Postgres 12, 13 (maybe they'll fix later)
"returning id, xmin" is used by npgsql ef core provider when using xmin column for concurrency.
We have an idea to maybe change "returning id, xmin" to "returning id, txid_current()" as temporary fix for partitioned table
txid_current() just won't prevent concurrent writes as it's data local to the transaction. A literal 0 in place of xmin would work just as well at not doing anything. But at this point why even call UseXminAsConcurrencyToken() for that partitioned table?
@freerider7777 why is the provider generating returning xmin in your case? This is only something that happens if you configure it, as per the docs. Do you have UseXminAsConcurrencyToken in your model configuration?
The point is that "returning txid_current() as xmin" gives the same value (xmin) of the record and can be used for concurrency.
Not really. txid_current() gives your the current transaction (i.e. in your connection/session), whereas xmin gives you the transaction which last touched the database row. txid_current wouldn't work as concurrency token, since it isn't stored on the row.
For simple insert/update it seems the same value - current transaction :)
INSERT INTO "tmp" ("date", "foo") VALUES (NOW(), 1) RETURNING id, txid_current() as xmin;
If you mean the selects - selects work normally (select ...xmin from ...), they don't need a tweak
Sure it's not EF Core provider's functionality for such tweaks :) I thought maybe I can make a custom build of the provider with this tweak
Thanks for the point with interceptors... We haven't moved from 2.2 to 3 yet, seems it's time to :))
I'm still hoping to look at this for 7.0, but at this point there's a good chance I won't be able to do this (too much other stuff going on). But note that you shouldn't require support here to use the feature - you can use raw SQL in your migrations to create partitioned tables as you wish (see #1035 (comment)).
Hi, I'm interested on this feature. What I didn't understand is if I can somehow alter the table creation sql statement and append the partitioning rule to it or am I forced to completely rewrite the statement by hand.
Another thing that I don't understand is this. I saw that more than 2 years ago this PR #1789 was proposed but the author received no feedback.
You need to replace the scaffolded migration code with SQL - this is usually pretty easy to do by generating the actual SQL, and copying-and-pasting the generated CREATE TABLE into the scaffolded migration (replacing the CreateTable call) and adding the bits you need.
Hi, I'm interested on this feature. What I didn't understand is if I can somehow alter the table creation sql statement and append the partitioning rule to it or am I forced to completely rewrite the statement by hand.
Another thing that I don't understand is this. I saw that more than 2 years ago this PR #1789 was proposed but the author received no feedback.
I unfortunately didn't have time to devote to this. It's not great, but sometimes reviewing a PR takes a lot of time and effort, and I simply haven't gotten around to it.
Hi @roji , I think that recommendation to just manually edit EF generated migrations is very far from ideal for us. Our use case is that we have a system with over 50 microservices all written in .NET and all sharing some common infrastructural libraries. In those libraries among many other things we provide message forwarding to the message bus using transactional outbox pattern. Therefore definition of transactional outbox table and it's mappings is defined in library (nuget). Till now whenever we were modifying any of those infrastructure owned tables (yes we have more of them than just the outbox) we were just doing the changes in the nuget and then stating in release notes that it requires generating EF migration. It wasn't a problem because migration was generated automatically and developer accepted whatever code was generated. Now if we want to introduce partitioning we are forcing developers in over 50 microservices to manually edit migrations that they don't even understand.
Long story short I think that recommendation to edit migrations manually is not ideal but acceptable if you are writing whole application but it is not acceptable for library authors (think about something like ASP Identity team adding partitioning support to user entity forcing every developer using this feature to manually edit migrations).
Is it realistic to expect work for supporting this feature will happen for 9.0 or we need to assume it will be moved from version to version (like it was so far) and therefore we need to figure out some other solution?
Reacted by pantonis, Piotr Lasota, Hosi, Stanisław Bański and pawel-bednarz
Hello, @roji I used an interceptor to rewrite the SQL, but the SaveChanges data was successfully saved to the table, but an exception in the npgsql driver was triggered, and an error was still reported at the code level.
It seems that npgsql defaults to a bigint after receiving txid_current() as xmin, and an exception occurs when converting to the rowversion uint type of the ef model.
@KrzysztofBranicki you make a good point about libraries vs. applications; however, it simply isn't realistic to expect EF to cover the entire range of DDL possibilities across all supported databases (after all, the point you make has nothing to do with PostgreSQL table partitioning specifically). There's a huge space of options there, and there are bound to be users out there who want each one of them; modeling them in EF is non-trivial work and requires careful planning, and generally the return on that effort isn't great, given that users can do whatever they want by editing their migrations.
Having said that, there definitely does seem to be lots of interest in table partitioning specifically. I can't commit on this getting done for 9.0 - but give the number of votes this is definitely one of the highest-value features, and I promise to do my best.
Reacted by Krzysztof Branicki, Pavel Biryukov, Nandor Krizbai, Szymon Gwóźdź, Rinke, Onur Arslan, nev-21, Thomas H, revocengiz, Mauricio Dominguez and 26 more
its possible to replace command in migration engine this way
public class CustomMigrationsSqlGenerator : NpgsqlMigrationsSqlGenerator
{
public CustomMigrationsSqlGenerator(
MigrationsSqlGeneratorDependencies dependencies,
INpgsqlSingletonOptions npgsqlSingletonOptions)
: base(dependencies, npgsqlSingletonOptions) { }
protected override void Generate(
MigrationOperation operation,
IModel model,
MigrationCommandListBuilder builder
)
{
Console.WriteLine($"Zeman-Info: CustomMigrationsSqlGenerator.Generate called for operation '{operation.GetType().Name}'...");
// change your create table query..
if (operation is CreateTableOperation createTableOperation)
{
// make temporary builder and generate original SQL
var tempBuilder = new MigrationCommandListBuilder(Dependencies);
base.Generate(createTableOperation, model, tempBuilder); // generate command but to temporary builder
// iterate original commands
foreach (var cmd in tempBuilder.GetCommandList())
{
string newCmd = cmd.CommandText;
if (
newCmd.TrimStart().StartsWith("CREATE TABLE", StringComparison.OrdinalIgnoreCase)
// and another condition like your Annotation
)
{
newCmd = newCmd.Replace(");", $") PARTITION BY LIST (YourColumn);");
}
Console.WriteLine($"your new command: {cmd.CommandText}");
builder.Append(newCmd);
builder.EndCommand();
}
}
else
{
base.Generate(operation, model, builder);
}
}
}
the problem is that the string "PARTITION BY .... (YourColumn);" must be in the same command as CREATE TABLE (is it correct?). The solution is not beautiful, but it is there. We write our own NpgsqlMigrationsSqlGenerator, intercept the CreateTableOperation command and modify it. This solution is the best i could come up with, please forgive me if i did something against the rules. i'm just starting out with Ent Framework Core 5 days ago.
Probably its easy to add Annotation or something in your OnModelCreating like
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity(entityClrType).Metadata.SetAnnotation("BY_PARTITION", nameof(Archivizable.IsArchive));
}
and check it in your Generate(..)
But why cant create partition table when i have primary key... really sad :(
the problem is that the string "PARTITION BY .... (YourColumn);" must be in the same command as CREATE TABLE (is it correct?). The solution is not beautiful, but it is there. We write our own NpgsqlMigrationsSqlGenerator, intercept the CreateTableOperation command and modify it. This solution is the best i could come up with, please forgive me if i did something against the rules.
Not sure if you broke the rule but that interesting indeed.
But why cant create partition table when i have primary key... really sad :(
@otarnus-dennemeyer
and let this remain a curiosity, because the solution seems extremely inelegant. Dont use it :P
We all know that postgres has a limitation of being part of the key, but i dont fully understand why.
I understand that being the primary key allows during insert to quickly check if the key is not already taken, because it does not have to search all subtables. However, this current limitation can perhaps be solved by using an additional common index (unless i am missing something and it does not solve the problem). During insertion, only one common index would be searched.
Maybe in the postgres implementation it is not easy to implement, I do not understand that.
Maybe in the postgres implementation it is not easy to implement, I do not understand that.
@zemanpg I think it is quite well explained in the linked article: This limitation exists because the individual indexes making up the constraint can only directly enforce uniqueness within their own partitions; therefore, the partition structure itself must guarantee that there are not duplicates in different partitions.
In practice this is not much of a problem except making you PK a bit longer.
In Oracle, you can also have "global" indexes on a partitioned table, but they tend to be a pain in maintenance, requiring rebuild in multiple cases (for ex. when you drop a partition).
Activity
jonmill commentedon Jan 17, 2020
@roji - I found a potentially better way that's simpler; I use table inheritance to create the master table using EF Core, then create inherited tables as necessary using raw sql with a Rule to redirect inserts into the inherited table. The one problem I've found is inserting into the master table; EF Core throws a concurrency error since rows weren't actually inserted into the master table.
I'm guessing this is due to how postgres rules change the actual query...for instance
Inserting data into Master causes a concurrency exception since EF tries to get values back for tracking but the insert rule necessary for inherited tables doesn't return one.
Do you know of any way around this outside of writing manual SQL to insert?
roji commentedon Jan 17, 2020
Hmm... If you examine the INSERTs sent by EF Core, you should see a RETURNING clause which instructs PostgreSQL to send back the generated columns in the new row. As long as you replicate the same clause in your INSTEAD rule, things should be transparent to EF Core and everything should work.
Hope I've understood your issue, note that there's an issue open on having EF Core support PostgreSQL table inheritance, although it's unlikely we'll get around to doing anything soon.
jonmill commentedon Jan 17, 2020
I don't think a
DO INSTEADrule with aWHEREclause can have aRETURNINGstatement...I tried that and Postgres complained. Is there a way to ignore theRETURNINGclause on insert?roji commentedon Jan 20, 2020
@jonmill no, EF Core really does require those keys in order to work correctly (in at least some scenarios). For example, if you add a new entity and then update it, EF Core needs to have the (generated) key from the earlier INSERT statement to properly generate the later UPDATE statement.
Note this paragraph in the PG docs which seems to indicate that RETURNING is supported in INSERT rules, but apparently on unconditional ones (e.g. no WHERE clause)? I'm guessing this is the problem you're running into?
jonmill commentedon Jan 21, 2020
@roji - gotcha; yes, that is the issue I'm running into. I got around it by just doing a manual INSERT statement instead of using EF. The items I'm inserting won't be tracked or (immediately) used after insertion, so the RETURNING clause is extra work that's unnecessary for me.
It'd be great if this was possible without writing a manual INSERT clause, but I couldn't find a way
roji commentedon Jan 23, 2020
Unfortunately EF Core doesn't know that you don't need tracking (and so don't need the RETURNING) - what you're asking for is dotnet/efcore#9118. Right now I don't think there's a solution for what you're trying to do.
jonmill commentedon Jan 23, 2020
Gotcha; thanks for all your help!
agabidullin commentedon Apr 8, 2020
Hi all!
Have found some workaround for table partitioning using ef core and npgsql.
And returns NEW row (it's important for ef core, otherwise there will be exception)
Hope it will help!
mathavanmani commentedon Aug 4, 2020
Hi @roji, we got all the tables migration happening using EF Core. For enabling the partition by range, I'm not sure how I can change the Migration File? ( to achieve something like below )
CREATE TABLE people (
id int not null,
birth_date date not null,
country_code character(2) not null,
name text
) PARTITION BY RANGE (birth_date);
reg child partition table, I can add by migrationBuilder.Sql(sql);. but not sure how I can create the master table with the partition definition using the EF Core Migration.
roji commentedon Aug 5, 2020
@mathavanmani EF Core (and the PostgreSQL provider) doesn't currently support table partitioning. However, it's perfectly fine to generate migrations, and then edit the generated files and introduce raw SQL. So you can use EF Core migrations to generate a plain vanilla CreateTable operation, then edit the migration and replace that with a raw SQL operation that contains your
PARTITION BYclauses etc. See these docs for more info on raw SQL in migrations.freerider7777 commentedon Sep 12, 2020
"returning xmin" does not work in partitioned tables in Postgres 12 (works ok in 11), so we can't use npgsql EF Core with partitioned tables...
There is a discussion but I don't know if they are going to fix it:
https://www.postgresql.org/message-id/16446-2011a4b103fc5fd1@postgresql.org
roji commentedon Sep 12, 2020
Thanks for posting - the PG maintainers usually do fix regressions quite diligently, I'd be surprised if this isn't addressed. In any case, the EF Core PG provider doesn't do table partitioning on its own in any way.
freerider7777 commentedon Sep 13, 2020
Hope they will... There is a strange discussion "whether this a bug", I pointed them npgsql ef core provider uses this construction
https://www.postgresql.org/message-id/CA%2BTgmoaN0kQa3nxToHtD8nRymSnUYaj4XL3zKq8Q_0AUJcQNPQ%40mail.gmail.com
roji commentedon Oct 28, 2020
The required relational model infrastructure is done on the EF Core side, so this should no be doable.
/cc @AndriySvyryd
freerider7777 commentedon Nov 13, 2020
12.5, 13.1 release of postgres,
RETURNING xmin
still not working for partitioned tables...
any suggestions how to work around?
Sin333 commentedon Nov 17, 2020
It's actual now, are you going to add PartitionBy for ef core provider?
Sorry english is it not my native language.
Sin333 commentedon Nov 17, 2020
It's important for my team. I can help you for this, I have custom realisation for 'FOR UPDATE' 'FOR SHARE', but I can't realisation 'Partition By' without change ef core provider for PostgreSQL
roji commentedon Nov 18, 2020
@Sin333 the intention is indeed to support this in the provider - there just hasn't been enough time (or user requests) up to now, and this isn't as trivial as some other features.
Some quick thoughts:
PARTITION BY RANGE (logdate)clause on CREATE TABLE.freerider7777 commentedon Nov 18, 2020
@Sin333 I think you're talking about creation of tables, but there is a problem with using partitioned tables, when you use xmin as concurrency token (it does not work):
[Timestamp]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[Column("xmin", TypeName = "xid")]
public uint Rowversion { get; set; }
roji commentedon Nov 18, 2020
@freerider7777 even if there's a PostgreSQL limitation around the use of xmin with partitioned tables, that doesn't invalidate using partitioned tables in general (users don't necessarily always need xmin). I suggest we keep this issue about creation of partitioned tables.
freerider7777 commentedon Nov 18, 2020
@roji Ok, just warning :)
Sin333 commentedon Nov 18, 2020
@freerider7777 For use Partition By (timestamp) in PostgreSQL with ef core you can use pg extensions: 'timescaledb', 'pg_pathman', 'pg_partman', it's good and simple way.
But it's not working in my case. I need use Partition By with 'Enum', 'Guid' column
freerider7777 commentedon Nov 19, 2020
@Sin333 I wrote you details by email yesterday
freerider7777 commentedon Mar 30, 2021
Hi @roji !
Is there a way to change insert/update for partitioned table to contain not "returning xmin" (which is still not working) but "returning txid_current()" ?
roji commentedon Mar 30, 2021
@freerider7777 can you explain what would be the purpose of doing
RETURNING txid_current()?txid_currentsimply returns the ID of the current transaction, whereas the point of xmin is to serve as a concurrency token, i.e. something stored on the table's row which serves to detect whether a change occurred since it was loaded.If PostgreSQL
xmindoesn't work with table partitioning, then I don't see what else could be used as an (automatic) concurrency token...freerider7777 commentedon Mar 30, 2021
@roji
Simple reproduction:
Create schema
CREATE TABLE "tmp"
(
id bigint generated always as identity,
date timestamptz not null,
foo int not null,
PRIMARY KEY ("id", "date")
)
PARTITION BY RANGE ("date");
CREATE TABLE "tmp_2020" PARTITION OF "tmp" FOR VALUES FROM ('2020-01-01') TO
('2022-01-01');
Execute query
INSERT INTO "tmp" ("date", "foo")
VALUES (NOW(), 1)
RETURNING id, xmin; -- it still breaks here in Postgres 12, 13 (maybe they'll fix later)
"returning id, xmin" is used by npgsql ef core provider when using xmin column for concurrency.
We have an idea to maybe change "returning id, xmin" to "returning id, txid_current()" as temporary fix for partitioned table
NinoFloris commentedon Mar 30, 2021
txid_current()just won't prevent concurrent writes as it's data local to the transaction. A literal 0 in place of xmin would work just as well at not doing anything. But at this point why even callUseXminAsConcurrencyToken()for that partitioned table?roji commentedon Mar 30, 2021
@freerider7777 why is the provider generating
returning xminin your case? This is only something that happens if you configure it, as per the docs. Do you haveUseXminAsConcurrencyTokenin your model configuration?freerider7777 commentedon Mar 30, 2021
@roji We don't have UseXminAsConcurrencyToken but use attributes (which gives the same result):
freerider7777 commentedon Mar 30, 2021
@NinoFloris with 0 (instead of xmin) you'll receive DbUpdateConcurrencyException when updating the entity.
NinoFloris commentedon Mar 30, 2021
It was purely to illustrate the point anything other than a column does not work.
freerider7777 commentedon Mar 30, 2021
The point is that "returning txid_current() as xmin" gives the same value (xmin) of the record and can be used for concurrency.
roji commentedon Mar 30, 2021
Not really.
txid_current()gives your the current transaction (i.e. in your connection/session), whereas xmin gives you the transaction which last touched the database row. txid_current wouldn't work as concurrency token, since it isn't stored on the row.freerider7777 commentedon Mar 30, 2021
For simple insert/update it seems the same value - current transaction :)
INSERT INTO "tmp" ("date", "foo") VALUES (NOW(), 1) RETURNING id, txid_current() as xmin;
If you mean the selects - selects work normally (select ...xmin from ...), they don't need a tweak
roji commentedon Mar 30, 2021
@freerider7777 I finally understood what exactly you're proposing - thanks for your patience.
However, after also reading https://www.postgresql-archive.org/posgres-12-bug-partitioned-table-td6139957.html, I don't think the EF Core provider should be (implicitly) working around this PG problem. It should be fairly easy to write a database interceptor which rewrites xmin into
txid_current()if that's what you want to do.freerider7777 commentedon Mar 30, 2021
Sure it's not EF Core provider's functionality for such tweaks :) I thought maybe I can make a custom build of the provider with this tweak
Thanks for the point with interceptors... We haven't moved from 2.2 to 3 yet, seems it's time to :))
Aims to support Npgsql Table Partitioning as part of the EF Core enti…
nev-21 commentedon Nov 8, 2021
Hi, @roji is there any plan or advance about this feature?
ktb-dev commentedon Jul 6, 2022
Hi,
I am also interested in the question - how are things with the implementation of the table partitioning feature?
roji commentedon Jul 7, 2022
I'm still hoping to look at this for 7.0, but at this point there's a good chance I won't be able to do this (too much other stuff going on). But note that you shouldn't require support here to use the feature - you can use raw SQL in your migrations to create partitioned tables as you wish (see #1035 (comment)).
malix0 commentedon Jun 6, 2023
Hi, I'm interested on this feature. What I didn't understand is if I can somehow alter the table creation sql statement and append the partitioning rule to it or am I forced to completely rewrite the statement by hand.
Another thing that I don't understand is this. I saw that more than 2 years ago this PR #1789 was proposed but the author received no feedback.
roji commentedon Jun 6, 2023
You need to replace the scaffolded migration code with SQL - this is usually pretty easy to do by generating the actual SQL, and copying-and-pasting the generated CREATE TABLE into the scaffolded migration (replacing the CreateTable call) and adding the bits you need.
I unfortunately didn't have time to devote to this. It's not great, but sometimes reviewing a PR takes a lot of time and effort, and I simply haven't gotten around to it.
mmisztal1980 commentedon Jun 15, 2023
@roji I take it, this feature is still not available?
roji commentedon Nov 10, 2023
Note #2934 which is about recognizing partitions in scaffolding, possibly before actual support is implemented.
freerider7777 commentedon Nov 13, 2023
wow... this issue is still alive :))
KrzysztofBranicki commentedon Dec 12, 2023
Hi @roji , I think that recommendation to just manually edit EF generated migrations is very far from ideal for us. Our use case is that we have a system with over 50 microservices all written in .NET and all sharing some common infrastructural libraries. In those libraries among many other things we provide message forwarding to the message bus using transactional outbox pattern. Therefore definition of transactional outbox table and it's mappings is defined in library (nuget). Till now whenever we were modifying any of those infrastructure owned tables (yes we have more of them than just the outbox) we were just doing the changes in the nuget and then stating in release notes that it requires generating EF migration. It wasn't a problem because migration was generated automatically and developer accepted whatever code was generated. Now if we want to introduce partitioning we are forcing developers in over 50 microservices to manually edit migrations that they don't even understand.
Long story short I think that recommendation to edit migrations manually is not ideal but acceptable if you are writing whole application but it is not acceptable for library authors (think about something like ASP Identity team adding partitioning support to user entity forcing every developer using this feature to manually edit migrations).
Is it realistic to expect work for supporting this feature will happen for 9.0 or we need to assume it will be moved from version to version (like it was so far) and therefore we need to figure out some other solution?
dashiell-zhang commentedon Dec 13, 2023
Hello, @roji I used an interceptor to rewrite the SQL, but the SaveChanges data was successfully saved to the table, but an exception in the npgsql driver was triggered, and an error was still reported at the code level.
It seems that npgsql defaults to a bigint after receiving txid_current() as xmin, and an exception occurs when converting to the rowversion uint type of the ef model.
dashiell-zhang commentedon Dec 13, 2023
After adding oid conversion to the sql interceptor, it can be used correctly.
freerider7777 commentedon Dec 15, 2023
Yes, we did such interceptor as I remember :)) Now we're on spring boot projects - other technology other problems :))
roji commentedon Dec 16, 2023
@KrzysztofBranicki you make a good point about libraries vs. applications; however, it simply isn't realistic to expect EF to cover the entire range of DDL possibilities across all supported databases (after all, the point you make has nothing to do with PostgreSQL table partitioning specifically). There's a huge space of options there, and there are bound to be users out there who want each one of them; modeling them in EF is non-trivial work and requires careful planning, and generally the return on that effort isn't great, given that users can do whatever they want by editing their migrations.
Having said that, there definitely does seem to be lots of interest in table partitioning specifically. I can't commit on this getting done for 9.0 - but give the number of votes this is definitely one of the highest-value features, and I promise to do my best.
pantonis commentedon Apr 12, 2024
roji commentedon Apr 12, 2024
pantonis commentedon Apr 15, 2024
roji commentedon Apr 15, 2024
pantonis commentedon Apr 15, 2024
roji commentedon Apr 15, 2024
pantonis commentedon Apr 15, 2024
roji commentedon Apr 15, 2024
roji commentedon Apr 15, 2024
pantonis commentedon Apr 15, 2024
roji commentedon Apr 15, 2024
dashiell-zhang commentedon May 7, 2024
@pantonis The primary key can use the Snowflake ID algorithm to generate a long type ID. The Snowflake ID algorithm has a built-in concept of time.
n0099 commentedon May 18, 2024
#1035 (comment)
https://dba.stackexchange.com/questions/123145/how-to-view-tuples-changed-in-a-postgresql-transaction/123183#123183
https://stackoverflow.com/questions/49214219/what-is-the-meaning-of-epoch-in-txid-current-in-postgresql
https://www.postgresql.org/message-id/flat/141051591267657%40mail.yandex.ru
protected override void OnConfiguring(DbContextOptionsBuilder options) { + options.AddInterceptors(UseCurrentXactIdAsConcurrencyTokenCommandInterceptor.Instance)Also it's recommend to disable
SAVEPOINT: dotnet/efcore#23269 (comment) assubxidof subtransaction is always larger than the parent xid: https://www.postgresql.org/docs/current/subxacts.html+ class `UseCurrentXactIdAsConcurrencyTokenCommandInterceptor` to fix…
marcin1102 commentedon Jun 28, 2024
roji commentedon Jun 28, 2024
psavva commentedon Sep 20, 2024
I would also like to declare my interest in supporting partitioned takes.
Great work on the library.
yedajiang44 commentedon Sep 20, 2024
Did you achieve it? Can you tell me how to do it?
psavva commentedon Nov 6, 2024
Not yet
zemanpg commentedon Dec 19, 2024
its possible to replace command in migration engine this way
the problem is that the string "PARTITION BY .... (YourColumn);" must be in the same command as CREATE TABLE (is it correct?). The solution is not beautiful, but it is there. We write our own NpgsqlMigrationsSqlGenerator, intercept the CreateTableOperation command and modify it. This solution is the best i could come up with, please forgive me if i did something against the rules. i'm just starting out with Ent Framework Core 5 days ago.
Probably its easy to add Annotation or something in your OnModelCreating like
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity(entityClrType).Metadata.SetAnnotation("BY_PARTITION", nameof(Archivizable.IsArchive));
}
and check it in your Generate(..)
But why cant create partition table when i have primary key... really sad :(
otarnus-dennemeyer commentedon Jan 16, 2025
Not sure if you broke the rule but that interesting indeed.
That may simply be because you're not including your partition key in your primary key and this is mandatory. See : https://www.postgresql.org/docs/current/ddl-partitioning.html#DDL-PARTITIONING-DECLARATIVE-LIMITATIONS
zemanpg commentedon Jan 17, 2025
@otarnus-dennemeyer
and let this remain a curiosity, because the solution seems extremely inelegant. Dont use it :P
We all know that postgres has a limitation of being part of the key, but i dont fully understand why.
I understand that being the primary key allows during insert to quickly check if the key is not already taken, because it does not have to search all subtables. However, this current limitation can perhaps be solved by using an additional common index (unless i am missing something and it does not solve the problem). During insertion, only one common index would be searched.
Maybe in the postgres implementation it is not easy to implement, I do not understand that.
otarnus-dennemeyer commentedon Jan 20, 2025
@zemanpg I think it is quite well explained in the linked article:
This limitation exists because the individual indexes making up the constraint can only directly enforce uniqueness within their own partitions; therefore, the partition structure itself must guarantee that there are not duplicates in different partitions.
In practice this is not much of a problem except making you PK a bit longer.
In Oracle, you can also have "global" indexes on a partitioned table, but they tend to be a pain in maintenance, requiring rebuild in multiple cases (for ex. when you drop a partition).