Hi,
I am trying to create dynamically database with next code
var
MetaConn: TPQConnection;
CheckTran: TSQLTransaction;
Qry: TSQLQuery;
CreateConn: TPQConnection;
begin
Result := False;
// Konekcija za proveru postojanja baze
MetaConn := TPQConnection.Create(nil);
MetaConn.HostName := GlobalDBConfig.Host;
MetaConn.UserName := GlobalDBConfig.User;
MetaConn.Password := GlobalDBConfig.Password;
MetaConn.DatabaseName := 'postgres';
CheckTran := TSQLTransaction.Create(MetaConn);
MetaConn.Transaction := CheckTran;
try
MetaConn.Connected := True;
Qry := TSQLQuery.Create(nil);
Qry.DataBase := MetaConn;
Qry.Transaction := CheckTran;
Qry.SQL.Text := 'SELECT 1 FROM pg_database WHERE datname = ' + QuotedStr(GlobalDBConfig.Database);
Qry.Open;
if Qry.IsEmpty then
begin
Qry.Close;
CheckTran.Commit;
// new connection WITHOUT transaction for DB creating
CreateConn := TPQConnection.Create(nil);
try
CreateConn.HostName := GlobalDBConfig.Host;
CreateConn.UserName := GlobalDBConfig.User;
CreateConn.Password := GlobalDBConfig.Password;
CreateConn.DatabaseName := 'postgres';
CreateConn.Connected := True;
CreateConn.ExecuteDirect(
'CREATE DATABASE "' + GlobalDBConfig.Database + '" WITH OWNER = ' +
QuotedStr(GlobalDBConfig.User) + ' ENCODING = ''UTF8'''
);
Result := True;
finally
CreateConn.Free;
end;
end
else
Result := True;
finally
Qry.Free;
CheckTran.Free;
MetaConn.Free;
end;
But, on executing
CreateConn.ExecuteDirect(
'CREATE DATABASE "' + GlobalDBConfig.Database + '" WITH OWNER = ' +
QuotedStr(GlobalDBConfig.User) + ' ENCODING = ''UTF8'''
);
exists problem Transaction not Set.
On execution
var
MetaConn: TPQConnection;
CheckTran: TSQLTransaction;
Qry: TSQLQuery;
begin
Result := False;
// Konekcija za proveru postojanja baze
MetaConn := TPQConnection.Create(nil);
MetaConn.HostName := GlobalDBConfig.Host;
MetaConn.UserName := GlobalDBConfig.User;
MetaConn.Password := GlobalDBConfig.Password;
MetaConn.DatabaseName := 'postgres';
CheckTran := TSQLTransaction.Create(MetaConn);
MetaConn.Transaction := CheckTran;
try
MetaConn.Connected := True;
Qry := TSQLQuery.Create(nil);
Qry.DataBase := MetaConn;
Qry.Transaction := CheckTran;
Qry.SQL.Text := 'SELECT 1 FROM pg_database WHERE datname = ' + QuotedStr(GlobalDBConfig.Database);
Qry.Open;
if Qry.IsEmpty then
begin
Qry.Close;
CheckTran.Commit;
MetaConn.ExecuteDirect(
'CREATE DATABASE "' + GlobalDBConfig.Database + '" WITH OWNER = ' +
QuotedStr(GlobalDBConfig.User) + ' ENCODING = ''UTF8'''
);
Result := True;
end
else
Result := True;
finally
Qry.Free;
CheckTran.Free;
MetaConn.Free;
end;
an error appears "Create database cannot run inside transaction block"
Any suggestion?
Thanks in advance
Bojan