Пример #1
0
            /*!
             * saves this instance
             * @param insert_only set to true to never perform an update if the record exists
             * @return true if the save was successful
             */
            bool record::save() {
                bool rval = false;
                bool exists = record::exists();
                auto pk = schema()->primary_key();
                auto cols_to_save = available_columns(exists, pk);

                if (exists) {
                    update_query query(schema(), cols_to_save);

                    query.bind(get(cols_to_save));

                    query.where(op::equals(pk, get(pk)));

                    rval = query.execute();
                } else {
                    insert_query query(schema(), cols_to_save);

                    query.bind(get(cols_to_save));

                    rval = query.execute();

                    if (rval) {
                        // set the new id
                        set(pk, query.last_insert_id());
                    }
                }

                return rval;
            }
void
KexiRelationsTableFieldList::slotDropped(QDropEvent *ev)
{
    Q3ListViewItem *recever = itemAt(ev->pos() - QPoint(0, contentsY()));
    if (!recever || !KexiFieldDrag::canDecodeSingle(ev)) {
        ev->ignore();
        return;
    }
    QString sourceMimeType;
    QString srcTable;
    QString srcField;
    if (!KexiFieldDrag::decodeSingle(ev, sourceMimeType, srcTable, srcField))
        return;
    if (sourceMimeType != "kexi/table" && sourceMimeType == "kexi/query")
        return;
//  kDebug() << "KexiRelationsTableFieldList::slotDropped() srcfield: " << srcField;

    QString rcvField = recever->text(0);

    SourceConnection s;
    s.masterTable = srcTable;
    s.detailsTable = schema()->name();
    s.masterField = srcField;
    s.detailsField = rcvField;

    m_scrollArea->addConnection(s);

    kDebug() << "KexiRelationsTableFieldList::slotDropped() " << srcTable << ":" << srcField << " "
    << schema()->name() << ":" << rcvField;
    ev->accept();
}
Пример #3
0
void KexiFieldListView::slotDoubleClicked(QListViewItem* item)
{
	if (schema() && item) {
	//! @todo what about query fields/aliases? it.current()->text(0) can be not enough
		emit fieldDoubleClicked(schema()->table() ? "kexi/table" : "kexi/query",
			schema()->name(), item->text(0));
	}
}
Пример #4
0
/** read_back_view_ddl()
 
 Load back VIEW code from the database for everything we created, so that we know how it was normalized.

 This will go through the whole catalog and read the SQL definition for each view. This is needed because
 the server stores the view definition in a canonical form, which is quite different from what the user
 types (not only formatting is stripped, but object names are expanded and expressions are rewritten).
 That makes it impossible for us to synchronize by comparing the definition in the model with the
 definition in the server. So we need to store the server version of the view right after we create it in
 there and a snapshot of the view that was used to create that view. 
 
 During synchronization, we can detect changes in the model by comparing the model version of the snapshot with 
 the model SQL definition and detect server changes by comparing the server version of the definition with 
 the snapshot for the server. We need to do that separately for every target server that synchronization is 
 used with (using the db.SyncProfile object).
 */
void Db_plugin::read_back_view_ddl()
{
  Db_objects_setup *setup= db_objects_setup_by_type(dbotView);
  setup->reset();

  _grtm->get_grt()->send_info(std::string("Fetching back view definitions in final form."));

  _grtm->get_grt()->send_progress(0.0, std::string("Fetching back view definitions in final form."));

  sql::ConnectionWrapper dbc_conn= _db_conn->get_dbc_connection();
  sql::DatabaseMetaData *dbc_meta(dbc_conn->getMetaData());
  std::list<Db_obj_handle> db_objects;

  float total_views = 0;

  for (size_t sc = model_catalog()->schemata().count(), s = 0; s < sc; ++s)
  {
    db_SchemaRef schema(model_catalog()->schemata()[s]);
    total_views += schema->views().count();
  }
  if (total_views == 0)
  {
    _grtm->get_grt()->send_progress(1.0, "Finished.");
    _grtm->get_grt()->send_info("Nothing to fetch");
    return;
  }

  int current_view = 0;
  for (size_t sc = model_catalog()->schemata().count(), s = 0; s < sc; ++s)
  {
    db_SchemaRef schema(model_catalog()->schemata()[s]);
    for (size_t vc = schema->views().count(), v = 0; v < vc; ++v)
    {
      db_ViewRef view(schema->views()[v]);

      _grtm->get_grt()->send_progress((current_view / total_views),
                                      std::string("Fetch back database view code for ").append(schema->name()).append(".").append(view->name()));
      std::auto_ptr<sql::ResultSet> rset(dbc_meta->getSchemaObjects("", *schema->name(), "view", true, *view->name()));

      // take a snapshot of the server version of the SQL
      if (rset->next())
        view->oldServerSqlDefinition(grt::StringRef(rset->getString("ddl")));
      else
        _grtm->get_grt()->send_info(base::strfmt("Could not get definition for %s.%s from server", schema->name().c_str(), view->name().c_str()));

      // take a snapshot of the model version of the SQL
      view->oldModelSqlDefinition(view->sqlDefinition());

      current_view++;
    }
  }
  _grtm->get_grt()->send_progress(1.0, "Finished.");
  _grtm->get_grt()->send_info(base::strfmt("%i views were read back.", current_view));
}
Пример #5
0
            /*!
             * deletes this record from the database for the value in the id column
             */
            bool record::remove() const {
                auto pk = schema()->primary_key();

                if (!has(pk)) {
                    return false;
                }
                delete_query query(schema());

                query.where(op::equals(pk, get(pk)));

                return query.execute();
            }
