Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

What does it mean to clone database connection?



  • I have some code that looks like this that establishes connection to postgresql database:
    @
    ...
    QSqlDatabase db;
    QString new_name;

    for (int i = 0; i < 50; i++) {
      new_name = Qstring("%1_%2").arg(db_name).arg(i); 
    
      if (!QSqlDatabase::contains(new_name)) {
        if (i > 0) {
          QString previous = QString("%1_%2").arg(db_name).arg(i - 1);
    

    #ifdef XKGATEWAY_DEBUG
    Log::write(QString("Cloning existing DB connection "%1" as "%2"...\n").arg(previous).arg(new_name));
    #endif
    db = QSqlDatabase::cloneDatabase(db, previous);
    }
    break;
    }
    }

    m_db_connection = new_name;
    if (!db.isValid()) {
      db = QSqlDatabase::addDatabase("QPSQL", new_name);
      db.setHostName(config["host"].toString());
      db.setDatabaseName(config["database"].toString());
      db.setUserName(config["username"].toString());
      db.setPassword(config["password"].toString());
      db.setPort(5432);
    }
    
    if (db.open()) {
    ...@
    

    The QSqlDatabase class represents a connection to a database. The QSqlDatabase class provides an interface for accessing a database through a connection. An instance of QSqlDatabase represents the connection. The connection provides access to the database via one of the supported database drivers.

    The cloneDatabase method clones the database connection other and stores it as connectionName. All the settings from the original database, e.g. databaseName(), hostName(), etc., are copied across. Does nothing if other is an invalid database. Returns the newly created database connection.

    What does it mean to clone database connection and why would someone want to clone 50 database connections?


  • Lifetime Qt Champion

    Hi,

    In short it's creating a new connection using the same set of parameters with a different name so you can use it from a different thread and avoid having to set all the parameters again.

    This code doesn't clone the connection 50 times, It clones it once he can find an "available" name with a parameter up to 50. But there are other flaws in it so if you can, I would recommend to analyze what this code should do (e.g. the function/object purpose) and refactor it to do it right.


Log in to reply