Compare commits

..

1 Commits

Author SHA1 Message Date
Weinstock
a5acea58f2 Play with db constraints 2021-04-14 19:38:38 +02:00
38 changed files with 324 additions and 353 deletions

View File

@@ -5,7 +5,7 @@ const app = express()
const { PORT=4444 } = process.env const { PORT=4444 } = process.env
const [,,port=PORT] = process.argv const [,,port=PORT] = process.argv
const cwd = __dirname process.chdir(__dirname)
app.use('/-/:tarball', (req,res,next) => { app.use('/-/:tarball', (req,res,next) => {
console.debug ('GET', req.params) console.debug ('GET', req.params)
@@ -13,7 +13,7 @@ app.use('/-/:tarball', (req,res,next) => {
const { tarball } = req.params const { tarball } = req.params
const [, pkg ] = /^capire-(\w+)/.exec(tarball) const [, pkg ] = /^capire-(\w+)/.exec(tarball)
fs.lstat(tarball,(err => { fs.lstat(tarball,(err => {
if (err) exec(`npm pack ../${pkg}`,{cwd},next) if (err) exec(`npm pack ../${pkg}`,next)
else next() else next()
})) }))
} catch (e) { } catch (e) {

View File

@@ -13,5 +13,5 @@
"**/cds/lib/req/cls.js", "**/cds/lib/req/cls.js",
"**/odata-v4/okra/**" "**/odata-v4/okra/**"
] ]
} },
} }

View File