Пример #6
0
            /*!
             *  @return true if a record with the id column value exists
             */
            bool record::exists() const {
                auto pk = schema()->primary_key();

                if (!has(pk)) {
                    return false;
                }

                select_query query(schema());

                query.where(op::equals(pk, get(pk)));

                return query.count() > 0;
            }
Пример #7
0
std::unique_ptr<std::vector<char>> Format::pack(
        Data::PooledStack dataStack,
        const ChunkType chunkType) const
{
    std::unique_ptr<std::vector<char>> data;
    const std::size_t numPoints(dataStack.size());
    const std::size_t pointSize(schema().pointSize());

    if (m_compress)
    {
        Compressor compressor(m_metadata.schema(), dataStack.size());
        for (const char* pos : dataStack) compressor.push(pos, pointSize);
        data = compressor.data();
    }
    else
    {
        data = makeUnique<std::vector<char>>();
        data->reserve(numPoints * pointSize);
        for (const char* pos : dataStack)
        {
            data->insert(data->end(), pos, pos + pointSize);
        }
    }

    assert(data);
    dataStack.reset();

    Packer packer(m_tailFields, *data, numPoints, chunkType);
    append(*data, packer.buildTail());

    return data;
}
    json::QuickBuilder PropertyRestrictions<Key, KeyValue, Container>::GetSchema()
    {
        json::QuickBuilder schema( GetSchemaBase() );
        auto tn = JsonConfigurable::_typename_label();
        auto ts = JsonConfigurable::_typeschema_label();

        // this is kind of hacky, but there only two types right now.
        if( std::string( typeid(Key).name() ) == "class Kernel::IPKey" )
        {
            schema[ tn ] = json::String( "idmType:PropertyRestrictions" );
        }
        else
        {
            schema[ tn ] = json::String( "idmType:NodePropertyRestrictions" );
        }
        schema[ ts ] = json::Array();
        schema[ ts ][0] = json::Object();
        schema[ ts ][0]["<key>"] = json::Object();
        schema[ ts ][0]["<key>"][ "type" ] = json::String( "Constrained String" );
        schema[ ts ][0]["<key>"][ "constraints" ] = json::String( Key::GetConstrainedStringConstraintKey() );
        schema[ ts ][0]["<key>"][ "description" ] = json::String( Key::GetConstrainedStringDescriptionKey() );
        schema[ ts ][0]["<value>"] = json::Object();
        schema[ ts ][0]["<value>"][ "type" ] = json::String( "String" );
        schema[ ts ][0]["<value>"][ "constraints" ] = json::String( Key::GetConstrainedStringConstraintValue()  );
        schema[ ts ][0]["<value>"][ "description" ] = json::String( Key::GetConstrainedStringDescriptionValue() );
        return schema;
    }
