forked from sqlitebrowser/sqlitebrowser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddRecordDialog.cpp
More file actions
334 lines (283 loc) · 11.6 KB
/
Copy pathAddRecordDialog.cpp
File metadata and controls
334 lines (283 loc) · 11.6 KB
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
#include "AddRecordDialog.h"
#include "ui_AddRecordDialog.h"
#include "sqlitedb.h"
#include "Settings.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
#include <QStyledItemDelegate>
#include <QWhatsThis>
#include <QLineEdit>
#include <QMenu>
class NullLineEdit: public QLineEdit {
private:
bool m_isNull;
public:
NullLineEdit(QWidget* parent=nullptr): QLineEdit(parent), m_isNull (true) {}
bool isNull() {return m_isNull;}
void setNull(bool value) {
if (value) {
clear();
setPlaceholderText(Settings::getValue("databrowser", "null_text").toString());
setModified(false);
} else
setPlaceholderText("");
m_isNull = value;
}
protected:
void contextMenuEvent(QContextMenuEvent *event)
{
QMenu* editContextMenu = createStandardContextMenu();
QAction* nullAction = new QAction(tr("Set to NULL"), editContextMenu);
connect(nullAction, &QAction::triggered, [&]() {
setNull(true);
});
nullAction->setShortcut(QKeySequence(tr("Alt+Del")));
editContextMenu->addSeparator();
editContextMenu->addAction(nullAction);
editContextMenu->exec(event->globalPos());
delete editContextMenu;
}
void keyPressEvent(QKeyEvent *evt) {
// Alt+Del sets field to NULL
if((evt->modifiers() & Qt::AltModifier) && (evt->key() == Qt::Key_Delete))
setNull(true);
else {
// Remove any possible NULL mark when user starts typing
setPlaceholderText("");
QLineEdit::keyPressEvent(evt);
}
}
};
// Styled Item Delegate for non-editable columns (all except Value)
class NoEditDelegate: public QStyledItemDelegate {
public:
NoEditDelegate(QObject* parent=nullptr): QStyledItemDelegate(parent) {}
virtual QWidget* createEditor(QWidget* /* parent */, const QStyleOptionViewItem& /* option */, const QModelIndex& /* index */) const {
return nullptr;
}
};
// Styled Item Delegate for editable columns (Value)
class EditDelegate: public QStyledItemDelegate {
public:
EditDelegate(QObject* parent=nullptr): QStyledItemDelegate(parent) {}
virtual QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem& /* option */, const QModelIndex& /* index */) const {
return new NullLineEdit(parent);
}
virtual void setEditorData(QWidget *editor, const QModelIndex &index) const {
NullLineEdit* lineEditor = dynamic_cast<NullLineEdit*>(editor);
// Set the editor in the null state (unless the user has actually written NULL)
if (index.model()->data(index, Qt::UserRole).isNull() &&
index.model()->data(index, Qt::DisplayRole) == Settings::getValue("databrowser", "null_text"))
lineEditor->setNull(true);
else {
QStyledItemDelegate::setEditorData(editor, index);
lineEditor->setNull(false);
}
}
virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const {
NullLineEdit* lineEditor = dynamic_cast<NullLineEdit*>(editor);
// Restore NULL text (unless the user has already modified the value)
if (lineEditor->isNull() && !lineEditor->isModified()) {
model->setData(index, Settings::getValue("databrowser", "null_text"), Qt::DisplayRole);
model->setData(index, QVariant(), Qt::UserRole);
} else {
// Get isModified flag before calling setModelData
bool modified = lineEditor->isModified();
QStyledItemDelegate::setModelData(editor, model, index);
// Copy the just edited data to the user role, so it can be later used in the SQL insert statement.
if (modified) {
lineEditor->setNull(false);
model->setData(index, model->data(index, Qt::EditRole), Qt::UserRole);
}
}
}
};
AddRecordDialog::AddRecordDialog(DBBrowserDB& db, const sqlb::ObjectIdentifier& tableName, QWidget* parent)
: QDialog(parent),
ui(new Ui::AddRecordDialog),
pdb(db),
curTable(tableName),
m_table(*(pdb.getObjectByName<sqlb::Table>(curTable)))
{
// Create UI
ui->setupUi(this);
connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)),this,SLOT(itemChanged(QTreeWidgetItem*,int)));
populateFields();
ui->sqlTextEdit->setReadOnly(true);
// Update UI
ui->treeWidget->resizeColumnToContents(kName);
ui->treeWidget->resizeColumnToContents(kType);
ui->treeWidget->setFrameShape(QFrame::Box);
}
AddRecordDialog::~AddRecordDialog()
{
delete ui;
}
void AddRecordDialog::keyPressEvent(QKeyEvent *evt)
{
if((evt->modifiers() & Qt::ControlModifier)
&& (evt->key() == Qt::Key_Enter || evt->key() == Qt::Key_Return))
{
accept();
return;
}
if(evt->key() == Qt::Key_Enter || evt->key() == Qt::Key_Return)
return;
QDialog::keyPressEvent(evt);
}
void AddRecordDialog::setDefaultsStyle(QTreeWidgetItem* item)
{
// Default values are displayed with the style configured for NULL values in the Data Browser.
QFont font;
font.setItalic(true);
item->setData(kValue, Qt::FontRole, font);
item->setData(kValue, Qt::BackgroundRole, QColor(Settings::getValue("databrowser", "null_bg_colour").toString()));
item->setData(kValue, Qt::ForegroundRole, QColor(Settings::getValue("databrowser", "null_fg_colour").toString()));
}
void AddRecordDialog::populateFields()
{
// disconnect the itemChanged signal or the SQL text will
// be updated while filling the treewidget.
disconnect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
this,SLOT(itemChanged(QTreeWidgetItem*,int)));
ui->treeWidget->clear();
// Allow all Edit Triggers, but they will only apply to the columns with
// editors (Value)
ui->treeWidget->setEditTriggers(QAbstractItemView::AllEditTriggers);
// Disallow edition of columns except Value
ui->treeWidget->setItemDelegateForColumn(kName, new NoEditDelegate(this));
ui->treeWidget->setItemDelegateForColumn(kType, new NoEditDelegate(this));
ui->treeWidget->setItemDelegateForColumn(kValue, new EditDelegate(this));
const auto& fields = m_table.fields;
const QStringList& pk = m_table.primaryKey();
for(const sqlb::Field& f : fields)
{
QTreeWidgetItem *tbitem = new QTreeWidgetItem(ui->treeWidget);
tbitem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable);
tbitem->setText(kName, f.name());
tbitem->setText(kType, f.type());
tbitem->setData(kType, Qt::UserRole, f.affinity());
// NOT NULL fields are indicated in bold.
if (f.notnull()) {
QFont font;
font.setBold(true);
tbitem->setData(kName, Qt::FontRole, font);
}
if (contains(pk, f.name()))
tbitem->setIcon(kName, QIcon(":/icons/field_key"));
else
tbitem->setIcon(kName, QIcon(":/icons/field"));
QString defaultValue = f.defaultValue();
QString toolTip;
if (f.autoIncrement())
toolTip.append(tr("Auto-increment\n"));
if (f.unique())
toolTip.append(tr("Unique constraint\n"));
if (!f.check().isEmpty())
toolTip.append(tr("Check constraint:\t %1\n").arg (f.check()));
auto fk = std::dynamic_pointer_cast<sqlb::ForeignKeyClause>(m_table.constraint({f.name()}, sqlb::Constraint::ForeignKeyConstraintType));
if(fk)
toolTip.append(tr("Foreign key:\t %1\n").arg(fk->toString()));
setDefaultsStyle(tbitem);
// Display Role is used for displaying the default values.
// Only when they are changed, the User Role is updated and then used in the INSERT query.
if (!defaultValue.isEmpty()) {
tbitem->setData(kValue, Qt::DisplayRole, f.defaultValue());
toolTip.append(tr("Default value:\t %1\n").arg (defaultValue));
} else
tbitem->setData(kValue, Qt::DisplayRole, Settings::getValue("databrowser", "null_text"));
if (!toolTip.isEmpty()) {
// Chop last end-of-line
toolTip.chop(1);
tbitem->setToolTip(kValue, toolTip);
tbitem->setToolTip(kType, toolTip);
}
}
updateSqlText();
// and reconnect
connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)),this,SLOT(itemChanged(QTreeWidgetItem*,int)));
}
void AddRecordDialog::accept()
{
if(!pdb.executeSQL(ui->sqlTextEdit->text()))
{
QMessageBox::warning(
this,
QApplication::applicationName(),
tr("Error adding record. Message from database engine:\n\n%1").arg(pdb.lastError()));
return;
}
QDialog::accept();
}
void AddRecordDialog::updateSqlText()
{
QString stmt = QString("INSERT INTO %1").arg(curTable.toString());
QStringList vals;
QStringList fields;
// If the User Role of the Value column is not null, the entered value is used
// in the INSERT statement. Otherwise, SQLite just uses the default value for the field.
for(int i = 0; i < ui->treeWidget->topLevelItemCount(); ++i)
{
QTreeWidgetItem *item = ui->treeWidget->topLevelItem(i);
// User role contains now values entered by the user, that we actually need to insert.
QVariant value = item->data(kValue, Qt::UserRole);
if (!value.isNull()) {
bool isNumeric;
fields << sqlb::escapeIdentifier(item->text(kName));
value.toDouble(&isNumeric);
// If it has a numeric format and has no text affinity, do not quote it.
if (isNumeric && item->data(kType, Qt::UserRole).toString() != "TEXT")
vals << value.toString();
else
vals << QString("'%1'").arg(value.toString().replace("'", "''"));
}
}
if(fields.empty())
{
stmt.append(" DEFAULT VALUES;");
} else {
stmt.append("\n(");
stmt.append(fields.join(", "));
stmt.append(")\nVALUES (");
stmt.append(vals.join(", "));
stmt.append(");");
}
ui->sqlTextEdit->setText(stmt);
}
void AddRecordDialog::itemChanged(QTreeWidgetItem *item, int column)
{
if (item->data(column, Qt::UserRole).isNull())
setDefaultsStyle(item);
else {
// Restore default fore/background for the value column,
// since the value has changed away from the default.
QFont font;
font.setItalic(false);
item->setData(column, Qt::FontRole, font);
item->setData(column, Qt::BackgroundRole, item->data(kName, Qt::BackgroundRole));
item->setData(column, Qt::ForegroundRole, item->data(kName, Qt::ForegroundRole));
}
updateSqlText();
}
void AddRecordDialog::help()
{
QWhatsThis::enterWhatsThisMode();
}
void AddRecordDialog::on_buttonBox_clicked(QAbstractButton* button)
{
if (button == ui->buttonBox->button(QDialogButtonBox::Cancel))
reject();
else if (button == ui->buttonBox->button(QDialogButtonBox::Save))
accept();
else if (button == ui->buttonBox->button(QDialogButtonBox::Help))
help();
else if (button == ui->buttonBox->button(QDialogButtonBox::RestoreDefaults)) {
if (QMessageBox::warning(this,
QApplication::applicationName(),
tr("Are you sure you want to restore all the entered values to their defaults?"),
QMessageBox::RestoreDefaults | QMessageBox::Cancel,
QMessageBox::Cancel) == QMessageBox::RestoreDefaults)
populateFields();
}
}