I am trying to insert a number of text files with json data into a database. Each file is is suffixed with 1,2,3... etc. (shapes_routes1.json, shapes_routes2.json etc.). To do this I am concatenating an index to the base file name from within a loop. I am getting this error:
psql:insertshapes.sql:37: ERROR: syntax error at or near "file_path"
LINE 17: copy temp_json from file_path;
Can you not supply copy from with a variable as the path? Or is there something I need to do to the variable (file_path) so psql knows its a path?
Any help or recommendations on this would be appreciated.
delete from shapes;
DO $$
declare
n INTEGER := 1;
prefix TEXT := '/Users/me/model/json/filechunks/shapes_routes';
i TEXT := NULL;
file_path TEXT := NULL;
BEGIN
LOOP
EXIT WHEN n = 166;
i := CAST(n as TEXT);
file_path := prefix || i || '.json';
n := n + 1;
create temporary table temp_json (values text);
copy temp_json from file_path; --GETTING ERROR ON THIS LINE
insert into shapes
select values->>'shape_id' as shape_id,
(CAST(values->>'shape_pt_lat' as real)) as shape_pt_lat,
(CAST(values->>'shape_pt_lon' as real)) as shape_pt_lon,
(CAST(values->>'shape_pt_sequence' as integer)) as shape_pt_sequence,
(CAST(values->>'shape_dist_traveled' as real)) as shape_dist_traveled,
values->>'route_id' as route_id
from (
select json_array_elements(replace(values,'\','\\')::json) as values
from temp_json
) a;
drop table temp_json;
END LOOP;
END $$;
shapes_routes1.jsonshapes_routes2.json... Why are you concatenating a/on its name? It will make the name as/Users/me/model/json/filechunks/shapes_routes/1.jsonand not the names you mention...truncateit before each import.