Пример #9
0
// Test multithreaded functionality
TEST_F(SkipListMapTest, MultithreadedTest) {

  std::vector<catalog::Column> columns;

  catalog::Column column1(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER), "A", true);
  columns.push_back(column1);
  catalog::Schema *schema(new catalog::Schema(columns));
  std::vector<storage::Tuple*> tuples;

  // Parallel Test
  size_t num_threads = 4;
  size_t scale_factor = 100;

  std::vector<std::thread> thread_group;

  LaunchParallelTest(num_threads, InsertTest, scale_factor, schema);

  size_t num_entries = 0;
  for (auto iterator = test_skip_list_map.begin();
      iterator != test_skip_list_map.end();
      ++iterator) {
    num_entries++;
  }

  LOG_INFO("Num Entries : %lu", num_entries);

  EXPECT_EQ(num_entries, num_threads * scale_factor * base_scale);

}
QGalleryAbstractResponse *QDocumentGalleryPrivate::createFilterResponse(
        QGalleryQueryRequest *request)
{
    QGalleryTrackerSchema schema(request->rootType());

    QGalleryTrackerResultSetArguments arguments;

    int error = schema.prepareQueryResponse(
            &arguments,
            this,
            request->scope(),
            request->rootItem().toString(),
            request->filter(),
            request->propertyNames(),
            request->sortPropertyNames());

    if (error != QDocumentGallery::NoError) {
        return new QGalleryAbstractResponse(error);
    } else {
        return createItemListResponse(
                &arguments,
                request->offset(),
                request->limit(),
                schema.isItemType(),
                request->autoUpdate());
    }
}
Пример #11
0
TEST_F(ValueCopyTests, VarcharTest) {
  std::vector<catalog::Column> columns;

  catalog::Column column1(VALUE_TYPE_VARCHAR, 25, "D", false);

  columns.push_back(column1);
  columns.push_back(column1);

  catalog::Schema *schema(new catalog::Schema(columns));

  storage::Tuple *tuple(new storage::Tuple(schema, true));

  auto pool = TestingHarness::GetInstance().GetTestingPool();

  Value val = ValueFactory::GetStringValue("hello hello world", pool);

  Value val2 = ValueFactory::GetStringValue("hello hello world", nullptr);

  tuple->SetValue(0, val2, nullptr);
  tuple->SetValue(1, val2, nullptr);

  Value val3 = tuple->GetValue(0);

  LOG_INFO("%s", val3.GetInfo().c_str());

  delete tuple;
  delete schema;
}
Пример #12
0
RowCollection<Group,Hash>::RowCollection(boost::shared_ptr<Query> const& query, const string& name, const Attributes& attributes, size_t chunkSize)
: _query(query), _attributes(attributes), _chunkSize(chunkSize), _sizeBuffered(0), _mode(RowCollectionModeAppend)
{
    assert(!attributes.empty());
    assert(chunkSize >= 2);

    // Use (CONFIG_MEM_ARRAY_THRESHOLD / 10) as the #bytes the unflushed items may have.
    _maxSizeBuffered = Config::getInstance()->getOption<size_t>(CONFIG_MEM_ARRAY_THRESHOLD) * MiB / 10;

    // Push the empty tag
    Attributes attributesWithET(attributes);
    attributesWithET.push_back(AttributeDesc(attributes.size(), DEFAULT_EMPTY_TAG_ATTRIBUTE_NAME,
           TID_BOOL, AttributeDesc::IS_EMPTY_INDICATOR, 0));

    // get the schema
    Dimensions dims(2);
    dims[0] = DimensionDesc("Row", 0, MAX_COORDINATE, 1, 0);
    dims[1] = DimensionDesc("Column", 0, MAX_COORDINATE, _chunkSize, 0);
    ArrayDesc schema(name, attributesWithET, dims);

    // create a MemArray
    _theArray = make_shared<MemArray>(schema,query);

    // get the array iterators
    _arrayIterators.reserve(attributes.size());
    for (size_t t=0; t<attributes.size(); ++t) {
        _arrayIterators.push_back(_theArray->getIterator(t));
    }
}
Пример #13
0
void Parser::init(ParserContext *context)
{
#if 0
  if (!parseFile(context, ":/schema/XMLSchema.xsd")) {
      qWarning("Error parsing builtin file XMLSchema.xsd");
  }
#else
  Q_UNUSED(context);
#endif

    // From the XML schema XSD
    {
        Element schema(XMLSchemaURI);
        schema.setName(QLatin1String("schema"));
        schema.setType(QName(XMLSchemaURI, QLatin1String("anyType")));
        d->mElements.append(schema);
    }

    // Define xml:lang, since we don't parse xml.xsd
    {
        Attribute langAttr(NSManager::xmlNamespace());
        langAttr.setName(QLatin1String("lang"));
        langAttr.setType(QName(XMLSchemaURI, QLatin1String("string")));
        d->mAttributes.append(langAttr);
    }


  // From http://schemas.xmlsoap.org/wsdl/soap/encoding
  {
      ComplexType array(soapEncNs);
      array.setArrayType(QName(XMLSchemaURI, QString::fromLatin1("any")));
      array.setName(QLatin1String("Array"));
      d->mComplexTypes.append(array);
  }

  // From http://schemas.xmlsoap.org/soap/encoding/, so that <attribute ref="soap-enc:arrayType" arrayType="kdab:EmployeeAchievement[]"/>
  // can be resolved.
  {
      Attribute arrayTypeAttr(soapEncNs);
      arrayTypeAttr.setName(QLatin1String("arrayType"));
      arrayTypeAttr.setType(QName(XMLSchemaURI, QLatin1String("string")));
      d->mAttributes.append(arrayTypeAttr);
  }

  // Same thing, but for SOAP-1.2: from http://www.w3.org/2003/05/soap-encoding
  {
      ComplexType array(soap12EncNs);
      array.setArrayType(QName(XMLSchemaURI, QString::fromLatin1("any")));
      array.setName(QLatin1String("Array"));
      d->mComplexTypes.append(array);
  }
  {
      Attribute arrayTypeAttr(soap12EncNs);
      arrayTypeAttr.setName(QLatin1String("arrayType"));
      arrayTypeAttr.setType(QName(XMLSchemaURI, QLatin1String("string")));
      d->mAttributes.append(arrayTypeAttr);
  }

}
Пример #14
0
void InfoKernel::dump(MetadataNode& root)
{
    if (m_showSchema)
        root.add(m_manager->pointTable().toMetadata().clone("schema"));

    if (m_PointCloudSchemaOutput.size() > 0)
    {
#ifdef PDAL_HAVE_LIBXML2
        XMLSchema schema(m_manager->pointTable().layout());

        std::ostream *out = FileUtils::createFile(m_PointCloudSchemaOutput);
        std::string xml(schema.xml());
        out->write(xml.c_str(), xml.size());
        FileUtils::closeFile(out);
#else
        std::cerr << "libxml2 support not enabled, no schema is produced" <<
            std::endl;
#endif

    }
    if (m_showStats)
        root.add(m_statsStage->getMetadata().clone("stats"));

    if (m_pipelineFile.size() > 0)
        PipelineWriter::writePipeline(m_manager->getStage(), m_pipelineFile);

    if (m_pointIndexes.size())
    {
        PointViewSet viewSet = m_manager->views();
        assert(viewSet.size() == 1);
        root.add(dumpPoints(*viewSet.begin()).clone("points"));
    }

    if (m_queryPoint.size())
    {
        PointViewSet viewSet = m_manager->views();
        assert(viewSet.size() == 1);
        root.add(dumpQuery(*viewSet.begin()));
    }

    if (m_showMetadata)
    {
        // If we have a reader cached, this means we
        // weren't reading a pipeline file directly. In that
        // case, use the metadata from the reader (old behavior).
        // Otherwise, return the full metadata of the entire pipeline
        if (m_reader)
            root.add(m_reader->getMetadata().clone("metadata"));
        else
            root.add(m_manager->getMetadata().clone("metadata"));
    }

    if (m_boundary)
    {
        PointViewSet viewSet = m_manager->views();
        assert(viewSet.size() == 1);
        root.add(m_hexbinStage->getMetadata().clone("boundary"));
    }
}
Пример #15
0
int PipelineKernel::execute()
{
    if (!Utils::fileExists(m_inputFile))
        throw pdal_error("file not found: " + m_inputFile);
    if (m_progressFile.size())
    {
        m_progressFd = Utils::openProgress(m_progressFile);
        m_manager.setProgressFd(m_progressFd);
    }

    m_manager.readPipeline(m_inputFile);

    if (m_validate)
    {
        // Validate the options of the pipeline we were
        // given, and once we succeed, we're done
        m_manager.prepare();
        Utils::closeProgress(m_progressFd);
        return 0;
    }

    if (m_stream)
    {
        FixedPointTable table(10000);
        m_manager.executeStream(table);
    }
    else
        m_manager.execute();

    if (m_metadataFile.size())
    {
        std::ostream *out = Utils::createFile(m_metadataFile, false);
        if (!out)
            throw pdal_error("Can't open file '" + m_metadataFile +
                "' for metadata output.");
        Utils::toJSON(m_manager.getMetadata(), *out);
        Utils::closeFile(out);
    }
    if (m_pipelineFile.size())
        PipelineWriter::writePipeline(m_manager.getStage(), m_pipelineFile);

    if (m_PointCloudSchemaOutput.size() > 0)
    {
#ifdef PDAL_HAVE_LIBXML2
        XMLSchema schema(m_manager.pointTable().layout());

        std::ostream *out = Utils::createFile(m_PointCloudSchemaOutput);
        std::string xml(schema.xml());
        out->write(xml.c_str(), xml.size());
        Utils::closeFile(out);
#else
        std::cerr << "libxml2 support not available, no schema is produced" <<
            std::endl;
#endif

    }
    Utils::closeProgress(m_progressFd);
    return 0;
}
Пример #16
0
int UrlObject::port() const {
  int port = static_cast<int>(_handle.port);
  if (port != 0) {
    return port;
  }

  return (schema() == "http" ? 80 : 443);
}
Пример #17
0
TEST_F(ExpressionTests, SimpleCaseCopyTest) {

  // CASE WHEN i=1 THEN 2 ELSE 3 END
  // EXPRESSION
  auto tup_val_exp = new expression::TupleValueExpression(type::TypeId::INTEGER,
      0, 0);
  auto const_val_exp_1 = new expression::ConstantValueExpression(
      type::ValueFactory::GetIntegerValue(1));
  auto const_val_exp_2 = new expression::ConstantValueExpression(
      type::ValueFactory::GetIntegerValue(2));
  auto const_val_exp_3 = new expression::ConstantValueExpression(
      type::ValueFactory::GetIntegerValue(3));

  auto *when_cond =
      new expression::ComparisonExpression(ExpressionType::COMPARE_EQUAL,
          tup_val_exp, const_val_exp_1);

  std::vector<expression::CaseExpression::WhenClause> clauses;
  clauses.push_back(expression::CaseExpression::WhenClause(
      expression::CaseExpression::AbsExprPtr(when_cond),
      expression::CaseExpression::AbsExprPtr(const_val_exp_2)));

  std::unique_ptr<expression::CaseExpression> o_case_expression(
      new expression::CaseExpression(type::TypeId::INTEGER, clauses,
          expression::CaseExpression::AbsExprPtr(const_val_exp_3)));

  std::unique_ptr<expression::CaseExpression> case_expression(
      dynamic_cast<expression::CaseExpression *>(o_case_expression->Copy()));

  // TUPLE
  std::vector<catalog::Column> columns;

  catalog::Column column1(type::TypeId::INTEGER,
                          type::Type::GetTypeSize(type::TypeId::INTEGER),
                          "i1", true);
  catalog::Column column2(type::TypeId::INTEGER,
                          type::Type::GetTypeSize(type::TypeId::INTEGER),
                          "i2", true);
  columns.push_back(column1);
  columns.push_back(column2);
  std::unique_ptr<catalog::Schema> schema(new catalog::Schema(columns));

  std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(schema.get(), true));

  // Test with A = 1, should get 2
  tuple->SetValue(0, type::ValueFactory::GetIntegerValue(1), nullptr);
  tuple->SetValue(1, type::ValueFactory::GetIntegerValue(1), nullptr);
  type::Value result = case_expression->Evaluate(tuple.get(), nullptr, nullptr);
  type::Value expected = type::ValueFactory::GetIntegerValue(2);
  EXPECT_EQ(type::CmpBool::CMP_TRUE, expected.CompareEquals(result));

  // Test with A = 2, should get 3
  tuple->SetValue(0, type::ValueFactory::GetIntegerValue(2), nullptr);
  tuple->SetValue(1, type::ValueFactory::GetIntegerValue(1), nullptr);
  result = case_expression->Evaluate(tuple.get(), nullptr, nullptr);
  expected = type::ValueFactory::GetIntegerValue(3);
  EXPECT_EQ(type::CmpBool::CMP_TRUE, expected.CompareEquals(result));
}
Пример #18
0
 /*!
  * @param exists true if the record exists
  * @param pk the primary key column name
  * @return a vector columns that are set on this record
  */
 std::vector<std::string> record::available_columns(bool exists, const std::string &pk) const {
     std::vector<std::string> values;
     auto columns = schema()->column_names();
     values.resize(columns.size());
     auto it = std::copy_if(columns.begin(), columns.end(), values.begin(),
                            [&](const std::string &val) { return has(val) && (exists || val != pk); });
     values.resize(std::distance(values.begin(), it));
     return values;
 }
