How to abort JDBC Postgresql CopyManager copying?

前端 未结 2 966
野趣味
野趣味 2021-01-14 20:03

Is there a way to cancel the copying process started by calling copyIn() method in a separate thread?

Say, I have a list of csv-files which I need to co

2条回答
  •  萌比男神i
    2021-01-14 20:18

    Disclaimer: I haven't tried this and I just got the idea by looking at the source code

    There is a CopyManager.copyIn(String sql) method that returns an instance of the CopyIn interface which in turn is a descendant of CopyOperation. That interface has a cancelCopy() method.

    See the JavaDocs here: http://jdbc.postgresql.org/documentation/publicapi/org/postgresql/copy/CopyOperation.html#cancelCopy%28%29

    But the methods that take a stream to copy the data only return a long value, so no way of using the instance of the CopyOperation used there.

    However, when looking at the source code of the copyIn() method this seems quite easy to do on your own.

    So instead of calling copyIn(String, Reader) you basically use the code from that method in your code:

    // your code 
    CopyManager copyManager = 
           new CopyManager((BaseConnection) new DataSource().connect());
    FileReader from = ...  // different name!
    int bufferSize = 65536;
    
    // here starts the copy of the driver's implementation of the copyIn() method.
    
    char[] cbuf = new char[bufferSize];
    int len;
    
    // if you store the instance of the CopyIn interface in an instance variable you 
    // should be able to call cancelCopy() on it
    CopyIn cp = copyManager.copyIn(sql);  
    
    try {
        while ( (len = from.read(cbuf)) > 0) {
            byte[] buf = encoding.encode(new String(cbuf, 0, len));
            cp.writeToCopy(buf, 0, buf.length);
        }
        return cp.endCopy();
    } finally { // see to it that we do not leave the connection locked
        if(cp.isActive())
            cp.cancelCopy();
    }
    

提交回复
热议问题