Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^3: Help Sorting a CSV File

by erix (Parson)
on Oct 07, 2019 at 14:20 UTC ( #11107135=note: print w/replies, xml ) Need Help??


in reply to Re^2: Help Sorting a CSV File
in thread Help Sorting a CSV File

I agree.

However, there is a another step in-between text and database, in the form of a "Foreign Data Wrapper", to let the database serve up the underlying (csv-)textfile:

psql -qX << SQL_TXT create server if not exists temp_fs foreign data wrapper file_fdw; drop foreign table if exists ft_pm2 cascade; create foreign table ft_pm2 ( "CAT_HEADER" text , "SUPPLIER_CODE" text , "CUSTOMER_CODE" text , "F4" text , "F5" text , "F6" text , "F7" text , "F8" numeric ) server temp_fs options ( format 'csv' , header 'true' , filename '/tmp/data.txt' ); copy(select * from ft_pm2 order by 2, 3) to stdout with (format csv, h +eader true); SQL_TXT

Results are (again):

CAT_HEADER,SUPPLIER_CODE,CUSTOMER_CODE,F4,F5,F6,F7,F8 CAT_LINE,0001P,ABC12345,20190924,,1,Z,3.36 CAT_LINE,0001P,ABC23456,20190924,,1,Z,2.14 CAT_LINE,0001P,ABC34567,20190924,,1,Z,12.23 CAT_LINE,0002P,ABC12345,20190924,,1,Z,4.26 CAT_LINE,0002P,ABC23456,20190924,,1,Z,1.21 CAT_LINE,0002P,ABC34567,20190924,,1,Z,22.24

Such SQL using a 'Foreign Table' reads the underlying csv/text file(s). The annoying part is setting up the table , for instance in the case of tables with hundreds of columns you need a separate little application to do that, and this is where perl comes in handy (reading the header line and turning it into the CREATE TABLE column-list).

Weaknesses and strengths:

Advantages: SQL access to csv data. DBD::CSV delivers SQL as in SQL::Statement::Syntax which is nice but basic. The Data Wrapper's Foreign Table gives you access to the data via the full postgres SQL engine: Window Functions, Grouping Sets/Cube/Rollup, Generated Columns, Partitioning , etc., etc.)

Disadvantages: Needs Postgres, and with extension file_fdw installed. Table remains read-only. No indexing possible, so that huge csv-files can make it slow (alhough 'copying' onto a materialized view [3] on the foreign table makes of course indexing possible again). Filesystem access for the postgres superuser is necessary.

It all depends what you want to do.

[1] file_fdw - this foreign data wrapper reads text files

[2] Create Server

[3] Create Foreign Table

[4] Create Materialized View

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11107135]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (9)
As of 2019-11-19 12:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (95 votes). Check out past polls.

    Notices?