Skip to content

Passing a collection of collections, or a collection of tuples as a parameter value for clauses like WHERE ... IN ... or INSERT INTO / UPDATE... WHERE statements isn't working #4437

Closed

Description

@natalie-o-perret

Steps to reproduce

I've already posted something on SO the other day, but lemme repost the chunks here.

The issue

I have two tables as defined below:

CREATE TABLE IF NOT EXISTS sch_brand_payment_data_lake_proxy.supplier_balances (
/* id is here for joining purposes with items table, instead of joining with the 4 columns used for sake
   of making sure a record is deemed as unique */
  id                             bigserial NOT NULL,
  accounting_document            text      NOT NULL,
  accounting_document_type       text      NOT NULL,
  company_code                   text      NOT NULL,
  document_date_year             int4      NOT NULL,
  accounting_doc_created_by_user text,
  accounting_clerk               text,
  assignment_reference           text,
  document_reference_id          text,
  original_reference_document    text,
  payment_terms                  text,
  supplier                       text,
  supplier_name                  text,
  document_date                  timestamp,
  posting_date                   timestamp,
  net_due_date                   timestamp,
  created_on                     timestamp default NULL,
  modified_on                    timestamp default NULL,
  pushed_on                      timestamp default NULL,
  is_modified bool GENERATED ALWAYS AS (modified_on IS NOT NULL AND modified_on > created_on) STORED,
  is_pushed   bool GENERATED ALWAYS AS (pushed_on   IS NOT NULL AND pushed_on > modified_on)  STORED,
  CONSTRAINT supplier_balances_pkey   PRIMARY KEY (id),
  /* accounting_document being the field of the composite unique index -> faster querying */
  CONSTRAINT supplier_balances_unique UNIQUE (
     accounting_document,
     accounting_document_type,
     company_code,
     document_date_year)
);

/* Creating other indexes for querying of those as well */
CREATE INDEX IF NOT EXISTS supplier_balances_accounting_document_type_idx
ON sch_brand_payment_data_lake_proxy.supplier_balances (accounting_document_type);
CREATE INDEX IF NOT EXISTS supplier_balances_company_code_idx
ON sch_brand_payment_data_lake_proxy.supplier_balances (company_code);
CREATE INDEX IF NOT EXISTS supplier_balances_document_date_year_idx
ON sch_brand_payment_data_lake_proxy.supplier_balances (document_date_year);

CREATE TABLE IF NOT EXISTS sch_brand_payment_data_lake_proxy.supplier_balance_items
(
    supplier_balance_id             bigserial NOT NULL,
    posting_view_item               text      NOT NULL,
    posting_key                     text,
    amount_in_company_code_currency numeric,
    amount_in_transaction_currency  numeric,
    cash_discount_1_percent         numeric,
    cash_discount_amount            numeric,
    clearing_accounting_document    text,
    document_item_text              text,
    gl_account                      text,
    is_cleared                      bool,
    clearing_date                   timestamp,
    due_calculation_base_date       timestamp,
    /* uniqueness is basically the posting_view_item for a given supplier balance */
    CONSTRAINT supplier_balance_items_pkey PRIMARY KEY (supplier_balance_id, posting_view_item),
    /* 1(supplier balance):N(supplier balance items) */
    CONSTRAINT supplier_balance_items_fkey FOREIGN KEY (supplier_balance_id)
               REFERENCES sch_brand_payment_data_lake_proxy.supplier_balances (id)
               ON DELETE CASCADE
               ON UPDATE CASCADE
);

That I then filled up as follows:

INSERT INTO 
sch_brand_payment_data_lake_proxy.supplier_balances 
(accounting_document, accounting_document_type, company_code, document_date_year)
VALUES 
('A', 'B', 'C', 0),
('A', 'B', 'C', 1),
('A', 'B', 'C', 2),
('A', 'B', 'C', 3),
('A', 'B', 'C', 4),
('A', 'B', 'C', 5)
RETURNING id;

Output:

id
1
2
3
4
5
6
INSERT INTO 
sch_brand_payment_data_lake_proxy.supplier_balance_items 
(supplier_balance_id, posting_view_item)
VALUES 
(1, 'A'),
(1, 'B'),
(3, 'A'),
(3, 'B'),
(2, 'A'),
(1, 'C');

