Tuesday, August 09, 2011

Fluent notation in PL/SQL

I am a big fan of the Fluent notation that has been gaining popularity in the .NET world. I decided to do an experiment to see if I can get PL/SQL to have something similar.

I managed to make this work:

declare
  ftp fluent_ftp := fluent_ftp();
begin
  ftp.run(
    ftp.for_country('UG',
      ftp.for_period('2011', '01', '01', ftp)
    )
  );
end;

To enable this type of syntax I had to create a custom type in PL/SQL first.

CREATE OR REPLACE TYPE schema.fluent_ftp AS OBJECT
(
    country_cd   VARCHAR2(2),
    fin_year_cd  VARCHAR2(4),
    fin_month_cd VARCHAR2(4),
    fin_day_cd   VARCHAR2(4),
    CONSTRUCTOR FUNCTION fluent_ftp RETURN SELF AS RESULT,
    CONSTRUCTOR FUNCTION fluent_ftp
    (
        a_fin_year_cd  VARCHAR2,
        a_fin_month_cd VARCHAR2,
        a_fin_day_cd   VARCHAR2,
        a_country_cd   VARCHAR2
    ) RETURN SELF AS RESULT,

Internally the new type just calls the existing API so no changes are needed on the underlying API at all.

MEMBER PROCEDURE run(a_fluent_ftp fluent_ftp) IS
    BEGIN
        schema.calculate_ftp.run(a_country_cd   => a_fluent_ftp.country_cd,
                                         a_system_code  => '',
                                         a_fin_year_cd  => a_fluent_ftp.fin_year_cd,
                                         a_fin_month_cd => a_fluent_ftp.fin_month_cd,
                                         a_fin_day_cd   => a_fluent_ftp.fin_day_cd);
    EXCEPTION
        WHEN OTHERS THEN
            RAISE;
        
    END run;

So that is how you can mimic the Fluent notation that the .NET community is enjoying currently on products like Fluent NHibernate and others.