Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres integer arrays as parameters?

I understand that in Postgres pure, you can pass an integer array into a function but that this isn't supported in the .NET data provider Npgsql.

I currently have a DbCommand into which I load a call to a stored proc, add in a parameter and execute scalar to get back an Id to populate an object with.

This now needs to take n integers as arguments. These are used to create child records linking the newly created record by it's id to the integer arguments.

Ideally I'd rather not have to make multiple ExecuteNonQuery calls on my DbCommand for each of the integers, so I'm about to build a csv string as a parameter that will be split on the database side.

I normally live in LINQ 2 SQL savouring the Db abstraction, working on this project with manual data access it's all just getting a bit dirty, how do people usually go about passing these kinds of parameters into postgres?

like image 562
Tristan Warner-Smith Avatar asked Feb 20 '09 17:02

Tristan Warner-Smith


People also ask

How do I declare an array variable in PostgreSQL?

PostgreSQL Array type PL/pgSQL in PostgreSQL allows us to declare a variable as an ARRAY type. This ARRAY can be either a base or a custom type. For example, if we want to store a list of PINCODE values, then, we can declare the variable as v_pincode INT[].

Can you store an array in Postgres?

PostgreSQL allows columns of a table to be defined as variable-length multidimensional arrays. Arrays of any built-in or user-defined base type, enum type, composite type, range type, or domain can be created.


1 Answers

See: http://www.postgresql.org/docs/9.1/static/arrays.html

If your non-native driver still does not allow you to pass arrays, then you can:

  • pass a string representation of an array (which your stored procedure can then parse into an array -- see string_to_array)

    CREATE FUNCTION my_method(TEXT) RETURNS VOID AS $$  DECLARE        ids INT[]; BEGIN        ids = string_to_array($1,',');        ... END $$ LANGUAGE plpgsql; 

    then

    SELECT my_method(:1) 

    with :1 = '1,2,3,4'

  • rely on Postgres itself to cast from a string to an array

    CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$         ... END $$ LANGUAGE plpgsql; 

    then

    SELECT my_method('{1,2,3,4}') 
  • choose not to use bind variables and issue an explicit command string with all parameters spelled out instead (make sure to validate or escape all parameters coming from outside to avoid SQL injection attacks.)

    CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$         ... END $$ LANGUAGE plpgsql; 

    then

    SELECT my_method(ARRAY [1,2,3,4]) 
like image 75
vladr Avatar answered Sep 21 '22 17:09

vladr