And check that what has been inserted is really there, just in case we've missed out something:

SELECT 
    accounting_document, 
    accounting_document_type, 
    company_code, 
    document_date_year
FROM sch_brand_payment_data_lake_proxy.supplier_balances;

Output:

id accounting_document accounting_document_type company_code document_date_year
1 A B C 0
2 A B C 1
3 A B C 2
4 A B C 3
5 A B C 4
6 A B C 5
SELECT 
    supplier_balance_id,
    posting_view_item
FROM sch_brand_payment_data_lake_proxy.supplier_balance_items;

Output:

supplier_balance_id posting_view_item
1 A
1 B
3 A
3 B
2 A
1 C

Now, if we want to select multiple values in a JOIN we can execute the raw SQL below:

SELECT 
    id,
    accounting_document, 
    accounting_document_type, 
    company_code, 
    document_date_year, 
    posting_view_item
FROM sch_brand_payment_data_lake_proxy.supplier_balances
LEFT OUTER JOIN sch_brand_payment_data_lake_proxy.supplier_balance_items
ON supplier_balances.id = supplier_balance_items.supplier_balance_id
WHERE (accounting_document, accounting_document_type, company_code, document_date_year)
IN  (('A', 'B', 'C', 1), ('A', 'B', 'C', 2))

Output:

id accounting_document accounting_document_type company_code document_date_year posting_view_item
2 A B C 1 A
3 A B C 2 A

So far, so good, this was just for the pure SQL preliminaries.

Reproducing the query just above is a plain npgsql is an easy feat:

using System.Data;

using Npgsql;

var connectionStringBuilder = new NpgsqlConnectionStringBuilder
{
    Host     = "localhost",
    Port     = 5432,
    Username = "brand_payment_migration",
    Password = "secret",
    Database = "brand_payment"
};
using var connection = new NpgsqlConnection(connectionStringBuilder.ToString());
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = 
"SELECT id, accounting_document, accounting_document_type, company_code, document_date_year, posting_view_item " +
"FROM sch_brand_payment_data_lake_proxy.supplier_balances " +
"LEFT OUTER JOIN sch_brand_payment_data_lake_proxy.supplier_balance_items " +
"ON supplier_balances.id = supplier_balance_items.supplier_balance_id " +
"WHERE (accounting_document, accounting_document_type, company_code, document_date_year) " +
"IN (('A', 'B', 'C', 1), ('A', 'B', 'C', 2));";

using var reader = command.ExecuteReader();
using var dataTable = new DataTable();
dataTable.Load(reader);
var cols = dataTable.Columns.Cast<DataColumn>().ToArray();
Console.WriteLine(string.Join(Environment.NewLine, cols.Select((x, i) => $"Col{i} = {x}")));
Console.WriteLine(string.Join("\t", cols.Select((_, i) => $"Col{i}")));
foreach (var dataRow in dataTable.Rows.Cast<DataRow>())
{
    Console.WriteLine(string.Join("\t", dataRow.ItemArray));
}

which, as expected outputs:

Col0 = id
Col1 = accounting_document
Col2 = accounting_document_type
Col3 = company_code
Col4 = document_date_year
Col5 = posting_view_item
Col0    Col1    Col2    Col3    Col4    Col5
2       A       B       C       1       A
3       A       B       C       2       A
3       A       B       C       2       B

to achieve is that, instead of passing a raw string for (('A', 'B', 'C', 1), ('A', 'B', 'C', 2));, I would love to use a NpgSqlParameter with a collection of value set (i.e. for each column)).

So I've changed the C# snippet above and added the parameter

// ...
"WHERE (accounting_document, accounting_document_type, company_code, document_date_year) " +
"IN @values;";
var parameter = command.CreateParameter();
parameter.ParameterName = "@values";
parameter.NpgsqlDbType = NpgsqlDbType.Array;
parameter.NpgsqlValue = new object[,]
{
    { "A", "B", "C", 1 }, 
    { "A", "B", "C", 2 }
};
// Note: the same kind of issue arises when using tuples, i.e.
// ( "A", "B", "C", 1 )
// ( "A", "B", "C", 2 )
command.Parameters.Add(parameter);
using var reader = command.ExecuteReader();
// ...