Пример #19
0
TEST_F(ProjectionTests, BasicTest) {
  MockExecutor child_executor;
  EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true));

  EXPECT_CALL(child_executor, DExecute())
      .WillOnce(Return(true))
      .WillOnce(Return(false));

  size_t tile_size = 5;

  // Create a table and wrap it in logical tile
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  std::unique_ptr<storage::DataTable> data_table(
      ExecutorTestsUtil::CreateTable(tile_size));
  ExecutorTestsUtil::PopulateTable(txn, data_table.get(), tile_size, false,
                                   false, false);
  txn_manager.CommitTransaction();

  std::unique_ptr<executor::LogicalTile> source_logical_tile1(
      executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0)));

  EXPECT_CALL(child_executor, GetOutput())
      .WillOnce(Return(source_logical_tile1.release()));

  // Create the plan node
  planner::ProjectInfo::TargetList target_list;
  planner::ProjectInfo::DirectMapList direct_map_list;

  /////////////////////////////////////////////////////////
  // PROJECTION 0
  /////////////////////////////////////////////////////////

  // construct schema
  std::vector<catalog::Column> columns;
  auto orig_schema = data_table.get()->GetSchema();
  columns.push_back(orig_schema->GetColumn(0));

  std::shared_ptr<const catalog::Schema> schema(new catalog::Schema(columns));

  // direct map
  planner::ProjectInfo::DirectMap direct_map =
      std::make_pair(0, std::make_pair(0, 0));
  direct_map_list.push_back(direct_map);

  std::unique_ptr<const planner::ProjectInfo> project_info(
      new planner::ProjectInfo(std::move(target_list),
                               std::move(direct_map_list)));

  planner::ProjectionPlan node(std::move(project_info), schema);

  // Create and set up executor
  executor::ProjectionExecutor executor(&node, nullptr);
  executor.AddChild(&child_executor);

  RunTest(executor, 1);
}
Пример #20
0
void CsvChunkLoader::bindHook()
{
    // For now at least, flat arrays only.
    Dimensions const& dims = schema().getDimensions();
    if (dims.size() != 1) {
        throw USER_EXCEPTION(SCIDB_SE_IMPORT_ERROR,
                             SCIDB_LE_MULTIDIMENSIONAL_ARRAY_NOT_ALLOWED);
    }
}
void
KexiRelationsTableFieldList::dropEvent(QDropEvent *event)
{
    kDebug();
    QModelIndex idx = indexAt(event->pos());

    if (!idx.isValid() || !KexiFieldDrag::canDecode(event)) {
        event->ignore();
        return;
    }
    QString sourceMimeType;
    QString srcTable;
    QStringList srcFields;
    QString srcField;

    if (!KexiFieldDrag::decode(event, sourceMimeType, srcTable, srcFields)) {
        return;
    }

    if (sourceMimeType != "kexi/table" && sourceMimeType == "kexi/query") {
        return;
    }

    if (srcFields.count() != 1) {
        return;
    }
    srcField = srcFields[0];
//  kDebug() << "srcfield:" << srcField;

    QString rcvField = model()->data(idx, Qt::DisplayRole).toString();

    SourceConnection s;
    s.masterTable = srcTable;
    s.detailsTable = schema()->name();
    s.masterField = srcField;
    s.detailsField = rcvField;

    m_scrollArea->addConnection(s);

    kDebug() << srcTable << ":" << srcField << schema()->name() << ":" << rcvField;
    event->accept();
}
Пример #22
0
// Test basic functionality
TEST_F(SkipListMapTest, BasicTest) {

  std::vector<catalog::Column> columns;

  catalog::Column column1(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER), "A", true);
  columns.push_back(column1);
  catalog::Schema *schema(new catalog::Schema(columns));
  std::vector<storage::Tuple*> tuples;

  storage::Tuple *tuple1(new storage::Tuple(schema, true));
  tuple1->SetValue(0, ValueFactory::GetIntegerValue(1), nullptr);
  tuples.push_back(tuple1);
  storage::Tuple *tuple2(new storage::Tuple(schema, true));
  tuple2->SetValue(0, ValueFactory::GetIntegerValue(2), nullptr);
  tuples.push_back(tuple2);
  storage::Tuple *tuple3(new storage::Tuple(schema, true));
  tuple3->SetValue(0, ValueFactory::GetIntegerValue(3), nullptr);
  tuples.push_back(tuple3);

  LOG_INFO("%s", tuple1->GetInfo().c_str());

  SkipListMap<key_type, value_type, key_comparator> map;

  EXPECT_TRUE(map.IsEmpty());

  size_t const element_count = tuples.size();

  for (size_t element = 0; element < element_count; ++element ) {
    key_type key;
    key.SetFromKey(tuples[element]);

    value_type val = &foo;
    auto status = map.Insert(key, val);
    EXPECT_TRUE(status);
    status = map.Insert(key, val);
    EXPECT_FALSE(status);
  }

  for (size_t element = 0; element < element_count; ++element ) {
    key_type key;
    key.SetFromKey(tuples[element]);

    value_type value = &bar;
    auto status = map.Find(key, value);
    EXPECT_TRUE(status);
    EXPECT_EQ(foo.block, value->block);
    LOG_INFO("bar : %d %d", value->block, value->offset);
  }

  for(auto tuple : tuples) {
    delete tuple;
  }
  delete schema;
}
Пример #23
0
TEST_F(ExpressionTests, DistinctFromTest) {
  // Create a table with id column and value column
  std::vector<catalog::Column> columns;

  catalog::Column column1(type::TypeId::INTEGER,
                          type::Type::GetTypeSize(type::TypeId::INTEGER), "id",
                          true);
  catalog::Column column2(type::TypeId::INTEGER,
                          type::Type::GetTypeSize(type::TypeId::INTEGER), "value",
                          true);

  columns.push_back(column1);
  columns.push_back(column2);

  std::unique_ptr<catalog::Schema> schema(new catalog::Schema(columns));

  std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(schema.get(), true));

  // Create "id IS DISTINCT FROM value" comparison
  auto lexpr = new expression::TupleValueExpression(type::TypeId::INTEGER, 0, 0);
  auto rexpr = new expression::TupleValueExpression(type::TypeId::INTEGER, 1, 1);

  expression::ComparisonExpression expr(
      StringToExpressionType("COMPARE_DISTINCT_FROM"), lexpr, rexpr);

  auto pool = TestingHarness::GetInstance().GetTestingPool();

  // id, value not NULL with the same values, should be false
  tuple->SetValue(0, type::ValueFactory::GetIntegerValue(10), pool);
  tuple->SetValue(1, type::ValueFactory::GetIntegerValue(10), pool);
  EXPECT_TRUE(expr.Evaluate(tuple.get(), tuple.get(), nullptr).IsFalse());

  // id, value not NULL with different values, should be true
  tuple->SetValue(1, type::ValueFactory::GetIntegerValue(5), pool);
  EXPECT_TRUE(expr.Evaluate(tuple.get(), tuple.get(), nullptr).IsTrue());

  // id not NULL, value is NULL, should be true
  tuple->SetValue(1,
      type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER), pool);
  EXPECT_TRUE(expr.Evaluate(tuple.get(), tuple.get(), nullptr).IsTrue());

  // id is NULL, value not NULL, should be true
  tuple->SetValue(0,
      type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER), pool);
  tuple->SetValue(1, type::ValueFactory::GetIntegerValue(10), pool);
  EXPECT_TRUE(expr.Evaluate(tuple.get(), tuple.get(), nullptr).IsTrue());

  // id is NULL, value is NULL, should be false
  tuple->SetValue(1,
       type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER), pool);
  EXPECT_TRUE(expr.Evaluate(tuple.get(), tuple.get(), nullptr).IsFalse());
}
Пример #24
0
int Space::insertSchema(int index, SharedPtr<Range> range, SharedPtr<View> view, SharedPtr<Layout> layout)
{
    ItemSchema schema(range, layout, view);

    m_schemas.insert(index, schema);
    m_schemasOrdered.clear();

    connectSchema(schema);

    emit spaceChanged(this, ChangeReasonSpaceItemsStructure);

    return index;
}
void KexiRelationsTableFieldList::dragMoveEvent(QDragMoveEvent* event)
{
    QModelIndex receiver = indexAt(event->pos());
    if (!receiver.isValid() || !KexiFieldDrag::canDecode(event))
        return;
    QString sourceMimeType;
    QString srcTable;
    QStringList srcFields;
    QString srcField;

    if (!KexiFieldDrag::decode(event, sourceMimeType, srcTable, srcFields)) {
        event->ignore();
        return;
    }

    if (sourceMimeType != "kexi/table" && sourceMimeType == "kexi/query") {
        event->ignore();
        return;
    }

    if (srcFields.count() != 1) {
        event->ignore();
        return;
    }

    srcField = srcFields[0];

    if (srcTable == schema()->name()) {
        event->ignore();
        return;
    }

    QString f = model()->data(receiver, Qt::DisplayRole).toString();

    kDebug() << "Source:" << srcTable << "Dest:" << schema()->name();

    if (!srcField.trimmed().startsWith("*") && !f.startsWith("*"))
        event->acceptProposedAction();
}
Пример #26
0
QDragObject* KexiFieldListView::dragObject()
{
	if (!schema())
		return 0;
	const QStringList selectedFields( selectedFieldNames() );
	return new KexiFieldDrag(m_schema->table() ? "kexi/table" : "kexi/query", 
		m_schema->name(), selectedFields, this, "KexiFieldDrag");
/*	if (selectedItem()) {
		KexiFieldDrag *drag = new KexiFieldDrag("kexi/table", m_schema->name(), 
			selectedItem()->text(1), this, "KexiFieldDrag");
			return drag;
	}*/
}
Пример #27
0
/*----------------------------------------------------------------------
|   OZN_Database::CheckTableSchema
+---------------------------------------------------------------------*/
NPT_Result 
OZN_Database::CheckTableSchema(const OZN_TableDescription& desc) 
{
    NPT_Result          res = NPT_FAILURE;
    NPT_String          sql;
    NPT_String          sql_create;
    OZN_StringProperty  schema(0, "");
    const char*         result;

    // generate the sql statement we would use to create the table
    NPT_CHECK(OZN_Sql::CreateTable(desc, sql_create));

    // generate the sql statement to query for a table schema
    NPT_CHECK(OZN_Sql::GetTableSchema(desc.name, sql));

    // query the db, if the table doesn't exist it will fail
    res = ExecuteScalar(sql, schema);
    result = schema.GetValue().string;
    if (NPT_SUCCEEDED(res) && result && result[0] != '\0') {
        //if existing table schema sql matches the one we would use
        // then it is the same table and same schema version
        if (NPT_StringsEqual(result, sql_create)) {
            return NPT_SUCCESS;
        }

        // weird, the query succeeded but returned nothing
        return NPT_FAILURE;
    }

    // close bracket
    OZN_Sql::Close(sql_create);

    // table doesn't exist, create it
    NPT_CHECK(ExecuteDML(sql_create, NULL));

    if (desc.unique_index_ids_count && desc.unique_index_ids) {
        res = OZN_Sql::CreateUniqueIndex(desc, 
            desc.unique_index_ids,
            desc.unique_index_ids_count,
            sql);
        NPT_CHECK(res);

        // close bracket
        OZN_Sql::Close(sql);

        // create unique index
        NPT_CHECK(ExecuteDML(sql, NULL));
    }

    return NPT_SUCCESS;
}
Пример #28
0
S_Yang_Schemas Session::list_schemas()
{
    S_Yang_Schemas schema(new Yang_Schemas());

    int ret = sr_list_schemas(_sess, &schema->_sch, &schema->_cnt);
    if (SR_ERR_OK == ret) {
        schema->_deleter = std::make_shared<Deleter>(schema->_sch, schema->_cnt);
        return schema;
    }
    if (SR_ERR_NOT_FOUND == ret) {
        return nullptr;
    }
    throw_exception(ret);
}
Пример #29
0
bool CreateExecutor::DExecute() {
  LOG_TRACE("Executing Create...");
  const planner::CreatePlan &node = GetPlanNode<planner::CreatePlan>();
  auto current_txn = context->GetTransaction();

  // Check if query was for creating table
  if (node.GetCreateType() == CreateType::TABLE) {
    std::string table_name = node.GetTableName();
    auto database_name = node.GetDatabaseName();
    std::unique_ptr<catalog::Schema> schema(node.GetSchema());

    ResultType result = catalog::Catalog::GetInstance()->CreateTable(
        database_name, table_name, std::move(schema), current_txn);
    current_txn->SetResult(result);

    if (current_txn->GetResult() == ResultType::SUCCESS) {
      LOG_TRACE("Creating table succeeded!");
    } else if (current_txn->GetResult() == ResultType::FAILURE) {
      LOG_TRACE("Creating table failed!");
    } else {
      LOG_TRACE("Result is: %s",
                ResultTypeToString(current_txn->GetResult()).c_str());
    }
  }

  // Check if query was for creating index
  if (node.GetCreateType() == CreateType::INDEX) {
    std::string table_name = node.GetTableName();
    std::string index_name = node.GetIndexName();
    bool unique_flag = node.IsUnique();
    IndexType index_type = node.GetIndexType();

    auto index_attrs = node.GetIndexAttributes();

    ResultType result = catalog::Catalog::GetInstance()->CreateIndex(
        DEFAULT_DB_NAME, table_name, index_attrs, index_name, unique_flag,
        index_type, current_txn);
    current_txn->SetResult(result);

    if (current_txn->GetResult() == ResultType::SUCCESS) {
      LOG_TRACE("Creating table succeeded!");
    } else if (current_txn->GetResult() == ResultType::FAILURE) {
      LOG_TRACE("Creating table failed!");
    } else {
      LOG_TRACE("Result is: %s",
                ResultTypeToString(current_txn->GetResult()).c_str());
    }
  }
  return false;
}
Пример #30
0
connectionStatus_t DrillClient::connect(const char* connectStr, const char* defaultSchema){
    connectionStatus_t ret=CONN_SUCCESS;
    ret=this->m_pImpl->connect(connectStr);
    DrillUserProperties props;
    std::string schema(defaultSchema);
    props.setProperty(USERPROP_SCHEMA,  schema);
    if(ret==CONN_SUCCESS){
        if(defaultSchema!=NULL){
            ret=this->m_pImpl->validateHandshake(&props);
        }else{
            ret=this->m_pImpl->validateHandshake(NULL);
        }
    }
    return ret;
}