/
standardsqlprovider.cpp
793 lines (721 loc) · 31 KB
/
standardsqlprovider.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
/*
* Orm4Qt - An Object Relational Mapping Library for the Qt Framework
* Copyright (c) 2014, Michael Dougras da Silva, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
*/
#include "standardsqlprovider.h"
using namespace Orm4Qt;
StandardSqlProvider::StandardSqlProvider() : SqlProvider()
{}
StandardSqlProvider::~StandardSqlProvider()
{}
std::shared_ptr<QSqlQuery> StandardSqlProvider::generateInsert(Class *reflect, const QList<int> &fieldsno)
{
//Check if there are fields to insert
if(fieldsno.isEmpty())
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::InvalidRequest, QString("There aren't fields to insert. Check if the name of the fields informed are valid.")));
return nullptr;
}//End Check if there are fields to insert
//Create the string to store the sql command
QString sqlstr;
QTextStream sql(&sqlstr);
QString columnsstr;
QTextStream columns(&columnsstr);
QString valuesstr;
QTextStream values(&valuesstr);
QMap<QString, QVariant> bindings;
//Insert the prefix of the command
sql << "INSERT INTO ";
//Add table name
if(!reflect->tags()["table"].isNull())
{
sql << reflect->tags()["table"].toString() << " (";
}
else
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::ConfigurationError, QString("The tag 'table' was not supplied for the class '%1'.").arg(reflect->tags()["name"].toString())));
return nullptr;
}//End add table name
//Add properties in the sql statemtent
for(int index : fieldsno)
{
Property *prop = reflect->properties()[index];
if(prop->tags()["column"].isNull())
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::ConfigurationError, QString("The tag 'column' was not supplied for the property '%1' in the class '%2'.")
.arg(prop->tags()["name"].toString())
.arg(reflect->tags()["name"].toString())));
return nullptr;
}
else
{
columns << prop->tags()["column"].toString() << ", ";
values << prop->tags()["column"].toString().prepend(":") << ", ";
bindings.insert(prop->tags()["column"].toString().prepend(":"), prop->value());
}
}//End add properties in the sql statement
//Insert version column
if(!reflect->tags()["versioncolumn"].isNull())
{
QString versioncolumn = reflect->tags()["versioncolumn"].toString();
columns << versioncolumn << ", ";
values << ":" << versioncolumn << ", ";
bindings.insert(versioncolumn.prepend(":"), reflect->tags()["version"]);
}//End insert version column
//Combine sql statement with columns and values
sql << columnsstr.left(columnsstr.size()-2) << ") VALUES(";
sql << valuesstr.left(valuesstr.size()-2) << ");";
//End combine sql statement with columns and values
//Create and validate query
std::shared_ptr<QSqlQuery> query(new QSqlQuery(QSqlDatabase::database(databaseConnectionName())));
if(query->prepare(sqlstr))
{
//Bind values of the insert
for(auto iter=bindings.begin(); iter!=bindings.end(); ++iter)
{
query->bindValue(iter.key(), iter.value());
}//End bind values of the insert
//Return the query object
return query;
}
else
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::DatabaseError, QString("Invalid SQL statement for insert a row. See the sqlerror attached."), query->lastError()));
return nullptr;
}//End create and validate query
}
std::shared_ptr<QSqlQuery> StandardSqlProvider::generateUpdate(Class *reflect, const QList<int> &fieldsno)
{
//Check if there are fields to update
if(fieldsno.isEmpty())
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::InvalidRequest, QString("There aren't fields to update. Check if the name of the fields informed are valid. In the update operation the autoid, autocolumn and primary keys properties are ignored.")));
return nullptr;
}//End Check if there are fields to update
//Objects to store the sql command
QString sqlstr;
QTextStream sql(&sqlstr);
//Begin the command
sql << "UPDATE ";
//Insert the table name
if(!reflect->tags()["table"].isNull())
{
sql << reflect->tags()["table"].toString() << " SET ";
}
else
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::ConfigurationError, QString("The tag 'table' was not supplied for the class '%1'.").arg(reflect->tags()["name"].toString())));
return nullptr;
}//End insert the table name
//Iterating over the fields
QMap<QString, QVariant> bindings;
for(int index: fieldsno)
{
Property *prop = reflect->properties()[index];
//Add the set statements
if(!prop->tags()["column"].isNull())
{
sql << prop->tags()["column"].toString()
<< " = "
<< prop->tags()["column"].toString().prepend(":")
<< ", ";
QVariant value = prop->value();
bindings.insert(prop->tags()["column"].toString().prepend(":"), value);
}
else
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::ConfigurationError, QString("The tag 'column' was not supplied for the property '%1' in the class '%2'.")
.arg(prop->tags()["name"].toString())
.arg(reflect->tags()["name"].toString())));
return nullptr;
}//End add set statements
}//End iterate over the fields
//Add the new version
if(!reflect->tags()["newversion"].isNull())
{
sql << reflect->tags()["versioncolumn"].toString()
<< " = "
<< reflect->tags()["versioncolumn"].toString().prepend(":new")
<< ", ";
bindings.insert(reflect->tags()["versioncolumn"].toString().prepend(":new"), reflect->tags()["newversion"]);
}//End add the new version
//Include the where clause
sqlstr = sqlstr.left(sqlstr.size()-2) + " ";
sql << "WHERE ";
//Add the autoid
if(!reflect->tags()["autoid"].isNull())
{
sql << reflect->tags()["autoid"].toString()
<< " = "
<< reflect->tags()["autoid"].toString().prepend(":")
<< " AND ";
bindings.insert(reflect->tags()["autoid"].toString().prepend(":"), reflect->tags()["id"]);
}
//Add the version check
if(!reflect->tags()["versioncolumn"].isNull())
{
sql << reflect->tags()["versioncolumn"].toString()
<< " = "
<< reflect->tags()["versioncolumn"].toString().prepend(":")
<< " AND ";
bindings.insert(reflect->tags()["versioncolumn"].toString().prepend(":"), reflect->tags()["version"]);
}
//QString autocolumn = reflect->tags()["autocolumn"].toString();
//Iterating over the keys
for(Property *prop: reflect->properties())
{
if(prop->tags()["key"].toBool()) // || (!autocolumn.isNull() && prop->tags()["name"].toString()==autocolumn))
{
if(prop->tags()["column"].isNull())
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::ConfigurationError, QString("The tag 'column' was not supplied for the property '%1' in the class '%2'.")
.arg(prop->tags()["name"].toString())
.arg(reflect->tags()["name"].toString())));
}
else
{
sql << prop->tags()["column"].toString()
<< " = "
<< prop->tags()["column"].toString().prepend(":")
<< " AND ";
bindings.insert(prop->tags()["column"].toString().prepend(":"), prop->value());
}
}
}//End iterating over the keys
sqlstr = sqlstr.left(sqlstr.size()-4);
//Create the query object
std::shared_ptr<QSqlQuery> query(new QSqlQuery(QSqlDatabase::database(databaseConnectionName())));
//Testing query
if(query->prepare(sqlstr))
{
for(auto iter=bindings.begin(); iter!=bindings.end(); ++iter)
{
query->bindValue(iter.key(), iter.value());
}
return query;
}
else
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::DatabaseError, QString("Invalid SQL statement for update a row. See the sqlerror attached."), query->lastError()));
return nullptr;
}
}
std::shared_ptr<QSqlQuery> StandardSqlProvider::generateDelete(Class *reflect)
{
//Objects to store the sql command
QString sqlstr;
QTextStream sql(&sqlstr);
//Begin the sql command
sql << "DELETE FROM ";
//Add the table name
if(!reflect->tags()["table"].isNull())
{
sql << reflect->tags()["table"].toString() << " WHERE ";
}
else
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::ConfigurationError, QString("The tag 'table' was not supplied for the class '%1'.").arg(reflect->tags()["name"].toString())));
return nullptr;
}//End add the table name
//Object to store the bindings
QMap<QString, QVariant> bindings;
//Add the autoid
if(!reflect->tags()["autoid"].isNull())
{
sql << reflect->tags()["autoid"].toString()
<< " = "
<< reflect->tags()["autoid"].toString().prepend(":")
<< " AND ";
bindings.insert(reflect->tags()["autoid"].toString().prepend(":"), reflect->tags()["id"]);
}
//Add the version check
if(!reflect->tags()["versioncolumn"].isNull())
{
sql << reflect->tags()["versioncolumn"].toString()
<< " = "
<< reflect->tags()["versioncolumn"].toString().prepend(":")
<< " AND ";
bindings.insert(reflect->tags()["versioncolumn"].toString().prepend(":"), reflect->tags()["version"]);
}
//QString autocolumn = reflect->tags()["autocolumn"].toString();
//Iterating over the keys
for(Property *prop: reflect->properties())
{
if(prop->tags()["key"].toBool()) // || (!autocolumn.isNull() && prop->tags()["name"].toString()==autocolumn))
{
if(prop->tags()["column"].isNull())
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::ConfigurationError, QString("The tag 'column' was not supplied for the property '%1' in the class '%2'.")
.arg(prop->tags()["name"].toString())
.arg(reflect->tags()["name"].toString())));
}
else
{
sql << prop->tags()["column"].toString()
<< " = "
<< prop->tags()["column"].toString().prepend(":")
<< " AND ";
QVariant v = prop->value();
bindings.insert(prop->tags()["column"].toString().prepend(":"), prop->value());
}
}
}//End iterating over the keys
sqlstr = sqlstr.left(sqlstr.size()-4);
//Create the query object
std::shared_ptr<QSqlQuery> query(new QSqlQuery(QSqlDatabase::database(databaseConnectionName())));
//Testing query
if(query->prepare(sqlstr))
{
for(auto iter=bindings.begin(); iter!=bindings.end(); ++iter)
{
query->bindValue(iter.key(), iter.value());
}
return query;
}
else
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::DatabaseError, QString("Invalid SQL statement for delete a row. See the sqlerror attached."), query->lastError()));
return nullptr;
}
}
std::shared_ptr<QSqlQuery> StandardSqlProvider::generateSelect(Class *reflect, const Where &where, const QList<int> &fieldsno, const QList<QPair<QString, OrderBy> > orderby, int offset, int limit)
{
//Objects to store the sql command
QString sqlstr;
QTextStream sql(&sqlstr);
//Begin the statement
sql << "SELECT ";
//Iterating the properties
for(int index: fieldsno)
{
Property *prop = reflect->properties()[index];
//Check if the property has the column tag
if(prop->tags()["column"].isNull())
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::ConfigurationError, QString("The tag 'column' was not supplied for the property '%1' in the class '%2'.")
.arg(prop->tags()["name"].toString())
.arg(reflect->tags()["name"].toString())));
return nullptr;
}
else
{
//Add the column in the select
sql << prop->tags()["column"].toString() << ", ";
}//End check if the property has the column tag
}
//Insert the autoid column
if(!reflect->tags()["autoid"].isNull())
{
sql << reflect->tags()["autoid"].toString() << ", ";
}
//Insert the version column
if(!reflect->tags()["versioncolumn"].isNull())
{
sql << reflect->tags()["versioncolumn"].toString() << ", ";
}
//Remove the last ", " from the command
sqlstr = sqlstr.left(sqlstr.size()-2);
//Insert the table name
sql << " FROM ";
if(reflect->tags()["table"].isNull())
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::ConfigurationError, QString("The tag 'table' was not supplied for the class '%1'.").arg(reflect->tags()["name"].toString())));
return nullptr;
}
else
{
sql << reflect->tags()["table"].toString() << " ";
}//End insert the table name
//Check if where is used
QMap<QString, QVariant> bindings; //The list of bindings used int the where clause
if(where.operation() != WhereOp::NoOperation)
{
//Init the where clause
QString wherestr = "WHERE ";
const Where *whereptr = &where;
int fieldDiff = 0; //Sufix inserted in the property name before adding it in the where clause
//Iterating over the where clauses joined
while(whereptr)
{
QString field; //Store the name of the field used in the comparison
//Check if the field is the autoid
if(whereptr->field()=="autoid")
{
field = reflect->tags()["autoid"].toString();
}
//Check if the field is one of the properties in the object
else
{
//Iterating over the properties to be selected
for(int index: fieldsno)
{
Property *prop = reflect->properties()[index];
if(prop->tags()["name"].toString()==whereptr->field())
{
field = prop->tags()["column"].toString();
break;
}
} //End iterating over the properties to be selected
}
//Check if the field name is valid
if(field.isNull())
{
//If the field is invalid ignore this clause and check the next
whereptr = whereptr->joined();
continue;
}
//Field is valid
else
{
//Check if is necessary to open a block of precedence
if(whereptr->precede()==WherePrecede::Begin)
wherestr += "(";
//Include the name of the field in the where clause
wherestr += field + " ";
}
//Include the sufix in the name of the property
field.append(QString("%1").arg(fieldDiff));
++fieldDiff;
//Prepare the field to be used as a placeholder
field.prepend(":");
//Char used to diff multiple arguments in the in and notin comparisons
char diff = 'a';
//Check the type of operation
switch(whereptr->operation())
{
case WhereOp::Equals:
wherestr += QString("= %1 ").arg(field);
bindings.insert(field, whereptr->arguments().first());
break;
case WhereOp::NotEquals:
wherestr += QString("<> %1 ").arg(field);
bindings.insert(field, whereptr->arguments().first());
break;
case WhereOp::GreaterThan:
wherestr += QString("> %1 ").arg(field);
bindings.insert(field, whereptr->arguments().first());
break;
case WhereOp::GreaterEquals:
wherestr += QString(">= %1 ").arg(field);;
bindings.insert(field, whereptr->arguments().first());
break;
case WhereOp::LessThan:
wherestr += QString("< %1 ").arg(field);
bindings.insert(field, whereptr->arguments().first());
break;
case WhereOp::LessEquals:
wherestr += QString("<= %1 ").arg(field);
bindings.insert(field, whereptr->arguments().first());
break;
case WhereOp::Contains:
wherestr += QString("LIKE '%%1%' ").arg(whereptr->arguments().first().toString());
break;
case WhereOp::EndsWith:
wherestr += QString("LIKE '%1%2' ").arg("%").arg(whereptr->arguments().first().toString());
break;
case WhereOp::StartsWith:
wherestr += QString("LIKE '%1%2' ").arg(whereptr->arguments().first().toString()).arg("%");
break;
case WhereOp::Like:
wherestr += QString("LIKE '%1'").arg(whereptr->arguments().first().toString());
break;
case WhereOp::In:
wherestr += QString("IN (");
for(QVariant value: whereptr->arguments())
{
wherestr += QString("%1, ").arg(field+diff);
bindings.insert(field+diff, value);
++diff;
}
wherestr = wherestr.left(wherestr.size()-2)+") ";
break;
case WhereOp::NotIn:
wherestr += QString("NOT IN (");
for(QVariant value: whereptr->arguments())
{
wherestr += QString("%1, ").arg(field+diff);
bindings.insert(field+diff, value);
++diff;
}
wherestr = wherestr.left(wherestr.size()-2)+") ";
break;
default:
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::OperationNotSupported, QString("This type of comparison is not supported by this sql provider.")));
return nullptr;
} //End check the type of operation
//Check if is necessary to close a block of precedence
if(whereptr->precede()==WherePrecede::End)
wherestr = wherestr.trimmed() + ") ";
//Check if this where is joined
switch(whereptr->join())
{
case WhereJoin::And:
wherestr += "AND ";
break;
case WhereJoin::Or:
wherestr += "OR ";
break;
case WhereJoin::NoJoin:
whereptr = nullptr;
continue;
} //Check if this where is joined
//Adjust the next where clause to analize
whereptr = whereptr->joined();
} //End iterating over the where clauses joined
//Include the where clause in the sql statement
sql << wherestr;
} //End check if where is used
//Check if order by is used
if(!orderby.isEmpty())
{
sql << " ORDER BY ";
for(QPair<QString,OrderBy> order: orderby)
{
for(Property *prop: reflect->properties())
{
if(prop->tags()["name"].toString() == order.first)
{
if(!prop->tags()["column"].isNull())
{
sql << prop->tags()["column"].toString() << " ";
if(order.second == OrderBy::Asc)
sql << "ASC, ";
else
sql << "DESC, ";
}
else
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::ConfigurationError, QString("The tag 'column' was not supplied for the property '%1' in the class '%2'.")
.arg(prop->tags()["name"].toString())
.arg(reflect->tags()["name"].toString())));
return nullptr;
}
break;
}
}
//Check if the orderby refers to the autoid
if(!reflect->tags()["autoid"].isNull() && order.first == "autoid")
{
sql << reflect->tags()["autoid"].toString() << " ";
if(order.second == OrderBy::Asc)
sql << "ASC, ";
else
sql << "DESC, ";
}//Check if the orderby refers to the autoid
}
//Remove the last ", " from the command
sqlstr = sqlstr.left(sqlstr.size()-2);
}//End check if order by is used
//Check if the offset and the limit are used
if(offset > -1 && limit > 0)
{
sql << " LIMIT " << limit << " OFFSET " << offset;
}//End check if the offset and the limit are used
//Create a new query object
std::shared_ptr<QSqlQuery> query(new QSqlQuery(QSqlDatabase::database(databaseConnectionName())));
//Check if the sql statement is valid
if(query->prepare(sqlstr))
{
//Bind the values registered in the where clause
for(auto iter=bindings.begin(); iter!=bindings.end(); ++iter)
{
query->bindValue(iter.key(), iter.value());
} //End bind the values registered in the where clause
//Return the query
return query;
}
//If the sql statement is invalid raise an error
else
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::DatabaseError, QString("Invalid SQL statement for select. See the sqlerror attached."), query->lastError()));
return nullptr;
}
}
std::shared_ptr<QSqlQuery> StandardSqlProvider::generateCount(Class *reflect, const Where &where)
{
//Objects to store the sql command
QString sqlstr;
QTextStream sql(&sqlstr);
//Begin the statement
sql << "SELECT COUNT(*) ";
//Insert the table name
sql << " FROM ";
if(reflect->tags()["table"].isNull())
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::ConfigurationError, QString("The tag 'table' was not supplied for the class '%1'.").arg(reflect->tags()["name"].toString())));
return nullptr;
}
else
{
sql << reflect->tags()["table"].toString() << " ";
}//End insert the table name
//Check if where is used
QMap<QString, QVariant> bindings; //The list of bindings used int the where clause
if(where.operation() != WhereOp::NoOperation)
{
//Init the where clause
QString wherestr = "WHERE ";
const Where *whereptr = &where;
int fieldDiff = 0; //Sufix inserted in the property name before adding it in the where clause
//Iterating over the where clauses joined
while(whereptr)
{
QString field; //Store the name of the field used in the comparison
//Check if the field is the autoid
if(whereptr->field()=="autoid")
{
field = reflect->tags()["autoid"].toString();
}
//Check if the field is one of the properties in the object
else
{
//Iterating over the properties to be selected
for(Property *prop: reflect->properties())
{
if(prop->tags()["name"].toString()==whereptr->field())
{
field = prop->tags()["column"].toString();
break;
}
} //End iterating over the properties to be selected
}
//Check if the field name is valid
if(field.isNull())
{
//If the field is invalid ignore this clause and check the next
whereptr = whereptr->joined();
continue;
}
//Field is valid
else
{
//Check if is necessary to open a block of precedence
if(whereptr->precede()==WherePrecede::Begin)
wherestr += "(";
//Include the name of the field in the where clause
wherestr += field + " ";
}
//Inserting the sufix in the name of the property
field.append(QString("%1").arg(fieldDiff++));
//Prepare the field to be used as a placeholder
field.prepend(":");
//Char used to diff multiple arguments
char diff = 'a';
//Check the type of operation
switch(whereptr->operation())
{
case WhereOp::Equals:
wherestr += QString("= %1 ").arg(field);
bindings.insert(field, whereptr->arguments().first());
break;
case WhereOp::NotEquals:
wherestr += QString("<> %1 ").arg(field);
bindings.insert(field, whereptr->arguments().first());
break;
case WhereOp::GreaterThan:
wherestr += QString("> %1 ").arg(field);
bindings.insert(field, whereptr->arguments().first());
break;
case WhereOp::GreaterEquals:
wherestr += QString(">= %1 ").arg(field);;
bindings.insert(field, whereptr->arguments().first());
break;
case WhereOp::LessThan:
wherestr += QString("< %1 ").arg(field);
bindings.insert(field, whereptr->arguments().first());
break;
case WhereOp::LessEquals:
wherestr += QString("<= %1 ").arg(field);
bindings.insert(field, whereptr->arguments().first());
break;
case WhereOp::Contains:
wherestr += QString("LIKE '%%1%' ").arg(whereptr->arguments().first().toString());
break;
case WhereOp::EndsWith:
wherestr += QString("LIKE '%1%2' ").arg("%").arg(whereptr->arguments().first().toString());
break;
case WhereOp::StartsWith:
wherestr += QString("LIKE '%1%2' ").arg(whereptr->arguments().first().toString()).arg("%");
break;
case WhereOp::Like:
wherestr += QString("LIKE '%1'").arg(whereptr->arguments().first().toString());
break;
case WhereOp::In:
wherestr += QString("IN (");
for(QVariant value: whereptr->arguments())
{
wherestr += QString("%1, ").arg(field+diff);
bindings.insert(field+diff, value);
++diff;
}
wherestr = wherestr.left(wherestr.size()-2)+") ";
break;
case WhereOp::NotIn:
wherestr += QString("NOT IN (");
for(QVariant value: whereptr->arguments())
{
wherestr += QString("%1, ").arg(field+diff);
bindings.insert(field+diff, value);
++diff;
}
wherestr = wherestr.left(wherestr.size()-2)+") ";
break;
default:
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::OperationNotSupported, QString("This type of comparison is not supported by this sql provider.")));
return nullptr;
} //End check the type of operation
//Check if is necessary to close a block of precedence
if(whereptr->precede()==WherePrecede::End)
wherestr = wherestr.trimmed() + ") ";
//Check if this where is joined
switch(whereptr->join())
{
case WhereJoin::And:
wherestr += "AND ";
break;
case WhereJoin::Or:
wherestr += "OR ";
break;
case WhereJoin::NoJoin:
whereptr = nullptr;
continue;
} //Check if this where is joined
//Adjust the next where clause to analize
whereptr = whereptr->joined();
} //End iterating over the where clauses joined
//Include the where clause in the sql statement
sql << wherestr;
} //End check if where is used
//Create a new query object
std::shared_ptr<QSqlQuery> query(new QSqlQuery(QSqlDatabase::database(databaseConnectionName())));
//Check if the sql statement is valid
if(query->prepare(sqlstr))
{
//Bind the values registered in the where clause
for(auto iter=bindings.begin(); iter!=bindings.end(); ++iter)
{
query->bindValue(iter.key(), iter.value());
} //End bind the values registered in the where clause
//Return the query
return query;
}
//If the sql statement is invalid raise an error
else
{
m_lastError = std::shared_ptr<OrmError>(new OrmError(ErrorType::DatabaseError, QString("Invalid SQL statement for count. See the sqlerror attached."), query->lastError()));
return nullptr;
}
}