Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple DB connections in a single resource #153

Open
ertankucukoglu opened this issue Dec 17, 2024 · 2 comments
Open

Multiple DB connections in a single resource #153

ertankucukoglu opened this issue Dec 17, 2024 · 2 comments

Comments

@ertankucukoglu
Copy link

Hello,

Is it possible to use multiple database connections in the same resource? What I am looking for is a way to do something like below

  [Path('twodb'), Connection('MAIN_DB'), Connection('MYSQL_DB'), RolesAllowed('user')]
  TMyTwoDBResource = class
  protected
    [Context] UD: TMARSUniDAC;
    [Context] UD2: TMARSUniDAC;
  public
...

I can read database connection parameters from some settings file and connect to the second database writing my own code. However, it would be more convenient if something like above is available.

Thanks & Regards,
Ertan

@ertankucukoglu
Copy link
Author

Multiple database usage in a single class seems to be already exists.

Below works just fine

  [Path('somepath'), Connection('MAIN_DB'), Connection('MYSQL_DB'), RolesAllowed('user')]
  TSomeResource = class
  protected
    [Context, Connection('MAIN_DB')] UD: TMARSUniDAC;
    [Context, Connection('MYSQL_DB')] UD2: TMARSUniDAC;
    ....

Thanks & Regards,
Ertan

@ertankucukoglu
Copy link
Author

I though this is working but it didn't. Likely I made a mistake while testing.
Below seems to work fine for me. I need to take care of freeing the instance though.

[Path('somepath'), RolesAllowed('user')]
TSomeResource = class
protected
  [Context] UD: TMARSUniDAC;
  ....

In any class procedure/function secondary database can be accessed as below

procedure TSomeResource.UsesDoubleDB;
var
  LConnection: TUniConnection; // for the second database access
  LQuery1stDB: TUniQuery,
  LQuery2ndDB: TUniQuery;
begin
  LConnection := nil;
  LQuery1stDB := nil;
  LQuery2ndDB := nil;
  try
    LConnection := UD.CreateConnectionByDefName('SECOND_DB', nil); // Get a connection object for the SEDOND_DB

    LQuery1stDB := TUniQuery.Create(nil);
    LQuery1stDB.Connection := UD.Connection; // MAIN_DB connection

    LQuery2ndDB := TUniQuery.Create(nil);
    LQuery2ndDB.Connection := LConnection; // SECOND_DB connection
  finally
    LQuery1stDB.Free();
    LQuery2ndDB.Free();
    LConnection.Free();
  end;
end;

I am leaving the issue open as I still would like to know if there is an alternative version that the MARS engine has the control on the connection object freeing.

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant