0

My function definition is this way, and it's throwing an error

CREATE OR REPLACE FUNCTION traffic.addcsv (
      filename text
    )
    RETURNS void AS
    $body$
    BEGIN
    DROP TABLE IF EXISTS traffic.tsdata;

    create table if not EXISTS traffic.tsdata
    (
        ldir text,
        dtime timestamp,
        epoch integer,
        ln_m integer,
        freeflow real,
        spdlimit integer,
        cnt integer,
        mean_spd real,
        stddev real,
        mn integer,
        mx integer,
        conf integer
    );

    COPY traffic.tsdata FROM '$1' DELIMITER ',' CSV HEADER;

    CREATE TABLE IF NOT EXISTS traffic.psdata
    (
         l_id BIGINT,
         direction char(1),
         dtime timestamp,
         day_number SMALLINT,
         epoch smallint,
         length_m integer,
         freeflow smallint,
         spdlimit smallint,
         cnt integer,
         mean_speed smallint,
         stddev double precision ,
         mn smallint,
         mx SMALLINT,
         confidence smallint
    ); 

    INSERT INTO traffic.psdata (
    l_id,
    direction,
    dtime,
    day_number,
    epoch,
    length_m,
    freeflow,
    spdlimit,
    cnt,
    mean_speed,
    stddev,
    mn,
    mx,
    confidence
    )
    SELECT
            (replace ( (replace(ldir,'F','')) ,'T',''  )::integer,
        RIGHT(tsdata.ldir,1)::char(1) ,
            dtime,
        EXTRACT(ISODOW FROM traffic.tsdata.dtime)::smallint ,
            epoch,
            ln_m,
            freeflow,
        spdlimit,
            cnt,
            mean_spd,
            stddev,
            mn,
            mx,
            conf)
    FROM traffic.tsdata;

    END;
    $body$
    LANGUAGE 'plpgsql'
    VOLATILE
    CALLED ON NULL INPUT
    SECURITY INVOKER
    PARALLEL UNSAFE
    COST 100;

ERROR: could not open file "$1" for reading: No such file or directory HINT: COPY FROM instructs the PostgreSQL server process to read a file. You may want a client-side facility such as psql's \copy. CONTEXT: SQL statement "COPY traffic.tsdata FROM '$1' DELIMITER ',' CSV HEADER" PL/pgSQL function traffic.addcsv(text) line 21 at SQL statement

1 Answer 1

1

I don't think PL/pgSQL allows variables in a COPY statement.

You can do it with dynamic SQL:

EXECUTE format('COPY traffic.tsdata FROM %L DELIMITER '','' CSV HEADER', $1);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.