Then I'm getting this exception:

Unhandled exception. System.ArgumentOutOfRangeException: Cannot set NpgsqlDbType to just Array, Binary-Or with the element type (e.g. Array of Box is NpgsqlDbType.Array | NpgsqlDbType.Box). (Parameter 'value')
   at Npgsql.NpgsqlParameter.set_NpgsqlDbType(NpgsqlDbType value)
   at Program.<Main>$(String[] args) in C:\Users\natalie-perret\Desktop\Personal\playground\csharp\CSharpPlayground\Program.cs:line 25

Then I've tried to work around that error with:

parameter.NpgsqlDbType = NpgsqlDbType.Array | NpgsqlDbType.Unknown;

but then getting another exception:

Unhandled exception. System.ArgumentException: No array type could be found in the database for element .<unknown>
   at Npgsql.TypeMapping.ConnectorTypeMapper.ResolveByNpgsqlDbType(NpgsqlDbType npgsqlDbType)
   at Npgsql.NpgsqlParameter.ResolveHandler(ConnectorTypeMapper typeMapper)
   at Npgsql.NpgsqlParameterCollection.ValidateAndBind(ConnectorTypeMapper typeMapper)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior)
   at Program.<Main>$(String[] args) in C:\Users\natalie-perret\Desktop\Personal\playground\csharp\CSharpPlayground\Program.cs:line 32

Seems that the type needs to be registered for some reason, actually if I don't specify the type:

Unhandled exception. System.NotSupportedException: The CLR type System.Object isn't natively supported by Npgsql or your PostgreSQL. To use it with a PostgreSQL composite
 you need to specify DataTypeName or to map it, please refer to the documentation.
   at Npgsql.TypeMapping.ConnectorTypeMapper.ResolveByClrType(Type type)
   at Npgsql.TypeMapping.ConnectorTypeMapper.ResolveByClrType(Type type)
   at Npgsql.NpgsqlParameter.ResolveHandler(ConnectorTypeMapper typeMapper)
   at Npgsql.NpgsqlParameter.Bind(ConnectorTypeMapper typeMapper)
   at Npgsql.NpgsqlParameterCollection.ValidateAndBind(ConnectorTypeMapper typeMapper)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior)
   at Program.<Main>$(String[] args) in C:\Users\natalie-perret\Desktop\Personal\playground\csharp\CSharpPlayground\Program.cs:line 31

The workaround I've ended up with is to rely on the jsonb support and in particular the jsonb_to_recordset function (see the PostgreSQL documentation section about json functions):

using System.Data;
using System.Text.Json;

using Npgsql;
using NpgsqlTypes;


var connectionStringBuilder = new NpgsqlConnectionStringBuilder
{
    Host     = "localhost",
    Port     = 5432,
    Username = "brand_payment_migration",
    Password = "secret",
    Database = "brand_payment"
};
using var connection = new NpgsqlConnection(connectionStringBuilder.ToString());
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = 
"SELECT id, accounting_document, accounting_document_type, company_code, document_date_year, posting_view_item " +
"FROM sch_brand_payment_data_lake_proxy.supplier_balances " +
"LEFT OUTER JOIN sch_brand_payment_data_lake_proxy.supplier_balance_items " +
"ON supplier_balances.id = supplier_balance_items.supplier_balance_id " +
"WHERE (accounting_document, accounting_document_type, company_code, document_date_year) " +
"IN (SELECT * FROM jsonb_to_recordset(@values) " +
"AS params (accounting_document text, accounting_document_type text, company_code text, document_date_year integer));";
var parameter = command.CreateParameter();
parameter.ParameterName = "@values";
parameter.NpgsqlDbType = NpgsqlDbType.Jsonb;
parameter.NpgsqlValue = JsonSerializer.Serialize(new []
{
    new Params("A", "B", "C", 1), 
    new Params("A", "B", "C", 2)
});
command.Parameters.Add(parameter);
using var reader = command.ExecuteReader();
using var dataTable = new DataTable();
dataTable.Load(reader);
var cols = dataTable.Columns.Cast<DataColumn>().ToArray();
Console.WriteLine(string.Join(Environment.NewLine, cols.Select((x, i) => $"Col{i} = {x}")));
Console.WriteLine(string.Join("\t", cols.Select((_, i) => $"Col{i}")));
foreach (var dataRow in dataTable.Rows.Cast<DataRow>())
{
    Console.WriteLine(string.Join("\t", dataRow.ItemArray));
}


