// Get a handle for the domains database.
QSqlDatabase domainsDatabase = QSqlDatabase::database(CONNECTION_NAME);
- // Instantiate a domain lookup query.
- QSqlQuery domainLookupQuery(domainsDatabase);
+ // Instantiate the all domain names query.
+ QSqlQuery allDomainNamesQuery(domainsDatabase);
+
+ // Set the query to be forward only (increases performance while iterating over the query).
+ allDomainNamesQuery.setForwardOnly(true);
+
+ // Prepare the query.
+ allDomainNamesQuery.prepare("SELECT " + _ID + "," + DOMAIN_NAME + " FROM " + DOMAINS_TABLE);
+
+ // Execute the query.
+ allDomainNamesQuery.exec();
+
+ // Create a domains settings map.
+ QMap<QString, int> domainSettingsMap;
+
+ // Populate the domain settings map.
+ while (allDomainNamesQuery.next())
+ {
+ // Add the domain name and database ID to the map.
+ domainSettingsMap.insert(allDomainNamesQuery.record().field(DomainsDatabaseHelper::DOMAIN_NAME).value().toString(),
+ allDomainNamesQuery.record().field(DomainsDatabaseHelper::_ID).value().toInt());
+ }
+
+ // Initialize the database ID tracker.
+ int databaseId = -1;
- // Create a hostname field.
- QSqlField hostnameField(DOMAIN_NAME, QVariant::String);
+ // Get the database ID if the hostname is found in the domain settings set.
+ if (domainSettingsMap.contains(hostname))
+ {
+ databaseId = domainSettingsMap.value(hostname);
+ }
+
+ // Create a subdomain string.
+ QString subdomain = hostname;
+
+ // Check all the subdomains of the hostname.
+ while ((databaseId == -1) && subdomain.contains(".")) // Stop checking when a match is found or there are no more `.` in the hostname.
+ {
+ // Check to see if the domain settings map contains the subdomain with a `*.` prepended.
+ if (domainSettingsMap.contains("*." + subdomain))
+ {
+ // Get the database ID.
+ databaseId = domainSettingsMap.value("*." + subdomain);
+ }
- // Set the hostname field value.
- hostnameField.setValue(hostname);
+ // Strip out the first subdomain.
+ subdomain = subdomain.section('.', 1);
+ }
- // SQL escape the hostname field.
- QString sqlEscapedHostname = domainsDatabase.driver()->formatValue(hostnameField);
+ // Instantiate the domain lookup query.
+ QSqlQuery domainLookupQuery(domainsDatabase);
// Prepare the domain lookup query.
- domainLookupQuery.prepare("SELECT * FROM " + DOMAINS_TABLE + " WHERE " + DOMAIN_NAME + " = " + sqlEscapedHostname);
+ domainLookupQuery.prepare("SELECT * FROM " + DOMAINS_TABLE + " WHERE " + _ID + " = " + QString::number(databaseId));
// Execute the query.
domainLookupQuery.exec();
// Return the query.
return domainLookupQuery;
}
-