@@ -35,7 +35,7 @@ const books = new Vue ({
try { try {
const res = await POST(`/submitOrder`, { amount, book: book.ID }) const res = await POST(`/submitOrder`, { amount, book: book.ID })
book.stock = res.data.stock book.stock = res.data.stock
books.order = { amount, succeeded: `Successfully ordered ${amount} item(s).` } books.order = { amount, succeeded: `Successfully orderd ${amount} item(s).` }
} catch (e) { } catch (e) {
books.order = { amount, failed: e.response.data.error.message } books.order = { amount, failed: e.response.data.error.message }
} }

View File

@@ -1,5 +1,5 @@
ID;name;dateOfBirth;placeOfBirth;dateOfDeath;placeOfDeath ID;name
101;Emily Brontë;1818-07-30;Thornton, Yorkshire;1848-12-19;Haworth, Yorkshire 101;Emily Brontë
107;Charlotte Brontë;1818-04-21;Thornton, Yorkshire;1855-03-31;Haworth, Yorkshire 107;Charlotte Brontë
150;Edgar Allen Poe;1809-01-19;Boston, Massachusetts;1849-10-07;Baltimore, Maryland 150;Edgar Allen Poe
170;Richard Carpenter;1929-08-14;Kings Lynn, Norfolk;2012-02-26;Hertfordshire, England 170;Richard Carpenter
1 ID name dateOfBirth placeOfBirth dateOfDeath placeOfDeath
2 101 Emily Brontë 1818-07-30 Thornton, Yorkshire 1848-12-19 Haworth, Yorkshire
3 107 Charlotte Brontë 1818-04-21 Thornton, Yorkshire 1855-03-31 Haworth, Yorkshire
4 150 Edgar Allen Poe 1809-01-19 Boston, Massachusetts 1849-10-07 Baltimore, Maryland
5 170 Richard Carpenter 1929-08-14 King’s Lynn, Norfolk 2012-02-26 Hertfordshire, England

View File

@@ -1,6 +1,6 @@
ID;title;descr;author_ID;stock;price;currency_code;genre_ID ID;title;author_ID;genre_ID
201;Wuthering Heights;"Wuthering Heights, Emily Brontë's only novel, was published in 1847 under the pseudonym ""Ellis Bell"". It was written between October 1845 and June 1846. Wuthering Heights and Anne Brontë's Agnes Grey were accepted by publisher Thomas Newby before the success of their sister Charlotte's novel Jane Eyre. After Emily's death, Charlotte edited the manuscript of Wuthering Heights and arranged for the edited version to be published as a posthumous second edition in 1850.";101;12;11.11;GBP;11 201;Wuthering Heights;101;11
207;Jane Eyre;"Jane Eyre /ɛər/ (originally published as Jane Eyre: An Autobiography) is a novel by English writer Charlotte Brontë, published under the pen name ""Currer Bell"", on 16 October 1847, by Smith, Elder & Co. of London. The first American edition was published the following year by Harper & Brothers of New York. Primarily a bildungsroman, Jane Eyre follows the experiences of its eponymous heroine, including her growth to adulthood and her love for Mr. Rochester, the brooding master of Thornfield Hall. The novel revolutionised prose fiction in that the focus on Jane's moral and spiritual development is told through an intimate, first-person narrative, where actions and events are coloured by a psychological intensity. The book contains elements of social criticism, with a strong sense of Christian morality at its core and is considered by many to be ahead of its time because of Jane's individualistic character and how the novel approaches the topics of class, sexuality, religion and feminism.";107;11;12.34;GBP;11 207;Jane Eyre;107;11
251;The Raven;"""The Raven"" is a narrative poem by American writer Edgar Allan Poe. First published in January 1845, the poem is often noted for its musicality, stylized language, and supernatural atmosphere. It tells of a talking raven's mysterious visit to a distraught lover, tracing the man's slow fall into madness. The lover, often identified as being a student, is lamenting the loss of his love, Lenore. Sitting on a bust of Pallas, the raven seems to further distress the protagonist with its constant repetition of the word ""Nevermore"". The poem makes use of folk, mythological, religious, and classical references.";150;333;13.13;USD;16 251;The Raven;150;16
252;Eleonora;"""Eleonora"" is a short story by Edgar Allan Poe, first published in 1842 in Philadelphia in the literary annual The Gift. It is often regarded as somewhat autobiographical and has a relatively ""happy"" ending.";150;555;14;USD;16 252;Eleonora;150;16
271;Catweazle;Catweazle is a British fantasy television series, starring Geoffrey Bayldon in the title role, and created by Richard Carpenter for London Weekend Television. The first series, produced and directed by Quentin Lawrence, was screened in the UK on ITV in 1970. The second series, directed by David Reid and David Lane, was shown in 1971. Each series had thirteen episodes, most but not all written by Carpenter, who also published two books based on the scripts.;170;22;150;JPY;13 271;Catweazle;170;13
1 ID title descr author_ID genre_ID stock price currency_code
2 201 Wuthering Heights Wuthering Heights, Emily Brontë's only novel, was published in 1847 under the pseudonym "Ellis Bell". It was written between October 1845 and June 1846. Wuthering Heights and Anne Brontë's Agnes Grey were accepted by publisher Thomas Newby before the success of their sister Charlotte's novel Jane Eyre. After Emily's death, Charlotte edited the manuscript of Wuthering Heights and arranged for the edited version to be published as a posthumous second edition in 1850. 101 11 12 11.11 GBP
3 207 Jane Eyre Jane Eyre /ɛər/ (originally published as Jane Eyre: An Autobiography) is a novel by English writer Charlotte Brontë, published under the pen name "Currer Bell", on 16 October 1847, by Smith, Elder & Co. of London. The first American edition was published the following year by Harper & Brothers of New York. Primarily a bildungsroman, Jane Eyre follows the experiences of its eponymous heroine, including her growth to adulthood and her love for Mr. Rochester, the brooding master of Thornfield Hall. The novel revolutionised prose fiction in that the focus on Jane's moral and spiritual development is told through an intimate, first-person narrative, where actions and events are coloured by a psychological intensity. The book contains elements of social criticism, with a strong sense of Christian morality at its core and is considered by many to be ahead of its time because of Jane's individualistic character and how the novel approaches the topics of class, sexuality, religion and feminism. 107 11 11 12.34 GBP
4 251 The Raven "The Raven" is a narrative poem by American writer Edgar Allan Poe. First published in January 1845, the poem is often noted for its musicality, stylized language, and supernatural atmosphere. It tells of a talking raven's mysterious visit to a distraught lover, tracing the man's slow fall into madness. The lover, often identified as being a student, is lamenting the loss of his love, Lenore. Sitting on a bust of Pallas, the raven seems to further distress the protagonist with its constant repetition of the word "Nevermore". The poem makes use of folk, mythological, religious, and classical references. 150 16 333 13.13 USD
5 252 Eleonora "Eleonora" is a short story by Edgar Allan Poe, first published in 1842 in Philadelphia in the literary annual The Gift. It is often regarded as somewhat autobiographical and has a relatively "happy" ending. 150 16 555 14 USD
6 271 Catweazle Catweazle is a British fantasy television series, starring Geoffrey Bayldon in the title role, and created by Richard Carpenter for London Weekend Television. The first series, produced and directed by Quentin Lawrence, was screened in the UK on ITV in 1970. The second series, directed by David Reid and David Lane, was shown in 1971. Each series had thirteen episodes, most but not all written by Carpenter, who also published two books based on the scripts. 170 13 22 150 JPY

View File

@@ -1,5 +1,5 @@
ID;locale;title;descr ID;locale;title
201;de;Sturmhöhe;Sturmhöhe (Originaltitel: Wuthering Heights) ist der einzige Roman der englischen Schriftstellerin Emily Brontë (18181848). Der 1847 unter dem Pseudonym Ellis Bell veröffentlichte Roman wurde vom viktorianischen Publikum weitgehend abgelehnt, heute gilt er als ein Klassiker der britischen Romanliteratur des 19. Jahrhunderts. 201;de;Sturmhöhe
201;fr;Les Hauts de Hurlevent;Les Hauts de Hurlevent (titre original : Wuthering Heights), parfois orthographié Les Hauts de Hurle-Vent, est l'unique roman d'Emily Brontë, publié pour la première fois en 1847 sous le pseudonyme dEllis Bell. Loin d'être un récit moralisateur, Emily Brontë achève néanmoins le roman dans une atmosphère sereine, suggérant le triomphe de la paix et du Bien sur la vengeance et le Mal. 201;fr;Les Hauts de Hurlevent
207;de;Jane Eyre;Jane Eyre. Eine Autobiographie (Originaltitel: Jane Eyre. An Autobiography), erstmals erschienen im Jahr 1847 unter dem Pseudonym Currer Bell, ist der erste veröffentlichte Roman der britischen Autorin Charlotte Brontë und ein Klassiker der viktorianischen Romanliteratur des 19. Jahrhunderts. Der Roman erzählt in Form einer Ich-Erzählung die Lebensgeschichte von Jane Eyre (ausgesprochen /ˌdʒeɪn ˈɛə/), die nach einer schweren Kindheit eine Stelle als Gouvernante annimmt und sich in ihren Arbeitgeber verliebt, jedoch immer wieder um ihre Freiheit und Selbstbestimmung kämpfen muss. Als klein, dünn, blass, stets schlicht dunkel gekleidet und mit strengem Mittelscheitel beschrieben, gilt die Heldin des Romans Jane Eyre nicht zuletzt aufgrund der Kino- und Fernsehversionen der melodramatischen Romanvorlage als die bekannteste englische Gouvernante der Literaturgeschichte 207;de;Jane Eyre
252;de;Eleonora;“Eleonora” ist eine Erzählung von Edgar Allan Poe. Sie wurde 1841 erstveröffentlicht. In ihr geht es um das Paradox der Treue in der Treulosigkeit. 252;de;Eleonora
1 ID locale title descr
2 201 de Sturmhöhe Sturmhöhe (Originaltitel: Wuthering Heights) ist der einzige Roman der englischen Schriftstellerin Emily Brontë (1818–1848). Der 1847 unter dem Pseudonym Ellis Bell veröffentlichte Roman wurde vom viktorianischen Publikum weitgehend abgelehnt, heute gilt er als ein Klassiker der britischen Romanliteratur des 19. Jahrhunderts.
3 201 fr Les Hauts de Hurlevent Les Hauts de Hurlevent (titre original : Wuthering Heights), parfois orthographié Les Hauts de Hurle-Vent, est l'unique roman d'Emily Brontë, publié pour la première fois en 1847 sous le pseudonyme d’Ellis Bell. Loin d'être un récit moralisateur, Emily Brontë achève néanmoins le roman dans une atmosphère sereine, suggérant le triomphe de la paix et du Bien sur la vengeance et le Mal.
4 207 de Jane Eyre Jane Eyre. Eine Autobiographie (Originaltitel: Jane Eyre. An Autobiography), erstmals erschienen im Jahr 1847 unter dem Pseudonym Currer Bell, ist der erste veröffentlichte Roman der britischen Autorin Charlotte Brontë und ein Klassiker der viktorianischen Romanliteratur des 19. Jahrhunderts. Der Roman erzählt in Form einer Ich-Erzählung die Lebensgeschichte von Jane Eyre (ausgesprochen /ˌdʒeɪn ˈɛə/), die nach einer schweren Kindheit eine Stelle als Gouvernante annimmt und sich in ihren Arbeitgeber verliebt, jedoch immer wieder um ihre Freiheit und Selbstbestimmung kämpfen muss. Als klein, dünn, blass, stets schlicht dunkel gekleidet und mit strengem Mittelscheitel beschrieben, gilt die Heldin des Romans Jane Eyre nicht zuletzt aufgrund der Kino- und Fernsehversionen der melodramatischen Romanvorlage als die bekannteste englische Gouvernante der Literaturgeschichte
5 252 de Eleonora “Eleonora” ist eine Erzählung von Edgar Allan Poe. Sie wurde 1841 erstveröffentlicht. In ihr geht es um das Paradox der Treue in der Treulosigkeit.

View File

@@ -14,3 +14,8 @@ ID;parent_ID;name
22;21;Autobiography 22;21;Autobiography
23;20;Essay 23;20;Essay
24;20;Speech 24;20;Speech
30;;Others
31;30;Other-A
32;30;Other-A
33;30;Other-A
34;30;Other-A
1 ID parent_ID name
14 22 21 Autobiography
15 23 20 Essay
16 24 20 Speech
17 30 Others
18 31 30 Other-A
19 32 30 Other-A
20 33 30 Other-A
21 34 30 Other-A

View File

@@ -1,29 +1,19 @@
using { Currency, managed, sap } from '@sap/cds/common'; using { Currency, managed, sap } from '@sap/cds/common';
namespace sap.capire.bookshop; namespace sap.capire.bookshop;
entity Books : managed { entity Books {
key ID : Integer; key ID : Integer;
title : localized String(111); title : localized String(111);
descr : localized String(1111);
author : Association to Authors; author : Association to Authors;
genre : Association to Genres; genre : Association to Genres;
stock : Integer;
price : Decimal;
currency : Currency;
image : LargeBinary @Core.MediaType : 'image/png';
} }
entity Authors : managed { entity Authors {
key ID : Integer; key ID : Integer;
name : String(111); name : String(111);
dateOfBirth : Date;
dateOfDeath : Date;
placeOfBirth : String;
placeOfDeath : String;
books : Association to many Books on books.author = $self; books : Association to many Books on books.author = $self;
} }
/** Hierarchically organized Code List for Genres */
entity Genres : sap.common.CodeList { entity Genres : sap.common.CodeList {
key ID : Integer; key ID : Integer;
parent : Association to Genres; parent : Association to Genres;

View File

@@ -1,4 +1,3 @@
namespace sap.capire.bookshop; //> important for reflection namespace sap.capire.bookshop; //> important for reflection
using from './db/schema'; using from './db/schema';
using from './srv/cat-service';
using from './srv/admin-service'; using from './srv/admin-service';

View File

@@ -1 +0,0 @@
exports.CatalogService = require('./srv/cat-service')

View File

@@ -3,20 +3,42 @@
"version": "1.0.0", "version": "1.0.0",
"description": "A simple self-contained bookshop service.", "description": "A simple self-contained bookshop service.",
"dependencies": { "dependencies": {
"@capire/common": "*",
"@sap/cds": "^5.0.4", "@sap/cds": "^5.0.4",
"express": "^4.17.1", "express": "^4.17.1",
"passport": "0.4.1" "passport": "0.4.1",
"@sap/hana-client": "^2.7.21"
}, },
"scripts": { "scripts": {
"genres": "cds serve test/genres.cds",
"start": "cds run",
"watch": "cds watch" "watch": "cds watch"
}, },
"cds": { "cds": {
"requires": { "requires": {
"db": { "db": {
"kind": "sql" "kind": "sql",
"xxx-model": "*",
"xxx-credentials": {
"database": "localSqlite.db"
}
},
"[production]": {
"db": {
"kind": "hana",
"model": [
"db",
"srv"
]
}
}
},
"features": {
"assert_integrity": false
},
"hana": {
"deploy-format": "hdbtable"
},
"cdsc": {
"beta": {
"foreignKeyConstraints": true
} }
} }
} }

View File

@@ -1,31 +1,126 @@
# Bookshop Getting Started Sample # Foreign key constraints on DB
This stand-alone sample introduces the essential tasks in the development of CAP-based services as also covered in the [Getting Started guide in capire](https://cap.cloud.sap/docs/get-started/in-a-nutshell). As model we use a simplified version of the bookshop scenario, we work with nodejs runtime.
## Hypothetical Use Cases
1. Build a service that allows to browse _Books_ and _Authors_. ## Preparation
2. Books have assigned _Genres_, which are organized hierarchically.
3. All users may browse books without login.
4. All entries are maintained by Administrators.
5. End users may order books (the actual order mgmt being out of scope).
## Running the Sample As we want to see the effects of the database constaints, we first need to switch off the integrity checks done by the node runtime. In the `package.json`:
```json
```sh "cds": {
npm run watch ...,
"features": {
"assert_integrity": false
}
}
``` ```
## Content & Best Practices Then switch on constraint generation. In the `package.json`:
```json
"cds": {
...,
"cdsc": {
"beta": {
"foreignKeyConstraints": true
}
}
}
```
| Links to capire | Sample files / folders | ## SQLite
| --------------------------------------------------------------------------------------------------------- | ------------------------------------ |
| [Project Setup & Layouts](https://cap.cloud.sap/docs/get-started/projects#sharing-and-reusing-content) | [`./`](./) | In SQLite, FK constraints can only be specified during the creation of a table. They cannot be altered for an existing table. So here we at least don't have issues with existing data.
| [Domain Modeling with CDS](https://cap.cloud.sap/docs/guides/domain-models) | [`./db/schema.cds`](./db/schema.cds) |
| [Defining Services](https://cap.cloud.sap/docs/guides/services#defining-services) | [`./srv/*.cds`](./srv) | For SQLite, constraint checks need to be enabled by application at runtime for each db connection with the command
| [Single-purposed Services](https://cap.cloud.sap/docs/guides/services#single-purposed-services) | [`./srv/*.cds`](./srv) | ```sql
| [Providing & Consuming Providers](https://cap.cloud.sap/docs/guides/providing-services) | http://localhost:4004 | PRAGMA foreign_keys = ON;
| [Using Databases](https://cap.cloud.sap/docs/guides/databases) | [`./db/data/*.csv`](./db/data) | ```
| [Adding Custom Logic](https://cap.cloud.sap/docs/guides/service-impl) | [`./srv/*.js`](./srv) | We do this via a custom handler in `admin-service.js`.
| Adding Tests | [`./test`](./test) |
| [Sharing for Reuse](https://cap.cloud.sap/docs/guides/reuse-and-compose) | [`./index.cds`](./index.cds) | Now run the requests in `requests.http` (use `http://localhost:4004` as server URL). They behave as expected.
But the error messages are not providing any details. They say "constraint violation", but they don't say which table/constraint is violated:
```
HTTP/1.1 500 Internal Server Error
...
{
"error": {
"code": "SQLITE_CONSTRAINT",
"message": "SQLITE_CONSTRAINT: FOREIGN KEY constraint failed in: \nCOMMIT"
}
}
```
The runtime constraint checks do provide the name of the restricting association (but not the name of the entity where the association lives).
## HANA
Preparation:
* logon to cf account (e.g. trial)
* create HANA service instance: `cf create-service hanatrial hdi-shared bookshop-db`
First make the deplyoment without constraints (switch off constraint generation in `package.json`).
* Run `cds build --production`. No constraints are generated.
* Deploy db model: `cf push -f gen/db`
* Deploy nodejs app: `cf push -f gen/srv --random-route`. Take note of the app URL.
Run the requests in `request.http` (use the URL from the previous step as server URL, prepend with `https://`).
Make sure to introduce some data that violates the constraints. No errors are reported - as expected.
Now switch on constraint generation in `package.json`.
* Run `cds build --production`. The constraints are placed in separate `hdbconstraint` files in `gen\db\src\gen`. They are generated with `VALIDATED ON`.
* Re-deploy db model: `cf push -f gen/db`. It fails, as the existing data violates the constraints.
* Check logs: `cf logs bookshop-db-deployer --recent`.
```
Error: com.sap.hana.di.constraint: Could not create the database object [8250005]
at "src/gen/sap.capire.bookshop.Books_author.hdbconstraint" (1:1)
Error: com.sap.hana.di.constraint: Database error 7: : feature not supported: referential constraint violated by existing value [8201003]
at "src/gen/sap.capire.bookshop.Books_author.hdbconstraint" (1:1)
```
You can see which constraint is violated, but there is no info about the offensive entries.
Now use the requests from `request.http` to fix the entries that have been broken above.
* Re-deploy db model: `cf push -f gen/db`. It should succeed.
Again run the requests from `request.http`. This time all changes that would lead to a
constraint violation fail.
Inserting a book with non-existing author ID or changing a book's author ID to an invalid value yields
the message
```
HTTP/1.1 500 Internal Server Error
...
{
"error": {
"code": "500",
"message": "Internal Server Error"
}
}
```
When trying to delete a genre that is still referenced in a book we get
```
HTTP/1.1 462 status code 462
...
{
"error": {
"code": "462",
"message": "failed on update or delete by foreign key constraint violation: TrexColumnUpdate failed on table '21F87859727E470E94917B690908A09D:SAP_CAPIRE_BOOKSHOP_GENRES' with error: DELETE on 21F87859727E470E94917B690908A09D:SAP_CAPIRE_BOOKSHOP_GENRES(ID) failed, because 1 rows with corresponding foreign keys still exist in 21F87859727E470E94917B690908A09D:SAP_CAPIRE_BOOKSHOP_BOOKS(GENRE_ID), rc=1536"
}
}
```
Note: when using `cdsc` to generate the constraints
```
cdsc Q --beta foreignKeyConstraints -d hana -s hdi -o dbstuff db\schema.cds srv\admin-service.cds
```
there will be constraints for e.g. `sap_common_Currencies_texts`. This cannot be deplyoed, as the corresponding table is removed from `cds` via the tree-shaking mechanism. These constraints need to be removed manually before deployment.
## Todo
* Provide a way to control parameters `VALIDATED` and `ENFORCED` of the constraints (only interesting for HANA, as in SQLite changing constraints after table generation is not possible).
* Provide some tool to identify existing entries that violate constraints. We can generate a list of `SELECT` statements that find these entries, but how do we run it and show the results to the user?
* Can runtimes improve the error messages?

View File

@@ -1,5 +1,6 @@
using { sap.capire.bookshop as my } from '../db/schema'; using { sap.capire.bookshop as my } from '../db/schema';
service AdminService @(requires:'admin') { service AdminService {
entity Books as projection on my.Books; entity Books as projection on my.Books;
entity Authors as projection on my.Authors; entity Authors as projection on my.Authors;
entity Genres as projection on my.Genres;
} }

View File

@@ -1,12 +1,15 @@
// sqlite: FK constraint checks need to be enabled by application at runtime
// for each db connection
const cds = require('@sap/cds') const cds = require('@sap/cds')
module.exports = cds.service.impl (async function(){
module.exports = cds.service.impl (function(){ const db = await cds.connect.to('db')
this.before ('NEW','Authors', genid)
this.before ('NEW','Books', genid) if (db.kind === 'sqlite')
{
db.before('BEGIN', function (req) {
//console.log('--- PRAGMA foreign_keys = ON ---')
return this.dbc.run('PRAGMA foreign_keys = ON;')
}) })
/** Generate primary keys for target entity in request */
async function genid (req) {
const {ID} = await cds.tx(req).run (SELECT.one.from(req.target).columns('max(ID) as ID'))
req.data.ID = ID - ID % 100 + 100 + 1
} }
})

View File

@@ -1,16 +0,0 @@
using { sap.capire.bookshop as my } from '../db/schema';
service CatalogService @(path:'/browse') {
/** For displaying lists of Books */
@readonly entity ListOfBooks as projection on Books
excluding { descr };
/** For display in details pages */
@readonly entity Books as projection on my.Books { *,
author.name as author
} excluding { createdBy, modifiedBy };
@requires: 'authenticated-user'
action submitOrder ( book: Books:ID, amount: Integer ) returns { stock: Integer };
event OrderedBook : { book: Books:ID; amount: Integer; buyer: String };
}

View File

@@ -1,26 +0,0 @@
const cds = require('@sap/cds')
const { Books } = cds.entities ('sap.capire.bookshop')
class CatalogService extends cds.ApplicationService { init(){
// Reduce stock of ordered books if available stock suffices
this.on ('submitOrder', async req => {
const {book,amount} = req.data
let {stock} = await SELECT `stock` .from (Books,book)
if (stock >= amount) {
await UPDATE (Books,book) .with (`stock -=`, amount)
await this.emit ('OrderedBook', { book, amount, buyer:req.user.id })
return { stock }
}
else return req.error (409,`${amount} exceeds stock for book #${book}`)
})
// Add some discount for overstocked books
this.after ('READ','ListOfBooks', each => {
if (each.stock > 111) each.title += ` -- 11% discount!`
})
return super.init()
}}
module.exports = { CatalogService }

View File

@@ -1,4 +0,0 @@
using { sap.capire.bookshop as my } from '../db/schema';
service TestService {
entity Genres as projection on my.Genres;
}

View File

@@ -1,38 +0,0 @@
#################################################
#
# Genres
#
GET http://localhost:4004/test/Genres?
###
GET http://localhost:4004/test/Genres?
&$filter=parent_ID eq null&$select=name
&$expand=children($select=name)
###
POST http://localhost:4004/test/Genres?
Content-Type: application/json
{ "ID":100, "name":"Some Sample Genres...", "children":[
{ "ID":101, "name":"Cat", "children":[
{ "ID":102, "name":"Kitty", "children":[
{ "ID":103, "name":"Kitty Cat", "children":[
{ "ID":104, "name":"Aristocat" } ]},
{ "ID":105, "name":"Kitty Bat" } ]},
{ "ID":106, "name":"Catwoman", "children":[
{ "ID":107, "name":"Catalina" } ]} ]},
{ "ID":108, "name":"Catweazle" }
]}
###
GET http://localhost:4004/test/Genres(100)?
# &$expand=children
# &$expand=children($expand=children($expand=children($expand=children)))
###
DELETE http://localhost:4004/test/Genres(103)
###
DELETE http://localhost:4004/test/Genres(100)
###

View File

@@ -1,82 +1,68 @@
# running locally
@server = http://localhost:4004 @server = http://localhost:4004
@me = Authorization: Basic {{$processEnv USER}}:
# running on cf
#@server = https://bookshop-srv-....hana.ondemand.com
### get all books
GET {{server}}/admin/Books
### get all authors
GET {{server}}/admin/Authors
### get all genres
GET {{server}}/admin/Genres
### ------------------------------------------------------------------------ ### create book with wrong author ID -> should fail
# Get service info
GET {{server}}/browse
{{me}}
### ------------------------------------------------------------------------
# Get $metadata document
GET {{server}}/browse/$metadata
{{me}}
### ------------------------------------------------------------------------
# Browse Books as any user
GET {{server}}/browse/Books?
# &$select=title,stock
# &$expand=currency
# &sap-language=de
{{me}}
### ------------------------------------------------------------------------
# Fetch Authors as admin
GET {{server}}/admin/Authors?
# &$select=name,dateOfBirth,placeOfBirth
# &$expand=books($select=title;$expand=currency)
# &$filter=ID eq 101
# &sap-language=de
Authorization: Basic alice:
### ------------------------------------------------------------------------
# Create book
POST {{server}}/admin/Books POST {{server}}/admin/Books
Content-Type: application/json;IEEE754Compatible=true Content-Type: application/json
Authorization: Basic alice:
{ {
"ID": 2, "ID": 701,
"title": "Poems : Pocket Poets", "title": "XXX",
"descr": "The Everyman's Library Pocket Poets hardcover series is popular for its compact size and reasonable price which does not compromise content. Poems: Bronte contains poems that demonstrate a sensibility elemental in its force with an imaginative discipline and flexibility of the highest order. Also included are an Editor's Note and an index of first lines.", "author": { "ID": 9999 }
"author": { "ID": 101 },
"genre": { "ID": 12 },
"stock": 5,
"price": "12.05",
"currency": { "code": "USD" }
} }
### create book with correct author ID -> should work
POST {{server}}/admin/Books
Content-Type: application/json;IEEE754Compatible=true
### ------------------------------------------------------------------------ {
# Put image to books "ID": 702,
PUT {{server}}/admin/Books(2)/image "title": "Poems : Pocket Poets",
Content-Type: image/png "author": { "ID": 101 }
Authorization: Basic alice: }
data:image/png;base64,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 ### delete book
DELETE {{server}}/admin/Books(ID=701)
### change book to wrong author ID -> should fail
### ------------------------------------------------------------------------ PATCH {{server}}/admin/Books(ID=207)
# Reading image from from the server directly
GET {{server}}/browse/Books(2)/image
### ------------------------------------------------------------------------
# Submit Order as authenticated user
# (send that three times to get out-of-stock message)
POST {{server}}/browse/submitOrder
Content-Type:application/json Content-Type:application/json
{{me}}
{ "book":201, "amount":5 } {"author_ID": 9999}
### change book to correct author ID -> should work
PATCH {{server}}/admin/Books(ID=207)
Content-Type:application/json
{"author_ID": 170}
### ------------------------------------------------------------------------
# Browse Genres ### delete "leaf" genre that is used in a book -> should not work
GET {{server}}/browse/Genres? DELETE {{server}}/admin/Genres(ID=13)
# &$filter=parent_ID eq null&$select=name
# &$expand=children($select=name) ### delete "leaf" genre that is not used in a book -> should work
{{me}} DELETE {{server}}/admin/Genres(ID=14)
### delete "header" genre where leaves are used in a book -> should not work
DELETE {{server}}/admin/Genres(ID=10)
### delete "header" genre where leaves are not used in a book -> should work and delete all leaves
DELETE {{server}}/admin/Genres(ID=30)

View File

@@ -5,11 +5,9 @@ CAD;de;Kanadischer Dollar;Kanadischer Dollar
AUD;de;Australischer Dollar;Australischer Dollar AUD;de;Australischer Dollar;Australischer Dollar
GBP;de;Pfund;Britische Pfund GBP;de;Pfund;Britische Pfund
ILS;de;Schekel;Israelische Schekel ILS;de;Schekel;Israelische Schekel
JPY;de;Yen;Japanische Yen
EUR;fr;euro;de la Zone euro EUR;fr;euro;de la Zone euro
USD;fr;dollar;dollar des États-Unis USD;fr;dollar;dollar des États-Unis
CAD;fr;dollar canadien;dollar canadien CAD;fr;dollar canadien;dollar canadien
AUD;fr;dollar australien;dollar australien AUD;fr;dollar australien;dollar australien
GBP;fr;livre sterling;pound sterling GBP;fr;livre sterling;pound sterling
ILS;fr;Shekel;shekel israelien ILS;fr;Shekel;shekel israelien
JPY;fr;Yen;Yen japonais
1 code locale name descr
5 AUD de Australischer Dollar Australischer Dollar
6 GBP de Pfund Britische Pfund
7 ILS de Schekel Israelische Schekel
JPY de Yen Japanische Yen
8 EUR fr euro de la Zone euro
9 USD fr dollar dollar des États-Unis
10 CAD fr dollar canadien dollar canadien
11 AUD fr dollar australien dollar australien
12 GBP fr livre sterling pound sterling
13 ILS fr Shekel shekel israelien
JPY fr Yen Yen japonais

View File

@@ -70,7 +70,7 @@ annotate AdminService.Authors with @(
annotate sap.capire.bookshop.Books with @fiori.draft.enabled; annotate sap.capire.bookshop.Books with @fiori.draft.enabled;
annotate AdminService.Books with @odata.draft.enabled; annotate AdminService.Books with @odata.draft.enabled;
annotate AdminService.Books.texts with @( annotate AdminService.Books_texts with @(
UI: { UI: {
Identification: [{Value:title}], Identification: [{Value:title}],
SelectionFields: [ locale, title ], SelectionFields: [ locale, title ],
@@ -83,7 +83,7 @@ annotate AdminService.Books.texts with @(
); );
// Add Value Help for Locales // Add Value Help for Locales
annotate AdminService.Books.texts { annotate AdminService.Books_texts {
locale @ValueList:{entity:'Languages',type:#fixed} locale @ValueList:{entity:'Languages',type:#fixed}
} }
// In addition we need to expose Languages through AdminService // In addition we need to expose Languages through AdminService

View File

@@ -54,7 +54,7 @@ annotate my.Books with {
title @title:'{i18n>Title}'; title @title:'{i18n>Title}';
genre @title:'{i18n>Genre}' @Common: { Text: genre.name, TextArrangement: #TextOnly }; genre @title:'{i18n>Genre}' @Common: { Text: genre.name, TextArrangement: #TextOnly };
author @title:'{i18n>Author}' @Common: { Text: author.name, TextArrangement: #TextOnly }; author @title:'{i18n>Author}' @Common: { Text: author.name, TextArrangement: #TextOnly };
price @title:'{i18n>Price}' @Measures.ISOCurrency: currency_code; price @title:'{i18n>Price}';
stock @title:'{i18n>Stock}'; stock @title:'{i18n>Stock}';
descr @UI.MultiLineText; descr @UI.MultiLineText;
} }

View File

@@ -6,7 +6,7 @@
"@capire/reviews": "*", "@capire/reviews": "*",
"@capire/orders": "*", "@capire/orders": "*",
"@capire/common": "*", "@capire/common": "*",
"@sap/cds": "^5", "@sap/cds": ">=4",
"express": "^4.17.1", "express": "^4.17.1",
"passport": "^0.4.1" "passport": "^0.4.1"
}, },

View File

@@ -19,7 +19,7 @@ extend Books with {
// Extend Orders with Books as Products // Extend Orders with Books as Products
// //
using { sap.capire.orders.Orders } from '@capire/orders'; using { sap.capire.orders.Orders_Items } from '@capire/orders';
extend Orders.Items with { extend Orders_Items with {
book : Association to Books on product.ID = book.ID book : Association to Books on product.ID = book.ID
} }

View File

@@ -38,11 +38,7 @@ GET {{bookshop}}/browse/Books(201)?
&$select=ID,title,rating &$select=ID,title,rating
&$expand=reviews &$expand=reviews
###
GET {{bookshop}}/browse/Books?
&$select=title,author&$expand=currency
Accept-Language: de
################################################# #################################################
# #

View File

@@ -1,3 +1,2 @@
cds.requires.messaging.kind = file-based-messaging cds.requires.messaging.kind = file-based-messaging
PORT = 4006 PORT = 4006
# cds.odata.flavor = x4

View File

@@ -11,7 +11,6 @@
using { OrdersService } from '../../srv/orders-service'; using { OrdersService } from '../../srv/orders-service';
using { sap.common } from '@capire/common';
@odata.draft.enabled @odata.draft.enabled
@@ -69,7 +68,7 @@ annotate OrdersService.Orders with @(
annotate OrdersService.Orders.Items with @( annotate OrdersService.Orders_Items with @(
UI: { UI: {
LineItem: [ LineItem: [
{Value: product_ID, Label:'Product ID'}, {Value: product_ID, Label:'Product ID'},
@@ -78,22 +77,13 @@ annotate OrdersService.Orders.Items with @(
{Value: amount, Label:'Quantity'}, {Value: amount, Label:'Quantity'},
], ],
Identification: [ //Is the main field group Identification: [ //Is the main field group
{Value: product_ID, Label:'Product ID'},
{Value: title, Label:'Product Title'},
{Value: amount, Label:'Amount'}, {Value: amount, Label:'Amount'},
{Value: title, Label:'Product'},
{Value: price, Label:'Unit Price'}, {Value: price, Label:'Unit Price'},
], ],
Facets: [ Facets: [
{$Type: 'UI.ReferenceFacet', Label: '{i18n>OrderItems}', Target: '@UI.Identification'}, {$Type: 'UI.ReferenceFacet', Label: '{i18n>OrderItems}', Target: '@UI.Identification'},
], ],
HeaderInfo: {
TypeName: 'Order Item', TypeNamePlural: 'Order Items',
Title: {
Label: 'Product ID ', //A label is possible but it is not considered on the ObjectPage yet
Value: product_ID
},
Description: {Value: createdBy}
},
}, },
) { ) {
amount @( amount @(

View File

@@ -3,17 +3,17 @@ namespace sap.capire.orders;
entity Orders : cuid, managed { entity Orders : cuid, managed {
OrderNo : String @title:'Order Number'; //> readable key OrderNo : String @title:'Order Number'; //> readable key
Items : Composition of many Orders.Items on Items.up_ = $self; Items : Composition of many Orders_Items on Items.up_ = $self;
buyer : User; buyer : User;
currency : Currency; currency : Currency;
} }
entity Orders.Items { entity Orders_Items {
/*key*/ up_ : Association to Orders; // REVISIT: 'key' doesn't work due to bug in runtime
key ID : UUID; key ID : UUID;
product : Association to Products; up_ : Association to Orders;
product : Association to Products @assert.integrity:false; // REVISIT: this is a temporary workaround for a glitch in cds-runtime
amount : Integer; amount : Integer;
title : String; //> intentionally replicated as snapshot from product.title or alike title : String; //> intentionally replicated as snapshot from product.title
price : Double; price : Double;
} }

View File

@@ -2,7 +2,6 @@
"name": "@capire/orders", "name": "@capire/orders",
"version": "1.0.0", "version": "1.0.0",
"dependencies": { "dependencies": {
"@capire/common": "*", "@sap/cds": ">=4.3.0"
"@sap/cds": "^5"
} }
} }

View File

@@ -1,31 +0,0 @@
@Orders = http://localhost:4006/orders/Orders
### Read Orders
GET {{Orders}}?
###
GET {{Orders}}?$expand=Items
###
GET {{Orders}}(ID={{Order1}},IsActiveEntity=true)/Items
@Order1 = 64e718c9-ff99-47f1-8ca3-950c850777d4
@Order3 = e939604c-ab83-4d4f-bdb6-95fe30b3773e
### Create order, still inactive
POST {{Orders}}
Content-Type: application/json
{"ID": "{{Order3}}"}
### Get inactive order. We have to specify `IsActiveEntity`.
GET {{Orders}}(ID={{Order3}},IsActiveEntity=false)
### Activate order using `.../<servicename>.draftActivate`
POST {{Orders}}(ID={{Order3}},IsActiveEntity=false)/OrdersService.draftActivate
Content-Type: application/json
### Get active order
GET {{Orders}}(ID={{Order3}},IsActiveEntity=true)

View File

@@ -3,7 +3,7 @@ class OrdersService extends cds.ApplicationService {
/** register custom handlers */ /** register custom handlers */
init(){ init(){
const { 'Orders.Items':OrderItems } = this.entities const { Orders_Items:OrderItems } = this.entities
this.before ('UPDATE', 'Orders', async function(req) { this.before ('UPDATE', 'Orders', async function(req) {
const { ID, Items } = req.data const { ID, Items } = req.data

View File

@@ -26,7 +26,7 @@
"fiori": "cds watch fiori", "fiori": "cds watch fiori",
"media": "cds watch media", "media": "cds watch media",
"mocha": "npx mocha || echo", "mocha": "npx mocha || echo",
"jest": "npx jest@^26", "jest": "npx jest",
"test": "npm run jest --silent" "test": "npm run jest --silent"
}, },
"mocha": { "mocha": {

View File

@@ -7,7 +7,7 @@
"index.cds" "index.cds"
], ],
"dependencies": { "dependencies": {
"@sap/cds": "^5", "@sap/cds": ">=4",
"express": "^4.17.1" "express": "^4.17.1"
}, },
"scripts": { "scripts": {

View File

@@ -280,7 +280,7 @@ describe('cds.ql → cqn', () => {
).to.eql({ ).to.eql({
SELECT: { SELECT: {
from: { ref: ['Foo'] }, from: { ref: ['Foo'] },
where: cds.version >= '5.3.0' where: cdr
? [ ? [
// '(', //> this one is not required // '(', //> this one is not required
{ ref: ['ID'] }, { ref: ['ID'] },
@@ -289,7 +289,7 @@ describe('cds.ql → cqn', () => {
'and', 'and',
{ ref: ['args'] }, { ref: ['args'] },
'in', 'in',
{ list: args.map(val => ({ val })) }, { val: args },
'and', 'and',
'(', //> this one is missing, and that's changing the logic -> that's a BUG '(', //> this one is missing, and that's changing the logic -> that's a BUG
{ ref: ['x'] }, { ref: ['x'] },

View File

@@ -6,9 +6,13 @@ else cds.User = cds.User.Privileged // hard core monkey patch for older cds rele
describe('Custom Handlers', () => { describe('Custom Handlers', () => {
it('should reject out-of-stock orders', async () => { it('should reject out-of-stock orders', async () => {
await POST('/browse/submitOrder', { book: 201, amount: 5 }) await expect(
await POST('/browse/submitOrder', { book: 201, amount: 5 }) Promise.all([
await expect(POST('/browse/submitOrder', { book: 201, amount: 5 })).to.be.rejectedWith(/409 - 5 exceeds stock for book #201/) POST('/browse/submitOrder', { book: 201, amount: 5 }),
POST('/browse/submitOrder', { book: 201, amount: 5 }),
POST('/browse/submitOrder', { book: 201, amount: 5 }),
])
).to.be.rejectedWith(/409 - 5 exceeds stock for book #201/)
const { data } = await GET`/admin/Books/201/stock/$value` const { data } = await GET`/admin/Books/201/stock/$value`
expect(data).to.equal(2) expect(data).to.equal(2)
}) })

View File

@@ -43,7 +43,7 @@ describe('Localized Data', () => {
{ title: 'Jane Eyre', author: 'Charlotte Brontë', currency: { name: 'Pfund' } }, { title: 'Jane Eyre', author: 'Charlotte Brontë', currency: { name: 'Pfund' } },
{ title: 'The Raven', author: 'Edgar Allen Poe', currency: { name: 'US-Dollar' } }, { title: 'The Raven', author: 'Edgar Allen Poe', currency: { name: 'US-Dollar' } },
{ title: 'Eleonora', author: 'Edgar Allen Poe', currency: { name: 'US-Dollar' } }, { title: 'Eleonora', author: 'Edgar Allen Poe', currency: { name: 'US-Dollar' } },
{ title: 'Catweazle', author: 'Richard Carpenter', currency: { name: 'Yen' } }, { title: 'Catweazle', author: 'Richard Carpenter', currency: { name: 'Euro' } },
]) ])
}) })
@@ -85,7 +85,7 @@ describe('Localized Data', () => {
{ title: 'Jane Eyre', currency: { name: 'British Pound' } }, { title: 'Jane Eyre', currency: { name: 'British Pound' } },
{ title: 'The Raven', currency: { name: 'US Dollar' } }, { title: 'The Raven', currency: { name: 'US Dollar' } },
{ title: 'Eleonora', currency: { name: 'US Dollar' } }, { title: 'Eleonora', currency: { name: 'US Dollar' } },
{ title: 'Catweazle', currency: { name: 'Yen' } }, { title: 'Catweazle', currency: { name: 'Euro' } },
]) ])
}) })
}) })