Skip to content

3. Replace SAP CAP with Atscript DB ​

The same page at the same URLs as step 2, with no SAP® CAP behind them. The books, authors and genres become tables of your own in SQLite, through Atscript DB, served by Moost controllers. SAP CAP's rule and action become controller code, and no @sap/* package is left.

text
 step 2:  browser ──► /api/catalog/Books ──► ODataTableController ──► SAP CAP ──► database
 step 3:  browser ──► /api/catalog/Books ──► AsDbController ───────────────────► SQLite

The code: 3_atscript_full.

What moves together ​

The example moves all three sets at once. In a bigger app you can move a group at a time, and leave the rest on SAP CAP behind the step 2 server:

  • Related sets move together. A relation can't cross from Atscript DB to an entity set still on SAP CAP (Limitations).
  • Pickers follow the type. When a value help's type moves, point the value helps that name it at your new type, in annotate blocks (Your own models next to OData sets).
  • Operations are rewritten as controller code (below).
  • You copy the data (below).

Running the Atscript DB app ​

bash
cd 3_atscript_full
pnpm db:sync   # creates the tables in ./bookshop.db (asc db sync)
pnpm seed      # loads db/data/*.csv, SAP CAP's seed data
pnpm dev       # Vite on :5173, running the page and the Moost server
pnpm build && pnpm start   # the built server on :3000

Turning the generated types into tables of your own ​

You don't write the model from scratch. Step 2's generated catalog.as already has the keys, labels, lengths, precision, required fields, ranges, dictionary labels, descriptions, value helps, relations and the action's parameters. Copy it and change a few lines:

bash
cp 2_atscript_moost/src/generated/catalog.as 3_atscript_full/src/models/bookshop.as

