Search code examples
c++builderfiredac

FireDAC TFDTable CreateTable


I am trying to use the CreateTable() method of FireDAC's TFDTable class to create a table on my MySQL Server.

void __fastcall TFormMain::ButtonCreateTableClick(TObject *Sender)
{
    TFDTable *Table = new TFDTable(this);

    try
    {
        Table->Connection = FDConnection;
        Table->TableName = "Setting";
        Table->Exclusive = true;

        //Table->FieldDefs->Add( "SettingCode", ftString, 99 );
        //Table->FieldDefs->Add( "SettingValue", ftString, 255 );

        TField *Field;

        Field = new TStringField( this );
        Field->Name = "FieldSettingCode";
        Field->FieldName = "SettingCode";
        Field->Size = 100;
        Field->DataSet = Table;

        Field = new TStringField( this );
        Field->Name = "FieldSettingValue";
        Field->FieldName = "SettingValue";
        Field->Size = 255;
        Field->DataSet = Table;

        //  Fires "Table 'Setting' doesn't exist" error
        Table->CreateTable( false, TFDPhysCreateTableParts() << tpTable << tpPrimaryKey << tpIndexes );
        Table->Open();

        Table->Insert();
        Table->FieldByName("SettingCode")->Value = "test2";
        Table->FieldByName("SettingValue")->Value = "testValue2";
        Table->Post();

        // Table->CreateDataSet();
    }
    __finally
    {
        Table->Free();
    }
}

As soon as I call the CreateTable method it throws an error that the table xxxx.Setting does not exist:

Im Projekt DBCreator.exe ist eine Exception der Klasse EMySQLNativeException mit der Meldung '[FireDAC][Phys][MySQL] Table 'setting' already exists' aufgetreten.

So far so good: This error message is correct - but the real fun fact is, that the table has been successfully created and the code has been inserted.

This also happens using SQLite instead of MySQL.

I am using Embarcadero C++ Builder XE10 Seattle.

How should I handle this correctly? Is there a way to supress this pretty useless error message?

Edit: It turned out that EMySQLNativeException is only thrown when the debugger is running. So I just clicked the checkbox to ignore these exceptions and everything is good.

Creating databases with TFDTable and CreateTable() works like charm. Unfortunately it is just undocumented at all (like almost everything @Borland/CodeGear/Embarcadero)...


Solution

  • That exception is thrown by the FireDAC engine and is caused by an attempt to create table without checking if already exists. It is internally handled and the engine acts properly, so what you see is a debugger exception message. If you called the CreateTable method with the recreation parameter enabled:

    Table->CreateTable( True, TFDPhysCreateTableParts() << tpTable << tpPrimaryKey << tpIndexes );
    

    the table would be first deleted and you would not get the mentioned exception for this reason.