Delimiter //
/**
 * Add a Row in the Contact's loader table
 *
 * @author Armen
 */
Drop Procedure If Exists LOADER_TEST_MOCK_PUSH//
Create Procedure LOADER_TEST_MOCK_PUSH(
    In loaderTableName Varchar(80)
    , In id Int
    , In datas Text
    , In id_status Int
    , In datas_status Text
)
Begin
    Declare primaryKey varchar(50);
    Set @loaderTableName = loaderTableName;
    if @loaderTableName Not LIKE 'LOADER\\_%' Then
        Set @loaderTableName = Concat('LOADER_', @loaderTableName);
    End If;

    getPrimary: begin
        Declare pcursor cursor for 
            Select 
                `COLUMN_NAME`
            From 
                information_schema.KEY_COLUMN_USAGE 
            Where 
                TABLE_SCHEMA = schema()
                And `TABLE_NAME` Collate UTF8_general_ci  = @loaderTableName Collate UTF8_general_ci 
                And `CONSTRAINT_NAME` = 'PRIMARY'
                And ORDINAL_POSITION = 1  
        ;
        open pcursor;
            fetch pcursor Into primaryKey;
        close pcursor;
    end ;


    Set @id_status = id_status;
    If Coalesce(id_status,0) = 0 
        Then 
            Set @id_status = (Select Coalesce(Max(ID_LOADER_STATUS), 0) + 1 From LOADER_STATUS);
            call LOADER_TEST_MOCK_STATUS_PUSH(@id_status, datas_status);
    Else
        Set @found = (Select ID_LOADER_STATUS From LOADER_STATUS Where ID_LOADER_STATUS = @id_status);
        If @found Is Null Then
            Set @id_status = (Select Coalesce(Max(ID_LOADER_STATUS), 0) + 1 From LOADER_STATUS);
            call LOADER_TEST_MOCK_STATUS_PUSH(@id_status, datas_status);
        End If;
    End If;

    Set datas = Concat(
        'LOADER_STATUS_ID_LOADER_STATUS = ', @id_status 
        , ',', primaryKey,' = ' , id
        , ',', datas);
    Set @query = Concat('Insert Into ', @loaderTableName, ' Set ', datas);

    Prepare stmt FROM @query;
    Execute stmt;
    Deallocate prepare stmt;
End//
Delimiter ;