Beispiel #1
0
Column *TablePrivate::addColumn(const QString &name, const QString &sqlType, const QVariant &defaultValue)
{
    Q_Q(Table);
    if(q->columnNames().contains(name, Qt::CaseInsensitive)) {
        qWarning() << "TablePrivate::addColumn: Duplicate column name" << name;
        return columnsByName.value(name);
    }

    QSqlQuery query(database->sqlDatabase());

    QString queryString = QLatin1String("ALTER TABLE ")+this->name+QLatin1String(" ADD ")+name+
            QLatin1String(" ")+sqlType;
    if(!defaultValue.toString().isEmpty()) {
        queryString += QLatin1String(" DEFAULT ")+defaultValue.toString();
    }
    query.exec(queryString);
    checkSqlError(query);
    query.finish();

    q->clear();
    q->setTable(this->name);
    if(!q->select()) {
        qDebug() << q->lastError();
        return 0;
    }

    QSqlField columnField = q->record().field(name);

    Column *column = new Column(columnField, q);
    column->setIndex(columns.size());
    columns.append(column);
    columnsByName.insert(name, column);
    return column;
}
Beispiel #2
0
void TablePrivate::init()
{
    Q_Q(Table);

    q->setTable(name);
    q->setEditStrategy(QSqlTableModel::OnFieldChange);
    q->select();

    QSqlRecord columnNames = q->record();
    int columnCount = columnNames.count();
    columns.reserve(columnCount);
    for(int i = 0; i < columnCount; ++i) {
        Column *column = new Column(columnNames.field(i), q);
        column->setIndex(i);
        columns.append(column);
        columnsByName.insert(column->name(), column);
    }

    while(q->canFetchMore())
        q->fetchMore();

    QSqlQuery query = q->query();
    int rowCount = q->rowCount();
    int idIndex = q->record().indexOf(QLatin1String("id"));
    int id = 0;
    rows.reserve(rowCount);
    rowsById.reserve(rowCount);
    for(int i = 0; i < rowCount; ++i) {
        query.seek(i);
        id = query.value(idIndex).toInt();
        Row *row = new Row(i, id, q);
        rows.append(row);
        rowsById.insert(id, row);
    }
}