← 输入框|github.com|刷新
Skip to content

Add ability to parse annotations when package specification is getting compiled #631

Closed

Description

@jgebal

We could leverage schema level triggers to avoid time-consuming parsing, when scanning schema for suites.
If we would use triggers after create/alter/drop on schema, we could initiate parsing for a particular object and update annotation cache.
That way we minimize the impact on users when using context-menu in SQLDeveloper on large schema.

That feature could be installed/enabled optionally (decission at install time).
Alternatively, utPLSQL could try to create a trigger on user-behalf when running a scan on a schema.

Regardless of apprach, we should make sure that when utPLSQL gets removed, the leftover triggers will not cause any issues to schema where they were created.

There are few more things to consider however before we happily start implementing it.
Some resources:
https://docs.oracle.com/cloud/latest/db112/LNPLS/create_trigger.htm#LNPLS01374
https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:267415465220
http://psoug.org/reference/ddl_trigger.html

Activity

  1. lwasylow commented on Apr 8, 2018

    @lwasylow
    Member

    I think problem here is that test packages can be put in different places depending on strategies chosen. If they are in separate scheme that impact is minimal however if they are part of tested scheme then any changes there will be affected by trigger. I think this can be quite invasive approach and definitely need to be an optional feature.

  2. pesse commented on Apr 8, 2018

    @pesse
    Member

    @jgebal is Improvement of SQLDeveloper Context menu the only benefit you see? Because I think that can be handled much easier by caching layer in java-API. I already got some ideas and will start working on it after the CodeTalk is done.
    I'm not sure the additional complexity and potential side-effects are worth it unless you see some other possible improvements.

  3. lwasylow commented on Apr 8, 2018

    @lwasylow
    Member

    What about rather than parsing a package every time capture details of last created / compiled from dba views in cache table and parse only ones that changed since last time been parsed. Generally caching is a hard topic and don't think is a golden solution

  4. pesse commented on Apr 8, 2018

    @pesse
    Member

    Caching is an absolute necessity and pretty normal when we talk about client <-> database connection. It's not about caching things for hours or even minutes, more like caching things for seconds and outsource the burden of keeping the cache up-to-date in a seperate thread which does not slow down UI interaction. Call it buffering if that sounds nicer to you ;)

  5. lwasylow commented on Apr 8, 2018

    @lwasylow
    Member

    I do agree with that, just personally would not use triggers, but that's my personal opinion :)

  6. jgebal commented on Apr 8, 2018

    @jgebal
    MemberAuthor

    Guys. Cache is already there.
    It does as you say - check if something changed and if so - parse annotations.
    This "check if anything changed" however is a bit heavy on huge DB schemas.
    Also, if something did change it gets even heavier.
    With trigger, we could simply do it not at test run but at compile time.

  7. jgebal commented on Apr 8, 2018

    @jgebal
    MemberAuthor

    Here is a working POC for this:

    CREATE OR REPLACE TRIGGER bcs_trigger
    AFTER CREATE OR ALTER OR DROP
    ON SCHEMA
    DECLARE
      l_sql_text    ORA_NAME_LIST_T;
      l_parts       INTEGER;
    BEGIN
      IF ora_dict_obj_type = 'PACKAGE' THEN
        l_parts := ORA_SQL_TXT(l_sql_text);
        execute immediate 
          'begin
             ut3.ut_annotation_manager.rebuild_obj_annotation_cache(
               :ora_dict_obj_owner,
               :ora_dict_obj_name,
               :ora_dict_obj_type,
               :l_sql_text
             );
          end;'
        using ora_dict_obj_owner, ora_dict_obj_name, ora_dict_obj_type, l_sql_text;
        
      END IF;
    EXCEPTION 
      WHEN OTHERS THEN NULL;
    END bcs_trigger;
    /

    Add to ut_annotation_manager spec:

      /**
       * Rebuilds annotation cache for a specified object.
       *
       * @param a_object_owner owner of objects to get annotations for
       * @param a_object_name name of objects to get annotations for
       */
      procedure rebuild_obj_annotation_cache(
        a_object_owner varchar2,
        a_object_name varchar2,
        a_object_type varchar2,
        a_sql_text ora_name_list_t
      );

    and to body:

      procedure rebuild_obj_annotation_cache(
        a_object_owner varchar2,
        a_object_name varchar2,
        a_object_type varchar2,
        a_sql_text ora_name_list_t
      ) is
        l_object_to_parse ut_annotation_obj_cache_info;
    
        function get_source_from_sql_text(a_object_name varchar2, a_sql_text ora_name_list_t) return sys_refcursor is
          l_sql_clob    clob;
          l_sql_lines   ut_varchar2_rows := ut_varchar2_rows();
          l_parts       integer;
          l_result      sys_refcursor;
          l_sql_text    ora_name_list_t := a_sql_text;
        begin
          l_parts := l_sql_text.count;
          if l_parts > 0 then
            l_sql_text(1) := regexp_replace(l_sql_text(1),'^[\t ]*create([\t ]*or[\t ]*replace)?[\t ]*', modifier => 'i');
            for i in 1..l_parts loop
              ut_utils.append_to_clob(l_sql_clob, l_sql_text(i));
            end loop;
            l_sql_lines := ut_utils.convert_collection( ut_utils.clob_to_table(l_sql_clob) );
          end if;
          open l_result for
            select a_object_name as name, column_value||chr(10) as text from table(l_sql_lines);
          return l_result;
        end;
      begin
        l_object_to_parse := ut_annotation_obj_cache_info(a_object_owner, a_object_name, a_object_type, 'Y');
        build_annot_cache_for_sources(
            a_object_owner, a_object_type,
            get_source_from_sql_text(a_object_name, a_sql_text),
            ut_annotation_objs_cache_info(l_object_to_parse)
        );
      end;
  8. jgebal commented on Apr 8, 2018

    @jgebal
    MemberAuthor

    The big question is:

    • When should we be creating (trying to create) the trigger?

    If no trigger is present/firing - the behavior is as today - cache is smart-scanned and refreshed on run.

    We probably cant rely on trigger begin present, so a check would still need to be done to see if annotations cache in schema is up to date by running something like:
    select count(1), max(last_ddl_timestamp) from dba_objects where owner = :x and type = :y

  9. lwasylow commented on Apr 8, 2018

    @lwasylow
    Member

    Yes definitely we need to, last thing we want to is to have invalid results with performance cost.
    As for trigger, it should be part of installation as user / DBA need to be aware of that as some of dba are not happy with database level triggers, and also done at very last. Probably would also have to exclude framework packages from list.
    That is my opinion on that ;)

  10. Pazus commented on Apr 9, 2018

    @Pazus
    Member

    Let me join the discussion.

    I don’t like the trigger approach as we are going to introduce an object which knows about the internal of the framework and is not part of it (it is placed in another schema, schema with tests not the framework). So we’d introduce an “alien”, “spying” object in the foreighn place. Who is responsible for dropping it when the framework is uninstalled? Remember it’ll invalidate and block all compilations! There are also other concerns...

    I think the current cache is enough from the DB part of the framework. It is refreshed on the run. On the client (SQL Developer) I suppose we can catch compilation command, refresh cache in the background after successful recompilation and requery the framework cache tables to refresh client data.
    We might still face the outdated cache but only if someone else recompiled an object. Not sure it’s crucial enough to introduce complexity with trigger.

    What we might think about is a light cache invalidation check, so that client can refresh the cache while tests are executing or time to time on scheduled basis. Maybe we should associate some kind of hash/guid value with a cache state so it’s easier to check.

  11. pesse commented on Apr 9, 2018

    @pesse
    Member

    What @Pazus writes are exactly my concerns, therefore I asked whether boosting SQLDeveloper UI experience is the only benefit you see, @jgebal. If so, I think it should be solved by client-caching via java-API, not by additional complexity in core.
    A light cache invalidation check would be very helpful, though.

  12. Pazus commented on Apr 9, 2018

    @Pazus
    Member

    Do you think there is a way to improve current caching so that we reparse only changed objects and restructure the suites?

  13. jgebal commented on Apr 9, 2018

    @jgebal
    MemberAuthor

    Current caching is already smart. It does a check to see what has changed and parse changed objects only.
    That chec itself is still slow on huge schema (like EBS) even if nothing is changed.

  14. 8 remaining items

  15. jgebal commented on Jun 20, 2018

    @jgebal
    MemberAuthor

    I'm still thinking about that challenge.
    To give some background on current state.

    • We have persistent cache in utPLSQL schema. We store info on object and last parse date as well as list of annotations
    • We have in-memmory session level cache, that keeps whole suite objects hierarchy. It is built when a schema suite is invoked in session.

    Challenges:

    • Each time we call ut.run we perform cache validation against dba_objects/all_objects to check for objects recompiled since last run.
      This is time consuming.
    • If any package is recompiled, we re-parse it and update cache. This is time consuming, especially when multiple packages were recompiled.

    If we think of annotations as part of database engine and a separate library to utPLSQL, it makes perfect sence to parse annotations on compile-time.

    Parsing at runtime kills the performance. Benefits of TDD (fast feedback loop) are going away when you need to wait 5-7 seconds for framework to start.

    Adding another level of cache on client (java api) will not adress those challenges. Each time I compile package or test package the cache needs to be revalidated. This takes/can take more time than parsing single package.
    Client level cache will not solve problem when integration/calls to framework are done from within PLSQL itself.

    I would consider separating annotatins as a totally separate and independent module (project) that is used by utPLSQL.

    Annotations could then be used by other projects.
    Annotations coul/should be parsed and persisted at compile time to minimize the overhead of cache validation.

    When auto-parse is enabled, we would take the persistent cache for granted and simply run suites as defined by persistent annotations data.

  16. Pazus commented on Jun 21, 2018

    @Pazus
    Member

    Remember that it’ll make all compilations longer. If it takes 1 second to parse a package, and you compile it 10 times in a row, it’s +10 secs of compilation... even if there are no annotations in it.

  17. lwasylow commented on Jun 21, 2018

    @lwasylow
    Member

    If I understood right you propose to split utplsql and annotations into separate project and separate installations?

  18. mathewbutler commented on Jun 21, 2018

    @mathewbutler
    Contributor

    Have we assessed where all the time goes when managing the annotation cache and why the areas that are taking the time are slow?

    I can see there are some intersting ideas on how to deal with the cache issue. I’m keen though that we don’t just move the problem somewhere else, or that the performance of the existing implementation may be improved without an architectural change.

  19. jgebal commented on Jun 21, 2018

    @jgebal
    MemberAuthor

    Performance will definitely need to be tested and documented.

  20. jgebal commented on Jun 21, 2018

    @jgebal
    MemberAuthor

    I propose to separate amnotations so
    they can be installed standalone or as part of a bundle in other project.

    utPLSQL releases would bundle appropriate version of annotations and when installing utPLSQL, annotations would also be installed.

  21. jgebal commented on Jun 21, 2018

    @jgebal
    MemberAuthor

    Most of thime goes into reading DBA_OBJECTS and DBA_SOURCE.

  22. jgebal commented on Jun 21, 2018

    @jgebal
    MemberAuthor

    Here are reports produced by @PhilippSalvisberg running on a very large (40k+ packages) schema.
    Scenario:

    1. Install utPLSQL or cleanup annotation cache.
    2. execute ut.run('large_schema.non_existing_package');
    3. Get report for first (initial) run.
    4. execute ut.run('large_schema.non_existing_package');
    5. Get report for second run with cache populated

    Scenario was executed on schema that has zero unit tests, so the results are not affected by annotation parsing or suite building.

    trace_run_non_existing_ptest_package.zip

  23. mathewbutler commented on Jun 22, 2018

    @mathewbutler
    Contributor

    I’ll try and have a look at this later.

    I’d expect this to be a single select against dictionary with criteria to filter for test packages and/or invalid state.

    Strangely work have decided to block github so will see if I can workaround this to get the file and analyse.

  24. mathewbutler commented on Jun 22, 2018

    @mathewbutler
    Contributor

    Had a P1 issue today that wiped my day out. Will try and look at this over the weekend.

  25. mathewbutler commented on Jun 24, 2018

    @mathewbutler
    Contributor

    Analysis of initial cache population.

    Here's how the profiles were generated;

    1. Install utPLSQL or cleanup annotation cache.
    2. execute ut.run('large_schema.non_existing_package');
    3. Get report for first (initial) run.
    4. execute ut.run('large_schema.non_existing_package');
    5. Get report for second run with cache populated

    So, the first profile is when there are no test packages and the work is to populate the cache. Here;s the resource profile;

    image

    This shows that the majority (90%) of the time is spent reading indexes to retrieve data.

    Statement 2 from the profile contributes most to this;

    image

    This is statement 2;

    image

    i.e. obtain the object name and text of all packages owned by the user where the text contains the string "--%"

    Observations;

    1. there are two references to dba_source when only one is needed
    2. the object type is always "PACKAGE" so no need to be a bind variable, instead could be a string literal. In this case the first and third bind variables could instead be literals.
    3. this is written as an IN, and could instead be a join. However see point 1.
    4. there are no correlation in IN clause to correlate with the outer table

    Execution plan;

    The work in the execution plan is dominated by an index range scan of an index I_SOURCE1, which produces 4.2M rowsources;

    image

    This is later reduced by various parts of the plan to 44K rowsources;

    image

    and finally to 3496

    image

    The must be the matches that are then post processed to validate against the allowed utplsql annotations. Since there are no tests for this case, then post processing must discard all of these.

    Conclusion;
    For the first case 90% of the time is spent on this statemnent;

    select s.name, s.text
              from dba_source s
             where s.type = :a_object_type
               and s.owner = :a_object_owner
               and s.name
                in (select x.name
                      from dba_source x
                     where x.type = :a_object_type
                       and x.owner = :a_object_owner
                       and x.text like '%--%\%%' escape '\'
                   )
              order by name, line 
    

    Can this instead by re-written to be;

    select s.name, s.text
              from dba_source s
             where s.type = 'PACKAGE'
               and s.owner = :a_object_owner
               and s.text like '%--%\%%' escape '\'
              order by name, line
    

    If the original query form is required for some reason then the IN clause must be correlated with the outer table to reduce the need to full scan (only the PACKAGE entries identified from the accesses to the first table reference need to be examined).

    Note: Tee literal value for PACKAGE is acceptable since there only a small number fo possible object types. Using the literal may enable the optimizer to take advantages of histograms that may be available with bind variable peeking.

    Also, the optimizer is underestimating the rowsource s that will be identified by each step. Worth revisiting this after any initial changes.

    Cheers.

  26. mathewbutler commented on Jun 24, 2018

    @mathewbutler
    Contributor

    Analysis of second run when cache is populated;

    This takes ~1.4 seconds elapsed.

    The second run has a resource profile that looks like this;

    image

    that is 90% of time spent on CPU

    The highest CPU actions are these;

    image

    This is the first query;

    image

    This uses a second of CPU to obtain zero records, and also is doing some physical IO. I'm unclear where in the chain of processing this sits. I expect that this may be a pipelined function that delegates to the remaining SQL identified. I'm assuming this for now.

    image

    Recommendations;

    1. none for now

    The next statement (3) is this;

    image

    obtain and classify all database objects, even if these are not known to annotation cache info

    Observations;

    1. object type is a bind and could be a literal (the bind provided is 'PACKAGE')
    2. annotation info contains 44,899 references when there are no existing tests in the schema
    3. the access path to annotation cache info is via an index (UK) then via the PK that estimates only a single record will be returned. This could be because of stale database statistics. I expect that the PK includes the status.

    image

    Recommendations;

    1. is there some means to reduce the contents of the ut_annotation_cache_info table (I'm assuming that all entries in this case aren't actual tests but are because the previous query catured some false positives via;

    s.text like '%--%%%' escape ''

    Could this filter be made more restrictive so that it identifies fewer matches? e.g. we specify that annotation must start with X records of start of row, and spaces between "--" and "%" must be less than Y. As it is the execution plan needs to scan all objects in the database as below;

    image

    Other access paths might be available if there were statistics on the underlying fixed tables (x$), we could explore whether this improves things, but wouldn't recommend automating anything in utPLSL to do this. Instead there might be a note added to state this as a possible workaround. Unclear that the effort justifies the benefits yet. Clearly, and win will involve removal of the full scan of OBJ$.

    Statement 4
    obtain a count of objects with their last DDL time

    Here is statement 4;
    image

    Observations

    1. It's unclear why this is needed in the processing - again this is a full scan of OBJ$, and maybe it could be removed, or else merged with another statement that also scans OBJ$ (i.e. the previous one).
    2. There is no group by in the query - I'm not clear whether this might reduce the work. The group by is implied as I read the statement, but would be "cleaner" to include.
    3. There is only a small benefit to doing this in terms of execution time - but this is 14% of elapsed so worth consideration - especially if it's possible to combine this work with an existing statement that needs to scan OBJ$.
  27. Shoelace commented on Jul 10, 2018

    @Shoelace
    Member

    @mathewbutler in your initial cache population conclusion your 2 queries are not the same..
    your proposed query returns "source lines from packages that look like comments"
    where as the original function returns "all source lines from packages that have at least 1 line that looks like a comment"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions