Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mvYaF-0006f5-Ji for pgsql-general@arkaria.postgresql.org; Fri, 10 Dec 2021 05:36:40 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1mvYaE-0003gw-7U for pgsql-general@arkaria.postgresql.org; Fri, 10 Dec 2021 05:36:38 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mvSC2-00049N-QC for pgsql-general@lists.postgresql.org; Thu, 09 Dec 2021 22:47:15 +0000 Received: from nantes-m1.p27.eu ([172.105.247.37]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mvSBz-0005pH-Gp for pgsql-general@postgresql.org; Thu, 09 Dec 2021 22:47:13 +0000 Received: from [192.168.2.157] (10.244.88.92.rev.sfr.net [92.88.244.10]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (Client did not present a certificate) (Authenticated sender: jeff@p27.eu) by nantes-m1.p27.eu (Postfix) with ESMTPSA id 92684AC154 for ; Thu, 9 Dec 2021 22:47:09 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=p27.eu; s=mail; t=1639090029; bh=mBBJqOWC/BZyyv6aF3O7+mLFrsMXbphFoaCZJn132xY=; h=To:From:Subject:Date; b=RIO/NBwMFDbJtU6wo/9YG2wy/ZBmSblFZMJaXQI81OlToMi7hCy/A3x6hFzo4WNjv W0eVHSGtS5oUX4YD4Wb/2grGwn0lttekUW3lzuP3a59mw5B7VE5V47tR3Yoa/XSjOD IeBARyTXZzBwQfBd3rsouYg3ZXYMznRqmwluee2SubnKFvT+FsNnX6lKtJZ4+Kqs+5 reFzBw8ZFdvF080PIQtcbc9I/oAY1uhG9dpVmApAWXrVShPCw6CrzQVmZ5GMHyIblq TKnrbqnoLFMCplbFHMvSzrlCkktCr/04pjR5BT8wRSbYxMBRidaAWVWRzxXCUSJcmh dBN0bZoNAXSlg== To: Postgres General From: Jeff Abrahamson Subject: pqxx accumulating a transaction Message-ID: <104f5ce7-823d-69dd-df32-fbbc1aace857@p27.eu> Date: Thu, 9 Dec 2021 23:47:08 +0100 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Thunderbird/78.14.0 MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="------------D8A6EB9072E6124F940314DD" Content-Language: en-GB List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk This is a multi-part message in MIME format. --------------D8A6EB9072E6124F940314DD Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: base64 SSBhbSBhY2N1bXVsYXRpbmcgYSB0cmFuc2FjdGlvbiB1c2luZyBsaWJwcXh4IGFuZCBzdXNw ZWN0IEknbSBkb2luZwpzb21ldGhpbmcgb3Zlcmx5IHRvcnR1b3VzIHRvIGdldCB3aGVyZSBJ J20gZ29pbmcuCgpJIGRvbid0IG1lYW4gdG8gbWFrZSB0aGlzIHF1ZXN0aW9uIGxvbmdlciB0 aGFuIGl0IG5lZWRzIHRvIGJlLCBidXQgSQp0aGluayBjb250ZXh0IHdpbGwgaGVscC7CoCBT byBJJ2xsIHN0YXJ0IGJ5IGV4cGxhaW5pbmcgYnJpZWZseSBob3cgSSBnb3QKdG8gd2hlcmUg SSBhbS7CoCBBbmQgdGhlbiBJJ2xsIHNob3cgd2hlcmUgSSBhbSwgd2hpY2ggSSdtIHByZXR0 eSBzdXJlIGlzCmFidXNpdmUgYW5kIG5vdCBob3cgbGlicHF4eCBtZWFucyBmb3I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wMjcuZXUvamVmZi8K aHR0cDovL21vYmlsaXRhaW5zLmZyLwoK --------------D8A6EB9072E6124F940314DD Content-Type: text/html; charset=utf-8 Content-Transfer-Encoding: 8bit

I am accumulating a transaction using libpqxx and suspect I'm doing something overly tortuous to get where I'm going.

I don't mean to make this question longer than it needs to be, but I think context will help.  So I'll start by explaining briefly how I got to where I am.  And then I'll show where I am, which I'm pretty sure is abusive and not how libpqxx means for me to do things.

Intro: the naive approach to doing thousands of inserts

I have some code that wants to write a bunch of stuff to the database, typically INSERT ... ON CONFLICT UPDATE. Roughly, this code is looping over some container and generating the needed SQL to insert each container object that needs inserting.

The naive way to do this (skipping error/exception handling for the moment) is thus:

pqxx::work txn(conn);
ostringstream sql_stmt;
Container rows;
for (const auto& row : rows) {
    if (row.IsDirty()) {
        RowToSQL(sql_stmt, row, txn);
        txn.exec(sql_stmt.str());
        // Clear sql_stmt here.
    }
}
txn.commit();

The function RowToSQL() takes a transaction object so that it can quote strings appropriately using txn.quote().

This is inefficient, however: calling exec() over and over turns out to be quite slow.

So instead I build up a bunch of statements in the ostringstream, thus:

pqxx::work txn(conn);
ostringstream sql_stmt;
Container rows;
for (const auto& row : rows) {
    if (row.IsDirty()) {
        RowToSQL(sql_stmt, row, txn);
        if (++counter > kExecuteThreshold || sql_stmt.IsGettingRatherBig()) {
            txn.exec(sql_stmt.str());
            // Clear sql_stmt, reset counter here.
        }
        if (count > kCommitThreshold) {
            txn.commit();
            // Reset statement counter here.
        }
    }
}
// Final commit here.

I chose the two thresholds based on performance testing in our environment.  Think 100 and 10,000 for order of magnitude.

This worked until it didn't, because re-using the transaction this way leads to conflicts.

Attempt to activate transaction<READ COMMITTED> which is already closed.

I mostly understand all this.

This leads me to write something that has weird code smell, and I so suspect I've misunderstood how postgresql / libpqxx intend to be used.

Adding back error/exception handling, I've now written this based on lots of doc reading:

Less naive but weird code smell

// Has weird code smell.

pqxx::nontransaction non_txn;
ostringstream sql_stmt;
Container rows;
Vector<string> transactions;
for (const auto& row : rows) {
    if (row.IsDirty()) {
        RowToSQL(sql_stmt, row, non_txn);
        if (++counter > kExecuteThreshold || sql_stmt.IsGettingRatherBig()) {
            transactions.push_back(sql_stmt.str());
            // Clear sql_stmt, reset counter here.
        }
        if (count > kCommitThreshold) {
            try {
                pqxx::work txn(conn);
                for (const string& trans : transactions) {
                    txn.exec(trans);
                }
                txn.commit();
                transactions.clear();
                // Reset statement counter here.
            } catch (const exception& e) {
                txn.abort();    // Pedantic, happens on destruction.
                YellowAlert();  // Something appropriate.
            }
        }
    }
}
// Final commit here.

It seems quite wrong to me that I should build up this vector of things to execute and maintain these custom-tuned execution/transaction thresholds rather than using some facility of libpqxx. That is, this pattern seems common enough to me that the complexity I'm starting to see strikes me as my own misunderstanding.

Any pointers much appreciated.

-- 
Jeff Abrahamson
+33 6 24 40 01 57
+44 7920 594 255

http://p27.eu/jeff/
http://mobilitains.fr/
--------------D8A6EB9072E6124F940314DD--