github.com/voedger/voedger@v0.0.0-20240520144910-273e84102129/pkg/parser/sql_example_app/pmain/package.vsql (about)

     1  /*
     2  * Copyright (c) 2023-present unTill Pro, Ltd.
     3  */
     4  
     5  /*
     6  * Package consists of schema and resources
     7  * Schema consists of few schema files
     8  */
     9  
    10  IMPORT SCHEMA 'github.com/untillpro/untill';
    11  IMPORT SCHEMA 'github.com/untillpro/airsbp' AS air;
    12  
    13  /*
    14  * APPLICATION statement defines the application.
    15  * Package cannot contain more than one APPLICATION statement
    16  * When building Application schema from packages, exactly one package must have APPLICATION statement
    17  */
    18  APPLICATION example_app (
    19      USE air; -- name or alias. This identifies package name in QNames of the app
    20      USE untill;
    21  );
    22  
    23  
    24  -- Declare variable to use it later in the schema. Can be overriden on app deployment stage
    25  DECLARE nAntiDdosPerSecRate int32 DEFAULT 1000;
    26  
    27  
    28  /*
    29      Abstract tables can only be used for INHERITance by other tables.
    30      INHERITS includes all the fields, nested tables and constraints from an ancestor table.
    31      It is not allowed to use abstract tables for:
    32          - including into workspaces with USE statement;
    33          - declaring as nested table;
    34          - specifying in reference fields;
    35          - using in projectors;
    36          - making CUD in any workspace;
    37  */
    38  ABSTRACT TABLE NestedWithName INHERITS CRecord (
    39      /*  Field is added to any table inherited from NestedWithName
    40          The current comment is also added to scheme for this field  */
    41  
    42      ItemName varchar(50) -- Max length is 1024
    43  );
    44  
    45  /*
    46      Declare a table to use it later as nested.
    47      Note: Quotes can be optionally used with identifiers
    48  */
    49  TABLE "NestedTable" INHERITS NestedWithName (
    50      ItemDescr varchar, -- Default length is 255
    51      ItemTitle character varying(50) -- varchar and text are aliases for 'character varying'
    52  );
    53  
    54  -- Declare tag to assign it later to definition(s)
    55  TAG BackofficeTag;
    56  
    57  /*
    58      Any declared table must have one of the following tables as a root anchestor:
    59          - CDoc (Configuration)
    60          - ODoc (Operational)
    61          - WDoc (Workflow)
    62          - CSingleton (Configration singleton)
    63          - WSingleton (Workflow singleton)
    64  
    65      Nested tables must have one of the following tables as a root anchestor:
    66          - CRecord (Configuration)
    67          - ODoc (Operational)
    68          - WDoc (Workflow)
    69  */
    70  TABLE TablePlan INHERITS CDoc (
    71      FState int,
    72      TableNumber int,
    73      Name varchar NOT NULL,
    74      Rate currency NOT NULL,
    75      Expiration timestamp,
    76      VerifiableField varchar NOT NULL VERIFIABLE, -- Verifiable field
    77      Int1 int DEFAULT 1 CHECK(Int1 >= 1 AND Int2 < 10000),  -- Expressions evaluating to TRUE or UNKNOWN succeed.
    78      Text1 varchar DEFAULT 'a',
    79      BinData binary varying,
    80      BinData2 varbinary, -- "varbinary" and "bytes" are aliases for "binary varying"
    81      "bytes" bytes, -- optional quotes
    82  
    83      ScreenGroupRef ref(ScreenGroup),
    84      AnyTableRef ref,
    85      FewTablesRef ref(ScreenGroup, TablePlan) NOT NULL,
    86      CheckedField varchar(8) CHECK '^[0-9]{8}$', -- Field validated by regexp
    87      CHECK (ValidateRow(this)), -- Unnamed CHECK table constraint. Expressions evaluating to TRUE or UNKNOWN succeed.
    88      CONSTRAINT StateChecker CHECK (ValidateFState(FState)), -- Named CHECK table constraint
    89      UNIQUE (FState, Name), -- unnamed UNIQUE table constraint, core generates `main.TablePlan$uniques$01` automatically
    90      CONSTRAINT UniqueTable UNIQUE (TableNumber), -- named UNIQUE table constraint
    91      UNIQUEFIELD Name, -- deprecated. For Air backward compatibility only
    92      TableItems TABLE TablePlanItem (
    93          TableNo int,
    94          Chairs int
    95      ),
    96      items NestedTable, -- Include table declared in different place. Must be one of Record types
    97      ExcludedTableItems TablePlanItem
    98  ) WITH Comment='Backoffice Table', Tags=(BackofficeTag); -- Optional comment and tags
    99  
   100  TABLE ScreenGroup INHERITS CDoc();
   101  
   102  /*
   103      CSingletones is a configration singleton.
   104      These comments are included in the statement definition, but may be overridden with `WITH Comment=...`
   105  */
   106  TABLE SubscriptionProfile INHERITS CSingleton (
   107      CustomerID varchar,
   108      CustomerKind int,
   109      CompanyName varchar
   110  );
   111  
   112  TABLE Transaction INHERITS WSingleton (
   113      OpenDatetime timestamp,
   114      CloseDatetime timestamp
   115  );
   116  
   117  -- Package-level extensions
   118  EXTENSION ENGINE WASM (
   119  
   120      -- Function which takes sys.TableRow (unnamed param), returns boolean and implemented in WASM module in this package
   121      FUNCTION ValidateRow(TableRow) RETURNS boolean;
   122  
   123      -- Function which takes named parameter, returns boolean, and implemented in WASM module in this package
   124      FUNCTION ValidateFState(State int) RETURNS boolean;
   125  
   126  );
   127  
   128  --  Default object scope is PER APP PARTITION and no subject scope
   129  RATE AppDefaultRate 1000 PER HOUR;
   130  
   131  -- WORKSPACE statement declares the Workspace, descriptor and definitions, allowed in this workspace
   132  WORKSPACE MyWorkspace (
   133      DESCRIPTOR(                     -- Workspace descriptor is always SINGLETON
   134                                      -- If name omitted, then QName is: <WorkspaceName>+"Descriptor"
   135  
   136          air.TypeWithName,           -- Fieldset
   137          Country varchar(2) CHECK '^[A-Za-z]{2}$',
   138          Description varchar(100)
   139      );
   140  
   141      -- Definitions declared in the workspace are only available in this workspace
   142      TAG PosTag;
   143      ROLE LocationManager;
   144      ROLE LocationUser;
   145      TYPE TypeWithKind (
   146          Kind int
   147      );
   148      TYPE SubscriptionEvent (
   149          Origin varchar(20),
   150          Data varchar(20)
   151      );
   152      TYPE RestorePasswordParam (
   153          Email varchar(50)
   154      );
   155  
   156      -- To include table or workspace declared in different place of the schema, they must be USEd:
   157  	USE TABLE SubscriptionProfile;
   158      USE WORKSPACE MyWorkspace;  -- It's now possible to create MyWorkspace in MyWorkspace hierarchy
   159  
   160      -- Declare table within workspace
   161      TABLE WsTable INHERITS CDoc (
   162          air.TypeWithName,   -- Fieldset
   163  
   164          PsName varchar(15),
   165          items TABLE Child (
   166              TypeWithKind, -- Fieldset
   167              Number int
   168          )
   169      );
   170  
   171      -- Workspace-level extensions
   172      EXTENSION ENGINE BUILTIN (
   173  
   174          /*
   175          Projector can only be declared in workspace.
   176  
   177          A builtin function CountOrders must exist in package resources.
   178              ON Orders - points to a command
   179              INTENTS - lists all storage keys, projector generates intents for
   180              STATE - lists all storage keys, projector reads state from
   181                  (key consist of Storage Qname, and Entity name, when required by storage)
   182                  (no need to specify in STATE when already listed in INTENTS)
   183          */
   184          PROJECTOR CountOrders
   185              AFTER EXECUTE ON NewOrder
   186              INTENTS(View(OrdersCountView));
   187  
   188          -- Projectors triggered by CUD operation
   189          -- SYNC means that projector is synchronous
   190          SYNC PROJECTOR TablePlanThumbnailGen
   191              AFTER INSERT ON TablePlan
   192              INTENTS(View(TablePlanThumbnails));
   193  
   194          -- Projector triggered by command argument SubscriptionEvent
   195          -- Projector uses sys.HTTPStorage
   196          PROJECTOR UpdateSubscriptionProfile
   197              AFTER EXECUTE WITH PARAM ON SubscriptionEvent
   198              STATE(sys.Http, AppSecret);
   199  
   200          -- Projector triggered by few COMMANDs
   201          PROJECTOR UpdateDashboard
   202              AFTER EXECUTE ON (NewOrder, NewOrder2)
   203              STATE (Http, AppSecret)
   204              INTENTS(View(DashboardView, XZReports, NotificationsHistory, ActiveTablePlansView));
   205  
   206          -- Projector triggered by few types of CUD operations
   207          PROJECTOR UpdateActivePlans
   208              AFTER ACTIVATE OR DEACTIVATE ON TablePlan
   209              INTENTS(View(ActiveTablePlansView));
   210  
   211          /*
   212              Some projector which sends E-mails and performs HTTP queries.
   213              This one also triggered on events with errors
   214          */
   215          PROJECTOR NotifyOnChanges
   216              AFTER INSERT OR UPDATE ON (TablePlan, WsTable)
   217              STATE(Http, AppSecret)
   218              INTENTS(SendMail, View(NotificationsHistory))
   219              INCLUDING ERRORS;
   220  
   221          /*
   222          Projector on any CUD operation.
   223          CDoc, WDoc, ODoc are the only abstract tables which are allowed to use in this case
   224          */
   225          PROJECTOR RecordsRegistryProjector
   226              AFTER INSERT OR ACTIVATE OR DEACTIVATE ON (CRecord, WRecord);
   227  
   228          /*
   229          Commands can only be declared in workspaces
   230          Command can have optional argument and/or unlogged argument
   231          Command can return TYPE
   232          */
   233          COMMAND NewOrder(air.Order, UNLOGGED air.TypeWithName) RETURNS air.Order;
   234  
   235          -- Command can return void (in this case `RETURNS void` may be omitted)
   236          COMMAND NewOrder2(air.Order) STATE(AppSecret) INTENTS(Record(Transaction)) RETURNS void;
   237  
   238          COMMAND RestorePassword(RestorePasswordParam) RETURNS void;
   239  
   240          -- Command with declared Comment, Tags
   241          COMMAND NewOrder4(UNLOGGED air.Order) WITH
   242              Tags=(BackofficeTag, PosTag);
   243  
   244          -- Qieries can only be declared in workspaces
   245          QUERY Query1 RETURNS void;
   246  
   247          -- WITH Comment... overrides this comment
   248          QUERY Query11() RETURNS air.Order WITH Comment='A comment';
   249  
   250          -- Query which can return any value
   251          QUERY Query2(air.Order) STATE(AppSecret, Http) RETURNS any;
   252      );
   253  
   254      -- Object scope is PER APP PARTITION PER IP
   255      -- Use variable declared in the package
   256      RATE AntiDDosRate nAntiDdosPerSecRate PER SECOND;
   257  
   258      --  Custom scopes
   259      RATE BackofficeRate 1000 PER HOUR PER APP PARTITION;
   260      RATE QueryRate 1000 PER HOUR PER APP PARTITION PER IP;
   261      RATE CudRate 100 PER HOUR PER USER;
   262      RATE RestorePasswordRate1 3 PER 5 MINUTES PER APP PARTITION PER IP;
   263      RATE RestorePasswordRate2 10 PER DAY PER APP PARTITION PER IP;
   264  
   265  	LIMIT AntiDDOS ON EVERYTHING WITH RATE AntiDDosRate; -- all commands, queries and CUD
   266  	LIMIT RestorePasswordLimit1 ON COMMAND RestorePassword WITH RATE RestorePasswordRate1;   -- Single command applied with rate
   267  	LIMIT RestorePasswordLimit2 ON COMMAND RestorePassword WITH RATE RestorePasswordRate2;   -- Combination of two rates
   268  	LIMIT Query1Limit ON QUERY Query1 WITH RATE QueryRate; -- Single query applied with rate
   269  	LIMIT tl1 ON TABLE WsTable WITH RATE CudRate; -- CUD operations on a single table
   270  	LIMIT BackofficeLimit ON TAG BackofficeTag WITH RATE BackofficeRate; -- Limit on anything with tag
   271  
   272      -- ACLs
   273      GRANT ALL ON ALL TABLES WITH TAG BackofficeTag TO LocationManager;
   274      GRANT INSERT,UPDATE ON ALL TABLES WITH TAG PosTag TO LocationUser;
   275      GRANT SELECT ON TABLE untill.Prices TO LocationUser;
   276      GRANT SELECT(Price) ON TABLE untill.Prices TO LocationUser;
   277      GRANT INSERT ON COMMAND NewOrder TO LocationUser;
   278      GRANT SELECT ON QUERY Query1 TO LocationUser;
   279      GRANT SELECT ON ALL QUERIES WITH TAG PosTag TO main.LocationUser;
   280      GRANT INSERT ON WORKSPACE MyWorkspace TO LocationUser;
   281  
   282      -- VIEWs generated by the PROJECTOR.
   283      -- Primary Key must be declared in View.
   284      VIEW XZReports(
   285  
   286          -- Report Year
   287          Year int32,
   288  
   289          -- Report Month
   290          Month int32,
   291  
   292          -- Report Day
   293          Day int32,
   294  
   295          /*
   296              Field comment:
   297              0=X, 1=Z
   298          */
   299          Kind int32,
   300          Number int32,
   301          Description varchar(50),
   302  
   303          -- Reference to WDoc
   304          XZReportWDocID ref NOT NULL,
   305          PRIMARY KEY ((Year), Month, Day, Kind, Number)
   306      ) AS RESULT OF UpdateDashboard;
   307  
   308      VIEW OrdersCountView(
   309          Year int, -- same as int32
   310          Month int32,
   311          Day int32,
   312          Qnantity int32,
   313          SomeField int32,
   314          PRIMARY KEY ((Year), Month, Day)
   315      ) AS RESULT OF CountOrders;
   316  
   317      VIEW TablePlanThumbnails(
   318          Dummy int,
   319          Dummy2 int,
   320          PRIMARY KEY ((Dummy), Dummy2)
   321      ) AS RESULT OF TablePlanThumbnailGen;
   322  
   323      VIEW DashboardView(
   324          Dummy int,
   325          SomeRec record,
   326          Dummy2 int,
   327          PRIMARY KEY ((Dummy), Dummy2)
   328      ) AS RESULT OF UpdateDashboard;
   329      VIEW NotificationsHistory(
   330          Dummy int,
   331          Dummy2 int,
   332          PRIMARY KEY ((Dummy), Dummy2)
   333      ) AS RESULT OF UpdateDashboard;
   334      VIEW ActiveTablePlansView(
   335          Dummy int,
   336          Dummy2 int,
   337          PRIMARY KEY ((Dummy), Dummy2)
   338      ) AS RESULT OF UpdateDashboard;
   339  
   340  );
   341  
   342  /*
   343      Abstract workspaces:
   344          - Cannot be created
   345          - Cannot declare DESCRIPTOR
   346          - Cannot be USEd in other workspaces
   347          - Can only be used by other workspaces for INHERITance
   348  */
   349  ABSTRACT WORKSPACE AWorkspace ();
   350  
   351  /*
   352      INHERITS includes everything which is declared and/or USEd by other workspace.
   353      Possible to inherit from multiple workspaces
   354  */
   355  WORKSPACE MyWorkspace1 INHERITS AWorkspace, untill.UntillAWorkspace (
   356      POOL OF WORKSPACE MyPool ();
   357  );
   358  
   359  /*
   360      Allow my statements to be used in sys.Profile.
   361      sys.Profile workspace is declared as ALTERABLE, this allows other packages to extend it with ALTER WORKSPACE.
   362      We can also ALTER non-alterable workspaces when they are in the same package
   363  */
   364  ALTER WORKSPACE sys.Profile(
   365      USE TABLE TablePlan;
   366      USE WORKSPACE MyWorkspace1;
   367  );
   368  
   369  -- Declares ROLE
   370  ROLE UntillPaymentsUser;