1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the QtSql module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 3 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL3 included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 3 requirements
23** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24**
25** GNU General Public License Usage
26** Alternatively, this file may be used under the terms of the GNU
27** General Public License version 2.0 or (at your option) the GNU General
28** Public license version 3 or any later version approved by the KDE Free
29** Qt Foundation. The licenses are as published by the Free Software
30** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31** included in the packaging of this file. Please review the following
32** information to ensure the GNU General Public License requirements will
33** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34** https://www.gnu.org/licenses/gpl-3.0.html.
35**
36** $QT_END_LICENSE$
37**
38****************************************************************************/
39
40#include "qsqlfield.h"
41#include "qatomic.h"
42#include "qdebug.h"
43
44QT_BEGIN_NAMESPACE
45
46class QSqlFieldPrivate
47{
48public:
49 QSqlFieldPrivate(const QString &name,
50 QVariant::Type type, const QString &tableName) :
51 ref(1), nm(name), table(tableName), def(QVariant()), type(QMetaType::Type(type)),
52 req(QSqlField::Unknown), len(-1), prec(-1), tp(-1),
53 ro(false), gen(true), autoval(false)
54 {}
55
56 QSqlFieldPrivate(const QSqlFieldPrivate &other)
57 : ref(1),
58 nm(other.nm),
59 table(other.table),
60 def(other.def),
61 type(other.type),
62 req(other.req),
63 len(other.len),
64 prec(other.prec),
65 tp(other.tp),
66 ro(other.ro),
67 gen(other.gen),
68 autoval(other.autoval)
69 {}
70
71 bool operator==(const QSqlFieldPrivate& other) const
72 {
73 return (nm == other.nm
74 && table == other.table
75 && def == other.def
76 && type == other.type
77 && req == other.req
78 && len == other.len
79 && prec == other.prec
80 && ro == other.ro
81 && gen == other.gen
82 && autoval == other.autoval);
83 }
84
85 QAtomicInt ref;
86 QString nm;
87 QString table;
88 QVariant def;
89 QMetaType::Type type;
90 QSqlField::RequiredStatus req;
91 int len;
92 int prec;
93 int tp;
94 bool ro: 1;
95 bool gen: 1;
96 bool autoval: 1;
97};
98
99
100/*!
101 \class QSqlField
102 \brief The QSqlField class manipulates the fields in SQL database tables
103 and views.
104
105 \ingroup database
106 \ingroup shared
107 \inmodule QtSql
108
109 QSqlField represents the characteristics of a single column in a
110 database table or view, such as the data type and column name. A
111 field also contains the value of the database column, which can be
112 viewed or changed.
113
114 Field data values are stored as QVariants. Using an incompatible
115 type is not permitted. For example:
116
117 \snippet sqldatabase/sqldatabase.cpp 2
118
119 However, the field will attempt to cast certain data types to the
120 field data type where possible:
121
122 \snippet sqldatabase/sqldatabase.cpp 3
123
124 QSqlField objects are rarely created explicitly in application
125 code. They are usually accessed indirectly through \l{QSqlRecord}s
126 that already contain a list of fields. For example:
127
128 \snippet sqldatabase/sqldatabase.cpp 4
129 \dots
130 \snippet sqldatabase/sqldatabase.cpp 5
131 \snippet sqldatabase/sqldatabase.cpp 6
132
133 A QSqlField object can provide some meta-data about the field, for
134 example, its name(), variant type(), length(), precision(),
135 defaultValue(), typeID(), and its requiredStatus(),
136 isGenerated() and isReadOnly(). The field's data can be
137 checked to see if it isNull(), and its value() retrieved. When
138 editing the data can be set with setValue() or set to NULL with
139 clear().
140
141 \sa QSqlRecord
142*/
143
144/*!
145 \enum QSqlField::RequiredStatus
146
147 Specifies whether the field is required or optional.
148
149 \value Required The field must be specified when inserting records.
150 \value Optional The fields doesn't have to be specified when inserting records.
151 \value Unknown The database driver couldn't determine whether the field is required or
152 optional.
153
154 \sa requiredStatus()
155*/
156
157/*!
158 Constructs an empty field called \a fieldName of variant type \a type.
159
160 \sa setRequiredStatus(), setLength(), setPrecision(), setDefaultValue(),
161 setGenerated(), setReadOnly()
162*/
163QSqlField::QSqlField(const QString &fieldName, QVariant::Type type)
164{
165 d = new QSqlFieldPrivate(fieldName, type, QString());
166 val = QVariant(type);
167}
168
169/*!
170 \overload
171 Constructs an empty field called \a fieldName of variant type \a
172 type in \a table.
173
174 \sa setRequiredStatus(), setLength(), setPrecision(), setDefaultValue(),
175 setGenerated(), setReadOnly()
176*/
177QSqlField::QSqlField(const QString &fieldName, QVariant::Type type,
178 const QString &table)
179{
180 d = new QSqlFieldPrivate(fieldName, type, table);
181 val = QVariant(type);
182}
183
184/*!
185 Constructs a copy of \a other.
186*/
187
188QSqlField::QSqlField(const QSqlField& other)
189{
190 d = other.d;
191 d->ref.ref();
192 val = other.val;
193}
194
195/*!
196 Sets the field equal to \a other.
197*/
198
199QSqlField& QSqlField::operator=(const QSqlField& other)
200{
201 qAtomicAssign(d, x: other.d);
202 val = other.val;
203 return *this;
204}
205
206
207/*! \fn bool QSqlField::operator!=(const QSqlField &other) const
208 Returns \c true if the field is unequal to \a other; otherwise returns
209 false.
210*/
211
212/*!
213 Returns \c true if the field is equal to \a other; otherwise returns
214 false.
215*/
216bool QSqlField::operator==(const QSqlField& other) const
217{
218 return ((d == other.d || *d == *other.d)
219 && val == other.val);
220}
221
222/*!
223 Destroys the object and frees any allocated resources.
224*/
225
226QSqlField::~QSqlField()
227{
228 if (!d->ref.deref())
229 delete d;
230}
231
232/*!
233 Sets the required status of this field to \a required.
234
235 \sa requiredStatus(), setType(), setLength(), setPrecision(),
236 setDefaultValue(), setGenerated(), setReadOnly()
237*/
238void QSqlField::setRequiredStatus(RequiredStatus required)
239{
240 detach();
241 d->req = required;
242}
243
244/*! \fn void QSqlField::setRequired(bool required)
245
246 Sets the required status of this field to \l Required if \a
247 required is true; otherwise sets it to \l Optional.
248
249 \sa setRequiredStatus(), requiredStatus()
250*/
251
252/*!
253 Sets the field's length to \a fieldLength. For strings this is the
254 maximum number of characters the string can hold; the meaning
255 varies for other types.
256
257 \sa length(), setType(), setRequiredStatus(), setPrecision(),
258 setDefaultValue(), setGenerated(), setReadOnly()
259*/
260void QSqlField::setLength(int fieldLength)
261{
262 detach();
263 d->len = fieldLength;
264}
265
266/*!
267 Sets the field's \a precision. This only affects numeric fields.
268
269 \sa precision(), setType(), setRequiredStatus(), setLength(),
270 setDefaultValue(), setGenerated(), setReadOnly()
271*/
272void QSqlField::setPrecision(int precision)
273{
274 detach();
275 d->prec = precision;
276}
277
278/*!
279 Sets the default value used for this field to \a value.
280
281 \sa defaultValue(), value(), setType(), setRequiredStatus(),
282 setLength(), setPrecision(), setGenerated(), setReadOnly()
283*/
284void QSqlField::setDefaultValue(const QVariant &value)
285{
286 detach();
287 d->def = value;
288}
289
290/*!
291 \internal
292*/
293void QSqlField::setSqlType(int type)
294{
295 detach();
296 d->tp = type;
297}
298
299/*!
300 Sets the generated state. If \a gen is false, no SQL will
301 be generated for this field; otherwise, Qt classes such as
302 QSqlQueryModel and QSqlTableModel will generate SQL for this
303 field.
304
305 \sa isGenerated(), setType(), setRequiredStatus(), setLength(),
306 setPrecision(), setDefaultValue(), setReadOnly()
307*/
308void QSqlField::setGenerated(bool gen)
309{
310 detach();
311 d->gen = gen;
312}
313
314
315/*!
316 Sets the value of the field to \a value. If the field is read-only
317 (isReadOnly() returns \c true), nothing happens.
318
319 If the data type of \a value differs from the field's current
320 data type, an attempt is made to cast it to the proper type. This
321 preserves the data type of the field in the case of assignment,
322 e.g. a QString to an integer data type.
323
324 To set the value to NULL, use clear().
325
326 \sa value(), isReadOnly(), defaultValue()
327*/
328
329void QSqlField::setValue(const QVariant& value)
330{
331 if (isReadOnly())
332 return;
333 val = value;
334}
335
336/*!
337 Clears the value of the field and sets it to NULL.
338 If the field is read-only, nothing happens.
339
340 \sa setValue(), isReadOnly(), requiredStatus()
341*/
342
343void QSqlField::clear()
344{
345 if (isReadOnly())
346 return;
347 val = QVariant(type());
348}
349
350/*!
351 Sets the name of the field to \a name.
352
353 \sa name()
354*/
355
356void QSqlField::setName(const QString& name)
357{
358 detach();
359 d->nm = name;
360}
361
362/*!
363 Sets the read only flag of the field's value to \a readOnly. A
364 read-only field cannot have its value set with setValue() and
365 cannot be cleared to NULL with clear().
366*/
367void QSqlField::setReadOnly(bool readOnly)
368{
369 detach();
370 d->ro = readOnly;
371}
372
373/*!
374 \fn QVariant QSqlField::value() const
375
376 Returns the value of the field as a QVariant.
377
378 Use isNull() to check if the field's value is NULL.
379*/
380
381/*!
382 Returns the name of the field.
383
384 \sa setName()
385*/
386QString QSqlField::name() const
387{
388 return d->nm;
389}
390
391/*!
392 Returns the field's type as stored in the database.
393 Note that the actual value might have a different type,
394 Numerical values that are too large to store in a long
395 int or double are usually stored as strings to prevent
396 precision loss.
397
398 \sa setType()
399*/
400QVariant::Type QSqlField::type() const
401{
402 return QVariant::Type(d->type);
403}
404
405/*!
406 Set's the field's variant type to \a type.
407
408 \sa type(), setRequiredStatus(), setLength(), setPrecision(),
409 setDefaultValue(), setGenerated(), setReadOnly()
410*/
411void QSqlField::setType(QVariant::Type type)
412{
413 detach();
414 d->type = QMetaType::Type(type);
415 if (!val.isValid())
416 val = QVariant(type);
417}
418
419/*!
420 Returns \c true if the field's value is read-only; otherwise returns
421 false.
422
423 \sa setReadOnly(), type(), requiredStatus(), length(), precision(),
424 defaultValue(), isGenerated()
425*/
426bool QSqlField::isReadOnly() const
427{ return d->ro; }
428
429/*!
430 Returns \c true if the field's value is NULL; otherwise returns
431 false.
432
433 \sa value()
434*/
435bool QSqlField::isNull() const
436{ return val.isNull(); }
437
438/*! \internal
439*/
440void QSqlField::detach()
441{
442 qAtomicDetach(d);
443}
444
445/*!
446 Returns \c true if this is a required field; otherwise returns \c false.
447 An \c INSERT will fail if a required field does not have a value.
448
449 \sa setRequiredStatus(), type(), length(), precision(), defaultValue(),
450 isGenerated()
451*/
452QSqlField::RequiredStatus QSqlField::requiredStatus() const
453{
454 return d->req;
455}
456
457/*!
458 Returns the field's length.
459
460 If the returned value is negative, it means that the information
461 is not available from the database.
462
463 \sa setLength(), type(), requiredStatus(), precision(), defaultValue(),
464 isGenerated()
465*/
466int QSqlField::length() const
467{
468 return d->len;
469}
470
471/*!
472 Returns the field's precision; this is only meaningful for numeric
473 types.
474
475 If the returned value is negative, it means that the information
476 is not available from the database.
477
478 \sa setPrecision(), type(), requiredStatus(), length(), defaultValue(),
479 isGenerated()
480*/
481int QSqlField::precision() const
482{
483 return d->prec;
484}
485
486/*!
487 Returns the field's default value (which may be NULL).
488
489 \sa setDefaultValue(), type(), requiredStatus(), length(), precision(),
490 isGenerated()
491*/
492QVariant QSqlField::defaultValue() const
493{
494 return d->def;
495}
496
497/*!
498 \internal
499
500 Returns the type ID for the field.
501
502 If the returned value is negative, it means that the information
503 is not available from the database.
504*/
505int QSqlField::typeID() const
506{
507 return d->tp;
508}
509
510/*!
511 Returns \c true if the field is generated; otherwise returns
512 false.
513
514 \sa setGenerated(), type(), requiredStatus(), length(), precision(),
515 defaultValue()
516*/
517bool QSqlField::isGenerated() const
518{
519 return d->gen;
520}
521
522/*!
523 Returns \c true if the field's variant type is valid; otherwise
524 returns \c false.
525*/
526bool QSqlField::isValid() const
527{
528 return d->type != QMetaType::UnknownType;
529}
530
531#ifndef QT_NO_DEBUG_STREAM
532QDebug operator<<(QDebug dbg, const QSqlField &f)
533{
534 QDebugStateSaver saver(dbg);
535 dbg.nospace();
536 dbg << "QSqlField(" << f.name() << ", " << QMetaType::typeName(type: f.type());
537 dbg << ", tableName: " << (f.tableName().isEmpty() ? QStringLiteral("(not specified)") : f.tableName());
538 if (f.length() >= 0)
539 dbg << ", length: " << f.length();
540 if (f.precision() >= 0)
541 dbg << ", precision: " << f.precision();
542 if (f.requiredStatus() != QSqlField::Unknown)
543 dbg << ", required: "
544 << (f.requiredStatus() == QSqlField::Required ? "yes" : "no");
545 dbg << ", generated: " << (f.isGenerated() ? "yes" : "no");
546 if (f.typeID() >= 0)
547 dbg << ", typeID: " << f.typeID();
548 if (!f.defaultValue().isNull())
549 dbg << ", defaultValue: \"" << f.defaultValue() << '\"';
550 dbg << ", autoValue: " << f.isAutoValue()
551 << ", readOnly: " << f.isReadOnly() << ')';
552 return dbg;
553}
554#endif
555
556/*!
557 Returns \c true if the value is auto-generated by the database,
558 for example auto-increment primary key values.
559
560 \note When using the ODBC driver, due to limitations in the ODBC API,
561 the \c isAutoValue() field is only populated in a QSqlField resulting from a
562 QSqlRecord obtained by executing a \c SELECT query. It is \c false in a QSqlField
563 resulting from a QSqlRecord returned from QSqlDatabase::record() or
564 QSqlDatabase::primaryIndex().
565
566 \sa setAutoValue()
567*/
568bool QSqlField::isAutoValue() const
569{
570 return d->autoval;
571}
572
573/*!
574 Marks the field as an auto-generated value if \a autoVal
575 is true.
576
577 \sa isAutoValue()
578 */
579void QSqlField::setAutoValue(bool autoVal)
580{
581 detach();
582 d->autoval = autoVal;
583}
584
585/*!
586 Sets the tableName of the field to \a table.
587
588 \sa tableName()
589*/
590void QSqlField::setTableName(const QString &table)
591{
592 detach();
593 d->table = table;
594}
595
596/*!
597 Returns the tableName of the field.
598
599 \note When using the QPSQL driver, due to limitations in the libpq library,
600 the \c tableName() field is not populated in a QSqlField resulting
601 from a QSqlRecord obtained by QSqlQuery::record() of a forward-only query.
602
603 \sa setTableName()
604*/
605QString QSqlField::tableName() const
606{
607 return d->table;
608}
609
610QT_END_NAMESPACE
611

source code of qtbase/src/sql/kernel/qsqlfield.cpp