public Params(
    string accounting_document, 
    string accounting_document_type,
    string company_code,
    int document_date_year);

Output:

Col0 = id
Col1 = accounting_document
Col2 = accounting_document_type
Col3 = company_code
Col4 = document_date_year
Col5 = posting_view_item
Col0    Col1    Col2    Col3    Col4    Col5
2       A       B       C       1       A
3       A       B       C       2       A
3       A       B       C       2       B

But this comes at the cost of adding an additional step of json serialization when passing the parameters. So other than that and building an insanely long string, I'm kinda puzzled at the fact there is no way to pass directly the actual values, without extra steps, to the NpgsqlParameter.NpgsqlValueproperty.

[Edit 2]

Adding a DbFiddle

[Edit 3]

The same jsonb "trick" can be used for feeding the data (albeit, same hiccups I've already mentioned above):

INSERT INTO sch_brand_payment_data_lake_proxy.supplier_balances
    (accounting_document, accounting_document_type, company_code, document_date_year)
SELECT * FROM jsonb_to_recordset(
    '[{"accounting_document":"E","accounting_document_type":"B","company_code":"C","document_date_year":1},
      {"accounting_document":"E","accounting_document_type":"B","company_code":"C","document_date_year":2}]'::jsonb)
       AS params (accounting_document text, accounting_document_type text, company_code text, document_date_year integer)
RETURNING id;

===

Additional information:

- Npgsql version: 6.0.0
- PostgreSQL version: PostgreSQL 12.6 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.2.1_pre1) 10.2.1 20201203, 64-bit
- Operating system: .NET 6.0

