19 #include <QRegularExpression>
21 #include <nlohmann/json.hpp>
23 using namespace nlohmann;
25 static void jumpSpace(
const QString &txt,
int &i )
27 while ( i < txt.length() && txt.at( i ).isSpace() )
31 QString QgsPostgresStringUtils::getNextString(
const QString &txt,
int &i,
const QString &sep )
34 QString cur = txt.mid( i );
35 if ( cur.startsWith(
'"' ) )
37 const QRegularExpression stringRe( QRegularExpression::anchoredPattern(
"^\"((?:\\\\.|[^\"\\\\])*)\".*" ) );
38 const QRegularExpressionMatch match = stringRe.match( cur );
39 if ( !match.hasMatch() )
41 QgsMessageLog::logMessage( QObject::tr(
"Cannot find end of double quoted string: %1" ).arg( txt ), QObject::tr(
"PostgresStringUtils" ) );
44 i += match.captured( 1 ).length() + 2;
46 if ( !QStringView{txt}.mid( i ).startsWith( sep ) && i < txt.length() )
48 QgsMessageLog::logMessage( QObject::tr(
"Cannot find separator: %1" ).arg( txt.mid( i ) ), QObject::tr(
"PostgresStringUtils" ) );
52 return match.captured( 1 ).replace( QLatin1String(
"\\\"" ), QLatin1String(
"\"" ) ).replace( QLatin1String(
"\\\\" ), QLatin1String(
"\\" ) );
56 int sepPos = cur.indexOf( sep );
62 i += sepPos + sep.length();
63 return cur.left( sepPos ).trimmed();
69 QVariantList variantList;
72 QString newVal =
string.mid( 1,
string.length() - 2 );
74 if ( newVal.trimmed().startsWith(
'{' ) )
78 QString subarray = newVal;
79 while ( !subarray.isEmpty() )
82 int openedBrackets = 1;
84 while ( i < subarray.length() && openedBrackets > 0 )
88 if ( subarray.at( i ) ==
'}' && !escaped ) openedBrackets--;
89 else if ( subarray.at( i ) ==
'{' && !escaped ) openedBrackets++;
91 escaped = !escaped ? subarray.at( i ) ==
'\\' :
false;
94 variantList.append( subarray.left( ++i ) );
95 i = subarray.indexOf(
',', i );
96 i = i > 0 ? subarray.indexOf(
'{', i ) : -1;
100 subarray = subarray.mid( i );
106 while ( i < newVal.length() )
108 const QString value = getNextString( newVal, i, QStringLiteral(
"," ) );
109 if ( value.isNull() )
111 QgsMessageLog::logMessage( QObject::tr(
"Error parsing PG like array: %1" ).arg( newVal ), QObject::tr(
"PostgresStringUtils" ) );
114 variantList.append( value );
125 for (
const QVariant &v : std::as_const( list ) )
130 case QVariant::Type::Int:
131 case QVariant::Type::LongLong:
132 sl.push_back( v.toString() );
135 QString newS = v.toString();
136 if ( newS.startsWith(
'{' ) )
138 sl.push_back( newS );
142 newS.replace(
'\\', QLatin1String( R
"(\\)" ) );
143 newS.replace( '\"', QLatin1String( R
"(\")" ) );
144 sl.push_back( "\"" + newS +
"\"" );
150 QString s = sl.join(
',' ).prepend(
'{' ).append(
'}' );