In bookshop.as, each changed line says what it was (// was: …): of the copy's 104 lines of code, 12 went and 15 came, in six groups. They follow; the step's README has the whole diff.

Dropping the OData service's space ​

diff
 @db.table 'Books'
-@db.space 'catalog'
+// was: @db.space 'catalog'
 @meta.label 'Book'

The same on Authors and Genres. @db.space 'catalog' named step 2's OData service; without it, the tables join Atscript DB's default space.

Audit fields that Atscript DB fills ​

diff
     @meta.readonly
-    @db.default.store
-    createdAt?: string.isoDate
+    // was: @db.default.store
+    @ui.form.hidden // was: nothing (a UI hint: the form leaves the four audit fields out)
+    createdAt?: number.timestamp.created // was: string.isoDate

The same for modifiedAt (number.timestamp.updated), and @db.default.store goes from createdBy and modifiedBy too. It meant "the service fills it". Now Atscript DB sets the times by their types, and nothing fills the users, since nobody signs in (onWrite).

An integer version instead of SAP CAP's ETag ​

diff
     @db.column.version
-    @db.column.version.token
-    __etag: string
+    // was: @db.column.version.token
+    version: number.int // was: __etag: string

Atscript DB counts the writes, and the form still refuses to save over someone else's change (versioning).

Defaults that the database fills ​

diff
     @meta.default '0'
+    @db.default 0 // was: nothing (the service filled its DefaultValue)
     @expect.min 0

And @db.default 'EUR' on currency. @meta.default stays, so the form still starts with it (defaults).

A full-text index for the search box ​

diff
     @expect.maxLength 111
     @ui.dict.label
+    @db.index.fulltext // was: nothing (SAP CAP answered OData's $search; the search box searches this index now)
+    @ui.table.width '28ch' // was: nothing (a UI hint)
     title: string

The search box sends $search. Atscript DB looks the words up in this index, which asc db sync creates in SQLite (FTS5) and SQLite keeps up to date on every write. The books' /meta says they can be searched, and the search box shows.

The box finds less than SAP CAP's did. SAP CAP's $search matched part of a word, in any case, across the book's text fields and the author's name: Emm found Emma, and austen found Austen's three books. A full-text index matches words, and only in the fields it holds:

  • On SQLite, as the example has it, the box finds whole words of the title, in any case, best match first: emma and Pride and find their books. Emm finds nothing unless you type Emm*: a trailing * matches the start of a word, and the box doesn't add one. austen finds nothing, because author names aren't in the index; the Author filter finds an author's books. Words aren't stemmed either (prejudices misses Prejudice): @db.index.fulltext.language "english" on the table turns that on.
  • For part of a word on SQLite, its built-in trigram tokenizer finds it from three characters on (Emm finds Emma), without stemming: give the index a language and map that language to it, createAdapter(file, { ftsTokenizers: { english: "trigram" } }) (tokenizers). It's SQLite only, and the example doesn't use it.
  • PostgreSQL, MySQL and MongoDB match words their own way too: PostgreSQL and MongoDB stem English words and skip stop words by default, MySQL skips stop words and words under three letters, and MongoDB's Atlas Search, an index of its own, can match the start of a word. The details for each database: full-text search.

UI hints that now live in the model ​

diff
     @db.column.precision 9, 2
+    @expect.message 'Enter a price' // was: nothing (a UI hint: a missing price in plain words)
     price: decimal

Steps 1 and 2 keep their UI hints in catalog.ui.as, next to a generated file they can't edit. This file is yours, so the hints sit in it: the form leaves out the key and the audit fields, the widths of the title and the names, the author picker's single column, and the message for a missing price. Step 3 has no catalog.ui.as.

What stays as generated in the copy ​

Everything else: keys, labels, lengths, precision, required fields, ranges, relations, BooksRestockParams, and the value helps, which now name the tables of this file. The descriptions of createdBy and modifiedBy stay (@meta.description "User's unique ID", from SAP CAP's User type). So do the dictionary labels (@ui.dict.label): on the names, from SAP CAP's author.name and genre.name, so the page still shows names for the codes; and on title, from ID @Common.Text: title, so the Restock dialog still names a book by its title, then its key. Keep the field names: screens, saved table presets and filters refer to them.

What else your own copy may need ​

Changes the bookshop didn't need
  • @db.rel.store navigations have no foreign key in the $metadata: turn them into foreign-key relations (relations).
  • @odata.* lines, such as @odata.valueHelpService: remove them. Only the OData hosts read them.
  • What the $metadata doesn't carry: other @assert.* checks, @assert.unique, the bounds in the trailer. Add them as annotations or controller rules; the concept map pairs them.
  • Another database or several: name a space of your own instead of the default one.

Creating the SQLite tables with asc db sync ​

atscript.config.ts has no OData plugin now. db says where the tables go:

ts
db: { adapter: "@atscript/db-sqlite", connection: () => process.env.DB_FILE ?? "./bookshop.db" },

pnpm db:sync runs asc db sync, which creates the tables and later applies what changed (--dry-run to preview, --safe to skip destructive steps). It takes the place of cds deploy (schema sync). The server opens the same file in src/server/db.ts:

ts
export const db = createAdapter(process.env.DB_FILE ?? "./bookshop.db");
provideDbSpace(db); // the controllers find their tables here: the types name no @db.space now

PostgreSQL, MySQL and MongoDB work the same way, with another adapter (setup).

Some sets still on SAP CAP

Keep the OData plugin for them, and keep their generated files out of sync:

ts
db: { adapter: "@atscript/db-postgres", connection: process.env.DATABASE_URL!, exclude: ["src/generated/**"] },

One Moost app then serves both: OData controllers for the sets on SAP CAP, Atscript DB controllers for the moved ones.

Moving the data ​

Nothing moves the rows for you. The example fills empty tables in one of two ways:

  • pnpm seed loads SAP CAP's db/data/*.csv, as cds deploy did (scripts/seed.ts). Parents go first:

    ts
    await db.getTable(Genres).insertMany(csv("Genres", Genres) as Genres[]);
    await db.getTable(Authors).insertMany(csv("Authors", Authors) as Authors[]);
    await db.getTable(Books).insertMany(csv("Books", Books) as Books[]);
  • pnpm copy-from-cap copies the rows of a running SAP CAP service, step 2's by default, as OData JSON (scripts/copy-from-cap.ts). It's a one-off copy for this example, not a migration tool.

Using the database SAP CAP already uses ​

With PostgreSQL or SQLite, you can keep SAP CAP's database. Name the tables and columns as SAP CAP did with @db.table and @db.column: the qualified entity name with underscores (my_bookshop_Books), and <association>_<key> for a foreign key (author_ID). Then check with asc db sync --dry-run that the plan changes nothing you don't want changed.

The controllers at the same URLs ​

src/server/controllers.ts has one controller per table, at step 2's paths:

ts
/** Books, read and written. The page reads the names for the author and genre codes from Authors and Genres, whose
 *  names bookshop.as marks as their dictionary labels (`@ui.dict.label`). */
@TableController(Books, "api/catalog/Books")
export class BooksController extends AsDbController<typeof Books> {
  // … onWrite, checkWrite and restock: below
}

/** Authors: read-only, as SAP CAP's @readonly made them. */
@ReadableController(Authors, "api/catalog/Authors")
export class AuthorsController extends AsDbReadableController<typeof Authors> {}
// … Genres the same way: the genre picker's list

src/server/main.ts has no SAP CAP to wait for. The page is step 2's, file for file, and the server's /meta now describes Atscript DB tables (Moost DB controllers).

Moving SAP CAP's handlers and actions into the controllers ​

The rule "one title per author" in checkWrite ​

js
this.before(["CREATE", "UPDATE"], Books, async (req) => {
  const book =
    req.event === "UPDATE" ? { ...(await SELECT.one.from(req.subject)), ...req.data } : req.data;
  if (!book.author_ID) return;
  const twin = await SELECT.one
    .from(Books)
    .columns("ID")
    .where({ author_ID: book.author_ID, title: book.title });
  if (twin && twin.ID !== book.ID)
    req.error(400, "This author already has a book with this title", "title");
});
ts
protected override async checkWrite(ctx: TDbWriteCheckContext) {
  const books = await this.table.findMany({ filter: { $or: [...ctx.filters] }, controls: { $select: ["author_ID", "title"] } });
  for (const { author_ID, title } of books) {
    if (author_ID && (await ctx.count({ author_ID, title })) > 1) {
      throw new ValidatorError([{ path: "title", message: "This author already has a book with this title" }]);
    }
  }
}

checkWrite runs after the write, inside its transaction, on the books as stored: an update that sends the title alone is checked too. A refusal rolls back, and the form shows the message under the title (checkWrite).

SAP CAP's managed aspect in onWrite ​

SAP CAP ignored audit fields a client sent; onWrite drops them too:

ts
protected override onWrite(_action: TDbWriteAction, data: unknown) {
  const strip = ({ createdAt, createdBy, modifiedAt, modifiedBy, ...book }: Record<string, unknown>) => book;
  return Array.isArray(data) ? data.map(strip) : strip(data as Record<string, unknown>);
}

With users, fill createdBy and modifiedBy here (onWrite).

Restock as a db action of your own ​

The bound action becomes a db action, with BooksRestockParams from the copy as its form:

ts
@Post("actions/restock")
@DbAction<typeof Books, ["stock"]>("restock", { label: "Restock", requiredFields: ["stock"] })
async restock(
  @DbActionRows() rows: (Pick<Books, "ID" | "stock"> | undefined)[],
  @InputForm(BooksRestockParams) params: BooksRestockParams,
) {
  const books = rows.map((row) => {
    if (!row) throw notFoundError();
    const stock = (row.stock ?? 0) + params.quantity;
    if (stock > 9999) throw new HttpError(400, "Stock can't go above 9999");
    return { ID: row.ID, stock };
  });
  for (const book of books) await this.table.updateOne(book);
}

Like SAP CAP's handler, it answers 404 for a deleted book and refuses a stock past 9999, checking every book before changing any. The page shows the same Restock button, and its dialog names the book by its title: Emma (b7e2d4a0-…) (actions).

Where the other SAP CAP handlers go ​

SAP CAPMoost DB
before('CREATE' | 'UPDATE', …) on the bodyonWrite(action, data): change the body, or return an HttpError to refuse
a rule over the stored rowscheckWrite(ctx): after the write, inside its transaction
checks before the write, in the transactionguardWrite(ctx)
before('READ', …) restricting rowstransformFilter(filter)
actions and functionsdb actions (@DbAction) or endpoints of your own
@requires, @restrictAooth: @ArbacResource, @ArbacAction

Moost DB customization lists every hook.

Dropping the SAP CAP runtime ​

Step 3 has no .cds files, no srv/, no src/generated/, and no @sap/* package; only db/data/*.csv stays, for the seed. In your app, when the last set has moved:

  • [ ] Every screen reads an Atscript DB endpoint, and the OData plugin config and generated files are gone.
  • [ ] Nothing else needs the OData API. Atscript DB serves its own REST protocol, so an SAP Fiori® elements app or an SAP S/4HANA® integration that reads the service needs an OData service of its own.
  • [ ] Sign-in has a new home, with Aooth or the Moost auth of your choice. The example has none, so createdBy and modifiedBy stay empty.
  • [ ] Deployment runs asc db sync instead of cds deploy.
  • [ ] @sap/cds, its plugins, the .cds files and the SAP CAP build steps are removed.

See also ​

SAP, SAP S/4HANA, SAP Fiori, SAPUI5, SAP BTP and other SAP products and services mentioned herein, as well as their respective logos, are trademarks or registered trademarks of SAP SE (or an SAP affiliate company) in Germany and other countries. Atscript OData is an independent open-source project and is not affiliated with, sponsored or endorsed by SAP SE.
Released under the MIT License.