Activity

  1. changed the title [-]Passing a collection of collection, or a collection of tuples as parameters for clauses like `WHERE ... IN ...` or INSERT / UPDATE statements isn't working[/-] [+]Passing a collection of collection, or a collection of tuples as parameters for clauses like `WHERE ... IN ...` or `INSERT INTO` / `UPDATE... WHERE` statements isn't working[/+] on Apr 30, 2022
  2. roji commented on Apr 30, 2022

    @roji
    Member

    @natalie-o-perret are you basically asking for a way to send PostgreSQL records/row values as parameters ({ "A", "B", "C", 1 }), e.g. by providing a value tuple or object[] as a parameter value? That would also include an array of records over the above.

    If so, is this issue a duplciate of #2154?

  3. natalie-o-perret commented on Apr 30, 2022

    @natalie-o-perret
    Author

    @natalie-o-perret are you basically asking for a way to send PostgreSQL records/row values as parameters ({ "A", "B", "C", 1 }), e.g. by providing a value tuple or object[] as a parameter value? That would also include an array of records over the above.

    If so, is this issue a duplciate of #2154?

    Thanks for your answer, the issue is that like what @YohDeadfall said, atm it requires a specific in SQL:

    You should CREATE TYPE first, make the corresponding CLR class and map it using the MapComposite<T> method as it's said in the docs.

    You can map the type to ValueTuple<string, string>, but then it's not possible to map another PostgreSQL type to that struct. There is a one-to-one relation.

    CREATE TYPE book_info AS (author text, title text);
    public class BookInfo
    {
        public string Author { get; set; }
        public string Title { get; set; }
    }
    // in the static ctor of your DbContext
    NpgsqlConnection.GlobalTypeMapper.MapComposite<BookInfo>();
    new NpgsqlParameter("@items", items.Select(i => new BookInfo { Author = i.Author, Title = i.Title }).ToList())

    But this requires to create a specific type.

    It seems that @dhedey may have a solution / workaround, I'm gonna look at, need to look at the implications / limitations as well using UNNEST:

    If it helps anyone else, I have found quite a neat workaround for these types of queries using the UNNEST command, which can take multiple array parameters and zip them together into columns, which can be joined with the table to filter to the relevant columns.

    The use of the join is also more performant than the ANY/IN pattern in some cases.

    SELECT * FROM table WHERE (itemauthor, itemtitle) = ANY (('bob', 'hello'), ('frank', 'hi')...)
    

    Can be represented with:

     var authorsParameter = new NpgsqlParameter("@authors", NpgsqlDbType.Array | NpgsqlDbType.Varchar)
        { Value = authors.ToList() };
    var titlesParameter = new NpgsqlParameter("@titles", NpgsqlDbType.Array | NpgsqlDbType.Varchar)
        { Value = titles.ToList() };
    
    var results = dbContext.Set<MyRow>()
        .FromSqlInterpolated($@"
    SELECT
        t.*
    FROM UNNEST({authorsParameter}, {titlesParameter}) params (author, title)
    INNER JOIN table t
        ON t.author = params.author
        AND t.title = params.title
    ");
    

    NB - the Varchar can be replaced by other types for parameters which are arrays of other types (eg Bigint) - check out the NpgsqlDbType enum for more details.

  4. roji commented on Apr 30, 2022

    @roji
    Member

    [...] But this requires to create a specific type. [...]

    @natalie-o-perret so again, allowing you to send a PG record parameter via object[] or ValueType would obviate having to create a named, PG composite type, but would allow sending ad-hoc arrays. That's what #2154 tracks.

    The other solution above seem completely fine, though a bit more complex than simply sending an object[].

  5. natalie-o-perret commented on Apr 30, 2022

    @natalie-o-perret
    Author

    [...] But this requires to create a specific type. [...]

    @natalie-o-perret so again, allowing you to send a PG record parameter via object[] or ValueType would obviate having to create a named, PG composite type, but would allow sending ad-hoc arrays. That's what #2154 tracks.

    The other solution above seem completely fine, though a bit more complex than simply sending an object[].

    Well, the title is bit misleading, even going through the whole thread, is not super obvious that solving this issue would solve the same problem, and granted that I'm probably not the sharpest tool or that I'm must be a wee thick, but I thought it would be tackled by #2097 instead (but again, not entirely clear).

    Unless I'm mistaken, the expression = ANY (('bob', 'hello'), ('frank', 'hi')...) actually accepts an array of records, and not of composite types. PostgreSQL records are totally ad-hoc, weakly-typed bundles of values, and Npgsql does not provide any way of sending these at the moment. see #2097 for a discussion on mapping CLR value tuples, either to composites or to record types.

    Putting this on the backlog for now, we're unlikely to get around to this anytime soon.

    Okay seems the way composite is used, is implicitly to convey the meaning of composite type, gotcha.

    But I guess, I struggle to fully grasp the concept of record slash row the way they are used in the different articles or the way issues are titled for particular things to be solved.

    Looking at the official PostgreSQL documentation:

    43.3.4. Row Types

    name table_name%ROWTYPE;
    name composite_type_name;
    

    A variable of a composite type is called a row variable (or row-type variable). Such a variable can hold a whole row of a SELECT or FOR query result, so long as that query's column set matches the declared type of the variable. The individual fields of the row value are accessed using the usual dot notation, for example rowvar.field.

    43.3.5. Record Types

    name RECORD;
    

    Record variables are similar to row-type variables, but they have no predefined structure. They take on the actual row structure of the row they are assigned during a SELECT or FOR command. The substructure of a record variable can change each time it is assigned to. A consequence of this is that until a record variable is first assigned to, it has no substructure, and any attempt to access a field in it will draw a run-time error.

    Note that RECORD is not a true data type, only a placeholder. One should also realize that when a PL/pgSQL function is declared to return type record, this is not quite the same concept as a record variable, even though such a function might use a record variable to hold its result. In both cases the actual row structure is unknown when the function is written, but for a function returning record the actual structure is determined when the calling query is parsed, whereas a record variable can change its row structure on-the-fly.

    So it's not #2097 (which has been dropped + closed) 🤔?

    #2097 for a discussion on mapping CLR value tuples, either to composites or to record types.

    Sorry for asking clarifications 🤷‍♀️

    [EDIT] about the UNNEST workdaround, seems to be a fairly good workaround in hindsight, though, wondering how performant it is to extract each, but then this falls more under .NET Json serialization performance consideration.

    I've rewritten my initial C# stuff:

    using System.Data;
    
    using Npgsql;
    using NpgsqlTypes;
    
    
    var connectionStringBuilder = new NpgsqlConnectionStringBuilder
    {
        Host     = "localhost",
        Port     = 5432,
        Username = "brand_payment_migration",
        Password = "secret",
        Database = "brand_payment"
    };
    using var connection = new NpgsqlConnection(connectionStringBuilder.ToString());
    connection.Open();
    
    var selectStatement =
        "SELECT * FROM sch_brand_payment_data_lake_proxy.supplier_balances " +
        "WHERE (accounting_document, accounting_document_type, company_code, document_date_year) " +
        "IN (SELECT * FROM  unnest(" +
        "@accounting_document_texts, " +
        "@accounting_document_types, " +
        "@company_codes, " +
        "@document_date_years" +
        "))";
    
    var insertStatement = 
        "INSERT INTO sch_brand_payment_data_lake_proxy.supplier_balances " +
        "(accounting_document, accounting_document_type, company_code, document_date_year) " + 
        "SELECT * FROM unnest(" +
        "@accounting_document_texts, " +
        "@accounting_document_types, " +
        "@company_codes, " +
        "@document_date_years" + 
        ") RETURNING id;";
    
    var parameters = new (string Name, NpgsqlDbType DbType, object Value)[]
    {
        ("@accounting_document_texts", NpgsqlDbType.Array | NpgsqlDbType.Text,    new[] {"G", "G", "G"}),
        ("@accounting_document_types", NpgsqlDbType.Array | NpgsqlDbType.Text,    new[] {"Y", "Y", "Y"}),
        ("@company_codes",             NpgsqlDbType.Array | NpgsqlDbType.Text,    new[] {"Z", "Z", "Z"}),
        ("@document_date_years",       NpgsqlDbType.Array | NpgsqlDbType.Integer, new[] {1, 2, 3})
    };
    
    connection.ExecuteNewCommandAndWriteResultToConsole(insertStatement, parameters);
    connection.ExecuteNewCommandAndWriteResultToConsole(selectStatement, parameters);
    
    public static class Extensions
    {
        public static void AddParameter(this NpgsqlCommand command, string name, NpgsqlDbType dbType, object value)
        {
            var parameter = command.CreateParameter();
            parameter.ParameterName = name;
            parameter.NpgsqlDbType  = dbType;
            parameter.NpgsqlValue   = value;
            command.Parameters.Add(parameter);
        }
    
        public static NpgsqlCommand CreateCommand(this NpgsqlConnection connection, 
            string text, 
            IEnumerable<(string Name, NpgsqlDbType DbType, object Value)> parameters)
        {
            var command = connection.CreateCommand();
            command.CommandText = text;
            foreach (var (name, dbType, value) in parameters)
            {
                command.AddParameter(name, dbType, value);
            }
    
            return command;
        }
        public static void ExecuteAndWriteResultToConsole(this NpgsqlCommand command)
        {
            Console.WriteLine($"Executing command... {command.CommandText}");
            
            using var reader = command.ExecuteReader();
            using var dataTable = new DataTable();
            dataTable.Load(reader);
            var cols = dataTable.Columns.Cast<DataColumn>().ToArray();
            Console.WriteLine(string.Join(Environment.NewLine, cols.Select((x, i) => $"Col{i} = {x}")));
            Console.WriteLine(string.Join("\t", cols.Select((_, i) => $"Col{i}")));
            foreach (var dataRow in dataTable.Rows.Cast<DataRow>())
            {
                Console.WriteLine(string.Join("\t", dataRow.ItemArray));
            }
        }
    
        public static void ExecuteNewCommandAndWriteResultToConsole(this NpgsqlConnection connection, 
            string text,
            IEnumerable<(string Name, NpgsqlDbType DbType, object Value)> parameters)
        {
            using var command = connection.CreateCommand(text, parameters);
            command.ExecuteAndWriteResultToConsole();
        }
    }
    Executing command... INSERT INTO sch_brand_payment_data_lake_proxy.supplier_balances (accounting_document, accounting_document_type, company_code, document_date_year) SEL
    ECT * FROM unnest(@accounting_document_texts, @accounting_document_types, @company_codes, @document_date_years) RETURNING id;
    Col0 = id
    Col0
    28
    29
    30
    Executing command... SELECT * FROM sch_brand_payment_data_lake_proxy.supplier_balances WHERE (accounting_document, accounting_document_type, company_code, document_date_y
    ear) IN (SELECT * FROM  unnest(@accounting_document_texts, @accounting_document_types, @company_codes, @document_date_years))
    Col0 = id
    Col1 = accounting_document
    Col2 = accounting_document_type
    Col3 = company_code
    Col4 = document_date_year
    Col5 = accounting_doc_created_by_user
    Col6 = accounting_clerk
    Col7 = assignment_reference
    Col8 = document_reference_id
    Col9 = original_reference_document
    Col10 = payment_terms
    Col11 = supplier
    Col12 = supplier_name
    Col13 = document_date
    Col14 = posting_date
    Col15 = net_due_date
    Col16 = created_on
    Col17 = modified_on
    Col18 = pushed_on
    Col19 = is_modified
    Col20 = is_pushed
    Col0    Col1    Col2    Col3    Col4    Col5    Col6    Col7    Col8    Col9    Col10   Col11   Col12   Col13   Col14   Col15   Col16   Col17   Col18   Col19   Col20
    28      G       Y       Z       1                                                                                                                       False   False
    29      G       Y       Z       2                                                                                                                       False   False
    30      G       Y       Z       3                                                                                                                       False   False
    
  6. changed the title [-]Passing a collection of collection, or a collection of tuples as parameters for clauses like `WHERE ... IN ...` or `INSERT INTO` / `UPDATE... WHERE` statements isn't working[/-] [+]Passing a collection of collections, or a collection of tuples as parameters for clauses like `WHERE ... IN ...` or `INSERT INTO` / `UPDATE... WHERE` statements isn't working[/+] on Apr 30, 2022
  7. changed the title [-]Passing a collection of collections, or a collection of tuples as parameters for clauses like `WHERE ... IN ...` or `INSERT INTO` / `UPDATE... WHERE` statements isn't working[/-] [+]Passing a collection of collections, or a collection of tuples as a parameter value for clauses like `WHERE ... IN ...` or `INSERT INTO` / `UPDATE... WHERE` statements isn't working[/+] on Apr 30, 2022
  8. roji commented on Apr 30, 2022

    @roji
    Member

    So a composite type is an explicitly defined PG type - so you need to create it before you use it with CREATE TYPE. It corresponds to a row in the table, and in fact, when you create a table in PG, you're also creating a composite type with the same name. Since a composite is explicitly created, it generally makes sense to map it to a CLR type on the .NET side, and allow users to map the two (as in the docs).

    Re records, on the other hand:

    Unless I'm mistaken, the expression = ANY (('bob', 'hello'), ('frank', 'hi')...) actually accepts an array of records, and not of composite types. PostgreSQL records are totally ad-hoc, weakly-typed bundles of values, and Npgsql does not provide any way of sending these at the moment. see #2097 for a discussion on mapping CLR value tuples, either to composites or to record types.

    Now, I did a quick experimental implementation, and it turns out that PostgreSQL does not support parameterized input of record types; I get "input of anonymous composite types is not implemented". Unless I'm mistaken, that means that it's impossible to parameterize the following:

    WHERE (accounting_document, accounting_document_type, company_code, document_date_year)
    IN  (('A', 'B', 'C', 1), ('A', 'B', 'C', 2))

    I'll go ahead and close #2154 as not possible, but will keep this issue open in case you have any further questions.

  9. natalie-o-perret commented on Apr 30, 2022

    @natalie-o-perret
    Author

    Well, the raw SQL works:

    SELECT
        id,
        accounting_document,
        accounting_document_type,
        company_code,
        document_date_year,
        posting_view_item
    FROM sch_brand_payment_data_lake_proxy.supplier_balances
    LEFT OUTER JOIN sch_brand_payment_data_lake_proxy.supplier_balance_items
    ON supplier_balances.id = supplier_balance_items.supplier_balance_id
    WHERE (accounting_document, accounting_document_type, company_code, document_date_year)
    IN  (('A', 'B', 'C', 1), ('A', 'B', 'C', 2))

    but yea, with parameters instead, it doesn't 😞

    It's all cleared up on my end, thanks a ton for all your clarifications! 🙇‍♀️

    Closing the issue as I also consider it solved on my end ✅.

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions