MSBA-348 · Lesson 4 of 12 · 20 min
Domain review: X++ and data model
▶ Video coming soon A video version of this lesson is on the way.
This lesson covers the data model half of Design and develop AOT elements (10 to 15 percent) and the first objective group of Develop and test code (20 to 25 percent), which is about the X++ language itself: constructs, CRUD, transactions, global functions, best practice warnings and extensibility. Lesson 5 covers the user interface elements and the object-oriented, framework and testing objectives. Together the two lessons review the largest share of the exam.
Desmond ran this clinic around the pump warranty table that Prudence had built in October. "Every question in this part of the outline," he said, "is a question about CRPumpWarrantyTable in disguise. Where does the data live, how do you read and write it safely, and what is the right element to expose it?"
The data model: five kinds of element
The outline asks you to create and extend tables; create and extend views, queries and maps; create and extend data entities; and differentiate between all five. The fifth skill is the one most often tested, because the five look similar in Application Explorer and each has a distinct job.
| Element | What it is | Stores data? | Typical use |
|---|---|---|---|
| Table | A database table with fields, indexes, relations and methods | Yes | CRPumpWarrantyTable, CustTable |
| View | A read-only database view defined by a query, optionally with computed columns | No (database view) | A flattened read model for a form, report or entity |
| Query | A reusable AOT definition of data sources, joins, ranges and sorting | No | Data source for a form, a report, a view or a batch job; user-adjustable criteria |
| Map | A mapping of shared field and method names onto several tables | No | Code that works the same way on CustTable and VendTable through one map |
| Data entity | An abstraction over one or more tables, with a public name, a staging table and support for import, export, OData and integration | No (a view plus logic) | CRPumpWarrantyEntity for the distributor portal and data migration |
Exam questions that test the difference usually include one decisive requirement. "Must be available to an external system through OData" points to a data entity with IsPublic set. "Must be importable with data management, with a staging step" also points to an entity. "A read-only combination of three tables for a list page, without new storage" points to a view or a query. "Logic that must work for both customers and vendors without duplication" points to a map. "Store a new kind of record" is a table, and "add a field to a standard table" is a table extension.
Tables and table extensions
A table's design work is mostly properties: the primary index and the clustered index, the table group (Main, Transaction, Parameter, Group and so on), the cache lookup setting, the title fields, the TableType (regular, TempDB or InMemory), the configuration key, the save data per company setting and field groups such as AutoReport and AutoLookup. Fields are best based on extended data types, so that labels, sizes and lookups are inherited. Relations define foreign keys and give lookups and joins their meaning. Delete actions decide what happens to related records when a record is deleted: Cascade, Restricted or Cascade plus Restricted.
A table extension adds fields, field groups, indexes, relations, delete actions and some property changes to a standard table without changing it. You cannot remove standard fields, change their type or change the standard primary index. Extension names follow a pattern such as PurchLine.CRCustom, and new fields should carry your prefix to avoid collisions with other extensions. Methods on a standard table are extended with Chain of Command in a class, not in the table extension itself; lesson 5 reviews that.
Views, queries and maps
A query is an AOT element that describes data sources, joins, ranges, sort order and grouping. Queries are reused by forms, reports, views, entities and batch jobs, and can be extended to add ranges or data sources. In code, the same idea is built with the Query, QueryBuildDataSource and QueryBuildRange classes, which is the subject of the framework objective in lesson 5.
A view turns a query or a set of data sources into a database view. Views are read-only. They can have computed columns, which are fields whose value is a SQL expression produced by a static method at synchronization time; these are evaluated in the database, so they can be filtered and sorted efficiently. Views are useful as data sources for entities, reports and Power BI because the database does the joining.
A map lists field names and methods that several tables share and maps each to the corresponding field in each table. Code written against the map works on any mapped table. Maps were more common in older code, but you will still meet them in standard code, and the exam asks you to recognize them. A special case is the extension table pattern served by the SysExtensionSerializer maps, which lesson 5 reviews under frameworks.
Data entities
A data entity gives one or more tables a public, denormalized shape. Its properties include the public entity name and public collection name used by OData, IsPublic, the data management settings, the staging table and the entity key, which should be a natural key such as SerialNumber rather than RecId. Entities can have computed fields, calculated in SQL through a static method like a view's computed column, and unmapped virtual fields, calculated in X++ at run time, typically in postLoad on export and mapEntityToDataSource on import. Virtual fields cannot be filtered efficiently because the database knows nothing about them.
Entities are extended like tables: you can add fields from the underlying data sources, add data sources and add computed or virtual fields, all in an entity extension. In the integration clinics Prudence built CRPumpWarrantyEntity with SerialNumber as its key, EndDate as a read-only field and a validation that a pump must have been shipped to the customer. The exam's entity questions are reviewed again in lesson 6, because entities sit at the centre of integration.
X++ constructs and CRUD
The first code objective group begins with common structured programming constructs: variables and extended data types, if and switch, while, do while and for loops, containers, strings and dates, and the ternary operator. Questions rarely test syntax for its own sake; they test what a snippet does, which is why lesson 8 is devoted to reading code. Then comes CRUD: creating, reading, updating and deleting data. Reading uses select statements with keywords that change behaviour.
| Keyword | Effect | Exam signal |
|---|---|---|
| firstonly | Fetch at most one record | You need one record, such as a parameter or a lookup |
| forupdate | Select records so they can be updated in a transaction | An update without it fails |
| crosscompany | Read across legal entities (optionally a container of company IDs) | Report or job spanning CRCA, CRUS and CRMX |
| exists join | Return records that have a match, without fields from the joined table | Filter, not enrich |
| notexists join | Return records that have no match | Find warranties without an invoice |
| outer join | Return all records from the first table, with joined fields when they exist | Enrich optionally |
| order by, group by, sum, count | Sorting and aggregation in the database | Totals without a loop |
| validTimeState | Read date-effective data as of a date or range | Tables with ValidFrom and ValidTo |
CRPumpWarrantyTable warranty;
CustTable customer;
// Mining customers with at least one active warranty, read across companies
while select crosscompany AccountNum, CustGroup from customer
where customer.CustGroup == 'MINING'
exists join warranty
where warranty.CustAccount == customer.AccountNum
&& warranty.Status == CRWarrantyStatus::Active
{
info(strFmt('%1 (%2)', customer.AccountNum, customer.DataAreaId));
}Writing data uses table methods. insert, update and delete call the table's overridable methods and the framework events. doInsert, doUpdate and doDelete skip the overridden methods and should be avoided except in special cases. validateWrite and validateDelete are called by forms before saving or deleting, and code that writes data outside a form should call them explicitly when the rules must apply. initValue sets defaults on a new record. Updates require the record to be selected forupdate inside a transaction.
Transactions and exceptions
The objective says implement transaction scope, including by using exception handling. ttsbegin starts a transaction and ttscommit commits it; nested pairs increase and decrease the transaction level, and only the outermost ttscommit commits. ttsabort rolls back. An exception thrown inside a transaction rolls back the whole transaction to the outermost level. A catch block inside the transaction is skipped and the exception is caught outside the outermost ttscommit, with two important exceptions: UpdateConflict and DuplicateKeyException can be caught inside a transaction so that code can retry, and the standard pattern checks the transaction level before retrying.
#OCCRetryCount
try
{
ttsbegin;
CRPumpWarrantyTable warranty = CRPumpWarrantyTable::findBySerial(serial, true);
warranty.Status = CRWarrantyStatus::Void;
warranty.update();
ttscommit;
}
catch (Exception::Deadlock)
{
retry;
}
catch (Exception::UpdateConflict)
{
if (appl.ttsLevel() == 0)
{
if (xSession::currentRetryCount() >= #RetryNum)
{
throw Exception::UpdateConflictNotRecovered;
}
retry;
}
throw Exception::UpdateConflict;
}Other exception facts that appear in questions: throw error("...") writes to the Infolog and throws Exception::Error; info, warning and error only write messages; checkFailed writes a warning and returns false, which makes it the usual return in validate methods; a finally block runs whether or not an exception occurred; and .NET exceptions are caught with Exception::CLRError or with a typed catch of a System.Exception variable.
Global functions
X++ provides global functions that are available everywhere without an object. You met many in the fundamentals course: strFmt, strLen, subStr, num2Str, date2Str, today, mkDate, dayOfMth, mthOfYr, year, prevMth, nextMth, dateMthFwd, conPeek, conLen, conIns, tableNum, fieldNum, classStr, tableStr, fieldStr, methodStr and formStr, and curExt for the current company. The intrinsic functions such as tableStr and methodStr are checked by the compiler, so a misspelled table name fails at build time instead of at run time. The objective also covers creating your own global helpers, which in modern code is done with static methods on a class, because the Global class can be extended but adding methods there is discouraged.
Worked problem
The end date bug, revisited
In X++ Development Fundamentals, the first version of the warranty end date was one day early. The code was dateMthFwd(installDate, months) - 1. Cobalt Ridge's rule is that a warranty ends on the anniversary of installation. For an installation on February 29, 2024 with 12 months, what does the fixed rule return, and why does the exam care?
Show solution
- dateMthFwd moves a date forward by whole months and adjusts to the last day of the month when the day does not exist.
- February 29, 2024 plus 12 months gives February 28, 2025, because 2025 has no February 29.
- The fixed rule removes the minus one, so the end date is February 28, 2025.
- The exam asks this kind of question to test whether you know a global function's behaviour at a boundary, not whether you can do date arithmetic.
Answer: February 28, 2025. The Feb 29 test case in the SysTest suite exists to catch exactly this boundary.
Best practice warnings and extensibility
The compiler and the best practice checker produce warnings for issues such as missing labels on user-visible properties, fields not based on extended data types, missing indexes on relations, unused variables, select statements without an index, missing field groups and code that bypasses validation. Resolving best practice warnings usually means fixing the cause, such as adding a label or an EDT. Suppressing a rule is possible with an attribute or a suppression file, but should be rare and justified. Pipelines can be set to fail on new warnings.
The final skill in the group asks you to assess the extensibility of code and apply design patterns. Before you plan an extension, check whether the standard code offers a hook: a public or protected method you can wrap with Chain of Command, a delegate you can subscribe to, a replaceable method, an extensible enum or a class factory based on the SysExtension framework. Methods marked as Hookable false or Wrappable false cannot be wrapped; and private methods cannot be wrapped. When no hook exists, the right action is an extensibility request to Microsoft, which is what Desmond filed for the receipt check in the extension clinics. Patterns the exam names include the factory with SysExtension attributes, the singleton, the strategy pattern via abstract classes and subclasses, and the data contract pattern used by SysOperation.
How the exam asks about the data model
Questions in this part of the outline are rarely definitions. They describe a requirement and ask which element to create or which property to set. A requirement to show customer name and credit limit beside each warranty on a list page, without storing them twice, points to a join in the form's data sources or a view, never to new fields on the warranty table. A requirement that a field must grow when a standard field grows points to basing it on the same extended data type. A requirement that deleting a customer must be blocked while warranties exist points to a Restricted delete action on the relation, not to code in the customer's delete method.
Desmond made Prudence answer each scenario in two sentences: the element, then the reason that rules out the nearest alternative. "A view, because nothing is written; not an entity, because no external system needs it." The second sentence is what the exam is really testing, because the wrong options are usually the nearest alternatives. By the end of the clinic she could do it for twenty scenarios in fifteen minutes, which is about the pace the exam needs.
Common mistakes
MistakeChoosing a view because an external system must write data through it.
InsteadViews are read-only; use a data entity for import and OData writes.
MistakeCalling doUpdate to save a record so that validation does not slow it down.
InsteadUse update so overridden logic and events run; doUpdate is for rare special cases.
MistakeRetrying an UpdateConflict inside a nested transaction.
InsteadRetry only when the transaction level is zero; otherwise rethrow.
MistakeUsing an outer join to filter records that have a match.
InsteadUse an exists join to filter without fields; outer join returns everything.
MistakeAdding a method to a table extension element to change a standard table method.
InsteadWrap the method with Chain of Command in an extension class.
Summary and key terms
- Only tables store data; views are read-only database views, queries are reusable definitions, maps share field names across tables and data entities expose public shapes for integration.
- Table extensions add fields, indexes, relations and field groups; methods are extended through Chain of Command classes.
- Select keywords such as firstonly, forupdate, crosscompany, exists join and notexists join decide what a statement returns.
- Exceptions inside a transaction roll back to the outermost level; only UpdateConflict and DuplicateKeyException can be caught inside, and retry only at level zero.
- Fix best practice warnings at the cause, and assess hooks before extending; file an extensibility request when none exists.
- Computed column
- A view or entity field calculated by a SQL expression generated from a static method.
- Virtual field
- An entity field calculated in X++ at run time, not stored or filterable in the database.
- Exists join
- A join that filters the first table by the presence of a match without returning joined fields.
- ttsLevel
- The current transaction nesting depth; zero means no open transaction.
- Map
- An element that maps common field names and methods onto several tables.
- Extensibility request
- A request to Microsoft to add a hook where standard code cannot yet be extended.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Which element stores data: a view, a map or a table?
Show answer
A table.
Which two exceptions can be caught inside a transaction?
Show answer
UpdateConflict and DuplicateKeyException.
Why can a virtual entity field not be filtered efficiently?
Show answer
It is calculated in X++ at run time, so the database cannot filter on it.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.