1/****************************************************************************
2**
3** Copyright (C) 2017 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the examples of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:BSD$
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** BSD License Usage
18** Alternatively, you may use this file under the terms of the BSD license
19** as follows:
20**
21** "Redistribution and use in source and binary forms, with or without
22** modification, are permitted provided that the following conditions are
23** met:
24** * Redistributions of source code must retain the above copyright
25** notice, this list of conditions and the following disclaimer.
26** * Redistributions in binary form must reproduce the above copyright
27** notice, this list of conditions and the following disclaimer in
28** the documentation and/or other materials provided with the
29** distribution.
30** * Neither the name of The Qt Company Ltd nor the names of its
31** contributors may be used to endorse or promote products derived
32** from this software without specific prior written permission.
33**
34**
35** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46**
47** $QT_END_LICENSE$
48**
49****************************************************************************/
50
51#include "sqlconversationmodel.h"
52
53#include <QDateTime>
54#include <QDebug>
55#include <QSqlError>
56#include <QSqlRecord>
57#include <QSqlQuery>
58
59static const char *conversationsTableName = "Conversations";
60
61static void createTable()
62{
63 if (QSqlDatabase::database().tables().contains(str: conversationsTableName)) {
64 // The table already exists; we don't need to do anything.
65 return;
66 }
67
68 QSqlQuery query;
69 if (!query.exec(
70 query: "CREATE TABLE IF NOT EXISTS 'Conversations' ("
71 "'author' TEXT NOT NULL,"
72 "'recipient' TEXT NOT NULL,"
73 "'timestamp' TEXT NOT NULL,"
74 "'message' TEXT NOT NULL,"
75 "FOREIGN KEY('author') REFERENCES Contacts ( name ),"
76 "FOREIGN KEY('recipient') REFERENCES Contacts ( name )"
77 ")")) {
78 qFatal(msg: "Failed to query database: %s", qPrintable(query.lastError().text()));
79 }
80
81 query.exec(query: "INSERT INTO Conversations VALUES('Me', 'Ernest Hemingway', '2016-01-07T14:36:06', 'Hello!')");
82 query.exec(query: "INSERT INTO Conversations VALUES('Ernest Hemingway', 'Me', '2016-01-07T14:36:16', 'Good afternoon.')");
83 query.exec(query: "INSERT INTO Conversations VALUES('Me', 'Albert Einstein', '2016-01-01T11:24:53', 'Hi!')");
84 query.exec(query: "INSERT INTO Conversations VALUES('Albert Einstein', 'Me', '2016-01-07T14:36:16', 'Good morning.')");
85 query.exec(query: "INSERT INTO Conversations VALUES('Hans Gude', 'Me', '2015-11-20T06:30:02', 'God morgen. Har du fått mitt maleri?')");
86 query.exec(query: "INSERT INTO Conversations VALUES('Me', 'Hans Gude', '2015-11-20T08:21:03', 'God morgen, Hans. Ja, det er veldig fint. Tusen takk! "
87 "Hvor mange timer har du brukt på den?')");
88}
89
90SqlConversationModel::SqlConversationModel(QObject *parent) :
91 QSqlTableModel(parent)
92{
93 createTable();
94 setTable(conversationsTableName);
95 setSort(column: 2, order: Qt::DescendingOrder);
96 // Ensures that the model is sorted correctly after submitting a new row.
97 setEditStrategy(QSqlTableModel::OnManualSubmit);
98}
99
100QString SqlConversationModel::recipient() const
101{
102 return m_recipient;
103}
104
105void SqlConversationModel::setRecipient(const QString &recipient)
106{
107 if (recipient == m_recipient)
108 return;
109
110 m_recipient = recipient;
111
112 const QString filterString = QString::fromLatin1(
113 str: "(recipient = '%1' AND author = 'Me') OR (recipient = 'Me' AND author='%1')").arg(a: m_recipient);
114 setFilter(filterString);
115 select();
116
117 emit recipientChanged();
118}
119
120QVariant SqlConversationModel::data(const QModelIndex &index, int role) const
121{
122 if (role < Qt::UserRole)
123 return QSqlTableModel::data(idx: index, role);
124
125 const QSqlRecord sqlRecord = record(row: index.row());
126 return sqlRecord.value(i: role - Qt::UserRole);
127}
128
129QHash<int, QByteArray> SqlConversationModel::roleNames() const
130{
131 QHash<int, QByteArray> names;
132 names[Qt::UserRole] = "author";
133 names[Qt::UserRole + 1] = "recipient";
134 names[Qt::UserRole + 2] = "timestamp";
135 names[Qt::UserRole + 3] = "message";
136 return names;
137}
138
139void SqlConversationModel::sendMessage(const QString &recipient, const QString &message)
140{
141 const QString timestamp = QDateTime::currentDateTime().toString(format: Qt::ISODate);
142
143 QSqlRecord newRecord = record();
144 newRecord.setValue(name: "author", val: "Me");
145 newRecord.setValue(name: "recipient", val: recipient);
146 newRecord.setValue(name: "timestamp", val: timestamp);
147 newRecord.setValue(name: "message", val: message);
148 if (!insertRecord(row: rowCount(), record: newRecord)) {
149 qWarning() << "Failed to send message:" << lastError().text();
150 return;
151 }
152
153 submitAll();
154}
155

source code of qtquickcontrols2/examples/quickcontrols2/chattutorial/chapter4-models/sqlconversationmodel.cpp