Skip to content

Support for table partitioning #1035

Open

Description

@mrjrt

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!

Activity

  1. jonmill commented on Jan 17, 2020

    @jonmill

    @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?

  2. roji commented on Jan 17, 2020

    @roji
    Member

    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.

  3. jonmill commented on Jan 17, 2020

    @jonmill

    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?

  4. roji commented on Jan 20, 2020

    @roji
    Member

    @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.

  5. jonmill commented on Jan 21, 2020

    @jonmill

    @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

  6. roji commented on Jan 23, 2020

    @roji
    Member

    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.

  7. jonmill commented on Jan 23, 2020

    @jonmill

    Gotcha; thanks for all your help!

  8. agabidullin commented on Apr 8, 2020

    @agabidullin

    Hi all!
    Have found some workaround for table partitioning using ef core and npgsql.

    1. Create shadow property e.g. "Partitioned" for entity
    2. 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)
    3. But this returned row will be inserted in master table too.
    4. 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;

    1. Create AFTER INSERT TRIGGER function that deletes from master table rows by condition "Partitioned = false"

    Hope it will help!

  9. mathavanmani commented on Aug 4, 2020

    @mathavanmani

    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.

  10. roji commented on Aug 5, 2020

    @roji
    Member

    @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.

  11. modified the milestones: 5.0.0, 6.0.0 on Aug 29, 2020
  12. freerider7777 commented on Sep 12, 2020

    @freerider7777

    "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

  13. roji commented on Sep 12, 2020

    @roji
    Member

    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.

  14. freerider7777 commented on Sep 13, 2020

    @freerider7777

    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

  15. roji commented on Oct 28, 2020

    @roji
    Member

    The required relational model infrastructure is done on the EF Core side, so this should no be doable.

    /cc @AndriySvyryd

  16. freerider7777 commented on Nov 13, 2020

    @freerider7777

    12.5, 13.1 release of postgres,
    RETURNING xmin
    still not working for partitioned tables...
    any suggestions how to work around?

  17. Sin333 commented on Nov 17, 2020

    @Sin333

    It's actual now, are you going to add PartitionBy for ef core provider?
    Sorry english is it not my native language.

  18. Sin333 commented on Nov 17, 2020

    @Sin333

    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

  19. roji commented on Nov 18, 2020

    @roji
    Member

    @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).
  20. freerider7777 commented on Nov 18, 2020

    @freerider7777

    @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; }

  21. roji commented on Nov 18, 2020

    @roji
    Member

    @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.

  22. freerider7777 commented on Nov 18, 2020

    @freerider7777

    @roji Ok, just warning :)

  23. Sin333 commented on Nov 18, 2020

    @Sin333

    @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

  24. freerider7777 commented on Nov 19, 2020

    @freerider7777

    @Sin333 I wrote you details by email yesterday

  25. freerider7777 commented on Mar 30, 2021

    @freerider7777

    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()" ?

  26. roji commented on Mar 30, 2021

    @roji
    Member

    @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...

  27. freerider7777 commented on Mar 30, 2021

    @freerider7777

    @roji
    Simple reproduction:

    1. 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');

    2. 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

  28. NinoFloris commented on Mar 30, 2021

    @NinoFloris
    Member

    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?

  29. roji commented on Mar 30, 2021

    @roji
    Member

    @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?

  30. freerider7777 commented on Mar 30, 2021

    @freerider7777

    @roji We don't have UseXminAsConcurrencyToken but use attributes (which gives the same result):

        [Timestamp]
        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        [Column("xmin", TypeName = "xid")]
        public uint Rowversion { get; set; }
    
  31. freerider7777 commented on Mar 30, 2021

    @freerider7777

    @NinoFloris with 0 (instead of xmin) you'll receive DbUpdateConcurrencyException when updating the entity.

  32. NinoFloris commented on Mar 30, 2021

    @NinoFloris
    Member

    It was purely to illustrate the point anything other than a column does not work.

  33. freerider7777 commented on Mar 30, 2021

    @freerider7777

    The point is that "returning txid_current() as xmin" gives the same value (xmin) of the record and can be used for concurrency.

  34. roji commented on Mar 30, 2021

    @roji
    Member

    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.

  35. freerider7777 commented on Mar 30, 2021

    @freerider7777

    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

  36. roji commented on Mar 30, 2021

    @roji
    Member

    @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.

  37. freerider7777 commented on Mar 30, 2021

    @freerider7777

    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 :))

  38. modified the milestones: 6.0.0, 7.0.0 on Oct 9, 2021
  39. nev-21 commented on Nov 8, 2021

    @nev-21

    Hi, @roji is there any plan or advance about this feature?

  40. ktb-dev commented on Jul 6, 2022

    @ktb-dev

    Hi,
    I am also interested in the question - how are things with the implementation of the table partitioning feature?

  41. roji commented on Jul 7, 2022

    @roji
    Member

    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)).

  42. modified the milestones: 7.0.0, 8.0.0 on Oct 15, 2022
  43. malix0 commented on Jun 6, 2023

    @malix0

    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.

  44. roji commented on Jun 6, 2023

    @roji
    Member

    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.

  45. mmisztal1980 commented on Jun 15, 2023

    @mmisztal1980

    @roji I take it, this feature is still not available?

  46. roji commented on Nov 10, 2023

    @roji
    Member

    Note #2934 which is about recognizing partitions in scaffolding, possibly before actual support is implemented.

  47. modified the milestones: 8.0.0, 9.0.0 on Nov 13, 2023
  48. freerider7777 commented on Nov 13, 2023

    @freerider7777

    wow... this issue is still alive :))

  49. KrzysztofBranicki commented on Dec 12, 2023

    @KrzysztofBranicki

    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?

  50. dashiell-zhang commented on Dec 13, 2023

    @dashiell-zhang

    @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 if that's what you want to do.txid_current()

    image

    image

    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.

    image

    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.

  51. dashiell-zhang commented on Dec 13, 2023

    @dashiell-zhang

    image
    After adding oid conversion to the sql interceptor, it can be used correctly.

  52. freerider7777 commented on Dec 15, 2023

    @freerider7777

    Yes, we did such interceptor as I remember :)) Now we're on spring boot projects - other technology other problems :))

  53. roji commented on Dec 16, 2023

    @roji
    Member

    @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.

  54. pantonis commented on Apr 12, 2024

    @pantonis
  55. roji commented on Apr 12, 2024

    @roji
  56. pantonis commented on Apr 15, 2024

    @pantonis
  57. roji commented on Apr 15, 2024

    @roji
  58. pantonis commented on Apr 15, 2024

    @pantonis
  59. roji commented on Apr 15, 2024

    @roji
  60. pantonis commented on Apr 15, 2024

    @pantonis
  61. roji commented on Apr 15, 2024

    @roji
  62. roji commented on Apr 15, 2024

    @roji
  63. pantonis commented on Apr 15, 2024

    @pantonis
  64. roji commented on Apr 15, 2024

    @roji
  65. dashiell-zhang commented on May 7, 2024

    @dashiell-zhang

    But I don't have an option here. postgresql partition by range requires the partition column to be included in the primary key or unique constraints

    @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.

  66. n0099 commented on May 18, 2024

    @n0099

    #1035 (comment)

    @freerider7777 I finally understood what exactly you're proposing - thanks for your patience.

    However, after also reading 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.

    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

    /// <see>https://www.postgresql.org/message-id/flat/141051591267657%40mail.yandex.ru</see>
    /// <see>https://dba.stackexchange.com/questions/123145/how-to-view-tuples-changed-in-a-postgresql-transaction/123183#123183</see>
    /// <see>https://stackoverflow.com/questions/49214219/what-is-the-meaning-of-epoch-in-txid-current-in-postgresql</see>
    /// <see>https://github.com/npgsql/efcore.pg/issues/1035#issuecomment-2118584744</see>
    protected class UseCurrentXactIdAsConcurrencyTokenCommandInterceptor : DbCommandInterceptor
    {
        public static UseCurrentXactIdAsConcurrencyTokenCommandInterceptor Instance => new();
    
        public override InterceptionResult<DbDataReader> ReaderExecuting(
            DbCommand command,
            CommandEventData eventData,
            InterceptionResult<DbDataReader> result)
        {
            ManipulateCommand(command);
            return result;
        }
    
        public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
            DbCommand command,
            CommandEventData eventData,
            InterceptionResult<DbDataReader> result,
            CancellationToken cancellationToken = default)
        {
            ManipulateCommand(command);
            return new(result);
        }
    
        private static void ManipulateCommand(DbCommand command) =>
            command.CommandText = command.CommandText.Replace(
                "RETURNING xmin",
                "RETURNING pg_current_xact_id()::xid");
    }
    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
    +    options.AddInterceptors(UseCurrentXactIdAsConcurrencyTokenCommandInterceptor.Instance)

    Also it's recommend to disable SAVEPOINT: dotnet/efcore#23269 (comment) as subxid of subtransaction is always larger than the parent xid: https://www.postgresql.org/docs/current/subxacts.html

  67. marcin1102 commented on Jun 28, 2024

    @marcin1102
  68. roji commented on Jun 28, 2024

    @roji
  69. psavva commented on Sep 20, 2024

    @psavva

    I would also like to declare my interest in supporting partitioned takes.

    Great work on the library.

  70. yedajiang44 commented on Sep 20, 2024

    @yedajiang44

    I would also like to declare my interest in supporting partitioned takes.

    Great work on the library.

    Did you achieve it? Can you tell me how to do it?

  71. modified the milestones: 9.0.0, Backlog on Oct 27, 2024
  72. psavva commented on Nov 6, 2024

    @psavva

    I would also like to declare my interest in supporting partitioned takes.
    Great work on the library.

    Did you achieve it? Can you tell me how to do it?

    Not yet

  73. zemanpg commented on Dec 19, 2024

    @zemanpg

    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 :(

  74. otarnus-dennemeyer commented on Jan 16, 2025

    @otarnus-dennemeyer

    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 :(

    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

  75. zemanpg commented on Jan 17, 2025

    @zemanpg

    @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.

  76. otarnus-dennemeyer commented on Jan 20, 2025

    @otarnus-dennemeyer

    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).

  77. added theissue type on Jun 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions