How to export full-text files with SQL?

后端 未结 2 1159
悲哀的现实
悲哀的现实 2021-01-13 18:31

There are an easy way to import/export full-text fields as files?

  • that solve the problem of \"load as multiple lines\".
    Trying with SQ

2条回答
  •  忘掉有多难
    2021-01-13 18:53

    You can use plpythonu f.open(), f.write(), f.close() within a postgres function to write to a file.

    Language extension would need to be installed.,

    https://www.postgresql.org/docs/8.3/static/plpython.html

    Working example from the mailing list. https://www.postgresql.org/message-id/flat/20041106125209.55697.qmail%40web51806.mail.yahoo.com#20041106125209.55697.qmail@web51806.mail.yahoo.com

    for example plpythonu

    CREATE FUNCTION makefile(p_file text, p_content text) RETURNS text AS $$
      o=open(args[0],"w")
      o.write(args[1])
      o.close()
      return "ok"
    $$ LANGUAGE PLpythonU;
    

    PS: for safe implementation see this example.


    Preparing

    There are a not-so-obvious procedure to use PLpython extension. Supposing an UBUNTU server:

    1. On SQL check SELECT version().
    2. On terminal check sudo apt install postgresql-plpython listed versions.
    3. Install the correct version, eg. sudo apt install postgresql-plpython-9.6.
    4. Back to SQL do CREATE EXTENSION plpythonu.

    Testing

    The /tmp is default, to create or use other folder, eg. /tmp/sandbox,
    use sudo chown postgres.postgres /tmp/sandbox.

    Suppose the tables of the question's examples. SQL script, repeating some lines:

      DROP TABLE IF EXISTS ttmp; 
      DROP TABLE IF EXISTS xtmp; 
    
      CREATE TABLE ttmp (x text);
      COPY ttmp FROM '/tmp/sandbox/original.xml' ( FORMAT text );
      COPY (SELECT x FROM ttmp) TO '/tmp/sandbox/test1-good.xml' (format TEXT);
    
      CREATE TABLE xtmp (x xml);
      INSERT INTO  xtmp (x) 
         SELECT array_to_string(array_agg(x),E'\n')::xml FROM ttmp
      ;
    
      COPY (select x::text from xtmp) 
      TO '/tmp/sandbox/test2-bad.xml' ( FORMAT text );
    
      SELECT makefile('/tmp/sandbox/test3-good.xml',x::text) FROM xtmp;
    

    The sha1sum *.xml output of my XML original file:

    4947..  original.xml
    4947..  test1-good.xml
    949f..  test2-bad.xml
    4947..  test3-good.xml
    

提交回复
热议问题