Skip to Content
Technical Articles
Author's profile photo Mike Zaschka

Getting started with CAP on PostgreSQL (Node.js)

Starting with version 7.0.0 @sap/cds now has native support for PostgreSQL. Please use the official database adapter @cap-js/postgres in favor of the described packages below and check out the official documentation for more details.

There is also a great blog post by Tia Xu which includes a detailed step-by-step-guide on how to use @cap-js/postgres in a local environment as well as in combination with Cloud Foundry.

 

Updates

The SAP Cloud Application Programming Model is an opinionated framework of libraries, languages and tools by SAP to build enterprise-grade cloud-based services and applications. It comes with pre-baked support for SAP technologies (SAP HANA, SAP Event Mesh, etc.), but is (more and more) designed to be open to other tools, platforms and standards.
One major part of CAP is the domain model, in which all the domain entities can be defined via Core Data Services (CDS) and either be connected to external services or databases. Out of the box CAP has native support for SAP HANA (and SQLite for development scenarios only), but is also designed to support bring-your-own-database-scenarios (at least since version 4.1).

PostgreSQL is a powerful Open Source database, that can be downloaded and used for free and also is available on almost every PaaS-Provider, including SAP BTP (PostgreSQL on SAP BTP). While SAP HANA may be the better choice in CAP projects closely related to other SAP systems (S/4HANA, etc.), PostgreSQL may be a powerful and cheaper alternative in other scenarios (that maybe aren’t connected to SAP BTP at all).

But how can PostgreSQL can be used in CAP?

By using two Open Source Node.js modules in combination with @sap/cds:

  • cds-pg
  • cds-dbm

cds-pg – The PostgreSQL adapter for SAP CDS

Since PostgreSQL support is not natively available in CAP, the integration must be provided by others. In August 2020, Volker Buzek and Gregor Wolf started their efforts to build cds-pg, a PostgreSQL adapter for CAP and made it Open Source on GitHub. They also shared their vision and invited others to contribute in a blog post.
Since then, some community members (David Sooter, Lars Hvam, Mike Zaschka) contributed to the project and while it is not yet ready to be used in production, cds-pg already supports many features of CAP (which will be shown later in this post).

cds-dbm – Database deployment for PostgreSQL on CAP

While cds-pg contains the functionality to translate the CDS model to native PostgreSQL during runtime, there is a closely related library available, that deals with the deployment of the generated database schema (tables and views): cds-dbm.
For SAP HANA, SAP is providing the @sap/hdi-deployer module, that handles all the relevant deployment tasks (analyze the delta between the current state of the database and the current state of the CDS model, deploy the changes to the database, load CSV files, etc.). cds-dbm provides this functionality for cds-pg and is designed to support other potential CAP database adapters (think of SQL Server, DB2, MySQL, MariaDB, Amazon RDS…) in the future (that’s why the functionality is not baked in cds-pg, but in its own module).

Start using cds-pg and cds-dbm in a CAP project

There are already some projects available, that can act as a reference on how to use cds-pg and cds-dbm, e.g. the pg-beershop project by Gregor Wolf (which includes deployment scenarios to many different Cloud Service providers), but since this blog post should also showcase, that the development workflow feels very similar to native CAP development, we will start from scratch.
If you just want to look at the source code, you can find it on GitHub.

Prerequisites

To follow along the upcoming steps, you need to have the following tools installed on your system:

  • Node.js (version 12)
  • Java (JRE in at least version 8)
  • Docker (for running the PostgreSQL database)
  • Visual Studio Code (or another editor)

Many of the steps that need to be done are part of the default development workflow of CAP. A more detailed explanation of those standard steps can be found in the official documentation.

Create the initial project

To create the initial project, you need to have the @sap/cds-dk library installed as a global Node.js module.

npm i -g @sap/cds-dk

With this in place, we can kickstart the project by letting the @sap/cds-dk generate the devtoberfest project. While SAP’s Devtoberfest is/was real our project will just act as a demo and contain a data model leveraging projects and votes.

cds init devtoberfest

This should have created the base folder structure which can be opened in VS Code (or any other editor).

Add and setup the PostgreSQL database

To actually use PostgreSQL, we need to have a database in place. For this, we rely on docker. Simply create a docker-compose.yml file in the root folder of the project and insert the following data:

version: '3.1'

services:
  db:
    image: postgres:alpine
    restart: always
    environment:
      POSTGRES_PASSWORD: postgres
    ports:
      - '5432:5432'
  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080

We basically define two docker containers, one for the PostgreSQL database itself and one for adminer, a web based tool to access the database.

UPDATE (22.11.2020)
With version 0.0.14, cds-dbm is able to create the database during the deployment automatically, thus the steps to login to adminer and to create the database by hand are not required anymore. Just add the --create-db flag when running the deployment:
npx cds-dbm deploy --create-db`

To create the database, just open the browser and access the adminer interface at http://localhost:8080. Login with the following credentials (these will also be required for cds-pg later):

  • Server: db (this is the name of PostgreSQL service in the docker-compose.yml file)
  • User: postgres
  • Password: postgres

In the adminer interface, just create a new database and give it the name devtoberfest. And now we are ready to go.

Include and configure cds-pg and cds-dbm

The next step contains the integration and configuration of the Node.js modules. Since both are standard NPM modules, they can easily be installed via:

npm i cds-pg
npm i cds-dbm

The configuration is the more complex part, but also sticks to the default CAP rules of providing configuration in the project descriptor file (package.json).
The following snippet shows the required parts (the full example can be viewed here):

"cds": {
    "requires": {
      "db": {
        "kind": "database"
      },
      "database": {
        "impl": "cds-pg",
        "dialect": "plain"
        "model": [
          "srv"
        ],
        "credentials": {
          "host": "localhost",
          "port": 5432,
          "database": "devtoberfest",
          "user": "postgres",
          "password": "postgres"
        }
      }
    },
    "migrations": {
      "db": {
        "schema": {
          "default": "public",
          "clone": "_cdsdbm_clone",
          "reference": "_cdsdbm_ref"
        },
        "deploy": {
          "tmpFile": "tmp/_autodeploy.json",
          "undeployFile": "db/undeploy.json"
        }
      }
    }
  }

The cds.requires part is basically standard CAP and defines, that there is a db service of the kind database (freely chosen name) and the configuration of that service. The only difference to a native (meaning HANA/SQLite) project is the specific naming of cds-pg as the service implementation.

The additional cds.migrations section is currently required by cds-dbm. An explanation of the various configuration options can be found in the cds-dbm documentation.

Start developing the application

Since now the project is setup, we can start building the actual service and application. The good news is, that due to the abstraction of CDS, you can build the application in almost the exact same way, you would be doing with SAP HANA/SQLite… with some exceptions:
Since it’s currently not possible to hook into the cds command, the following commands are not yet supported:

  • cds watch (no equivalent present)
  • cds deploy(use cds-dbm deploy instead, more details on this below)

The first thing we should do is to define our data model. We start by adding the file db/data-model.cds and create an entity:

using { cuid } from '@sap/cds/common';
namespace db;

entity Projects: cuid {
  name : String(150);
  language: String(150);
  repository: String;
}

Next up, we need a service, that exposes the entity. Therefore just create the file srv/public-service.cdswith the following content:

using db from '../db/data-model';

service PublicService {
    entity Projects as projection on db.Projects;
}

Deployment

Since we now have defined our initial data model and service, we need to deploy the corresponding db artifacts to the PostgreSQL database. As mentioned above, cds deploy cannot be leveraged. Instead, we need to make use of the tasks cds-dbm provides. A full description can be found in the official documentation.
To deploy the changes, simply call the following cmd from the command line (npx is required as of now):

npx cds-dbm deploy

To verify, that the database tables have been created properly, just go back to the adminer and refresh the schema. You should see, that all the tables and views are available. You will also find two additional tables databasechangelog and  databasechangeloglock. These are automatically generated by the internally used library liquibase and should be left untouched.

Creating and consuming data

It’s now time to startup the server and add some data. At first, we want to use the service API to add data to the database. Therefore we start the server by typing:

cds serve

The service endpoints should now be available at: http://localhost:4004/public/
To create the data, we will leverage the VS Code REST Client plugin, because it is easy to setup and use. If you are not using VS Code, you can also use Postman, cUrl or other tools.

If you have the REST Client plugin installed, just add a file test/projects.http with the following content and send the request to your API.

### Create entity
POST http://localhost:4004/public/Projects
Content-Type: application/json

{
    "name": "cds-pg - PostgreSQL adapter for SAP CDS (CAP)",
    "repository": "https://github.com/sapmentors/cds-pg",
    "language": "Node.js"
}

When you open the projects in the browser (http://localhost:4004/public/Projects), you should see the inserted project, delivered right from the PostgreSQL database.

Loading data via .csv files

Another way to insert data into the database is by using .csv files (see official documentation). cds-dbmalso has support for .csv files. While the .csv files are automatically loaded in native CAP scenarios (with SQLite and SAP HANA) during deployment, the data loading must be explicitly triggered in cds-dbm.

But first, we need to create the file db/data/db-Projects.csv and add the following content:

ID,name,repository,language
c682de2f-536b-44fe-acdd-6475d5660ca2,cds-dbm - Database deployment for PostgreSQL on CAP,https://github.com/mikezaschka/cds-dbm,Node.js
5d1e6d61-3ad5-4813-9a67-1fd9df440f68,abapGit: Git client for ABAP,https://github.com/abapGit/abapGit,ABAP
b6c36859-84c1-486b-9f32-a6a25513f3ba,abap-dev-utilities: ABAP Development Tools,https://github.com/jrodriguez-rc/abap-dev-utilities,ABAP
2d7c145e-fd40-492f-8499-2dd21e3cf0fc,vscode_abap_remote_fs: Remote filesystem for ABAP systems,https://github.com/marcellourbani/vscode_abap_remote_fs,ABAP

To actually load the data into the database, you have two options:

// only load .csv data
npx cds-dbm load --via delta  

// deploy data model and load .csv data
npx cds-dbm deploy --load-via delta  

By specifying the load parameter to delta, cds-dbmdoes not remove existing data from the corresponding table, but only adds missing or updates altered rows. If the load parameter is set to full, then the target table will be truncated and the data from the .csv file loaded into the empty table (the only supported mode in native CAP).

So if you executed one of the above commands, then you should now see the data in your exposed API (http://localhost:4004/public/Projects).

Applying changes to the data model

As a last step, we now want to enhance the data model and add support for votes. Thus, we update the following files:

db/data-model.cds

using { cuid } from '@sap/cds/common';
namespace db;

entity Projects: cuid {
  name : String(150);
  language: String(150);
  repository: String;
  votes: Association to many Votes on votes.project = $self;
}

entity Votes: cuid {
  username : String(150);
  createdAt: DateTime;
  project: Association to one Projects;
}

srv/public-service.cds

using db from '../db/data-model';

service PublicService {
    entity Projects as projection on db.Projects;
    entity Votes as projection on db.Votes;
}

cds-dbm has support for automated delta deployments (like native CAP on SAP HANA) and only applies the changes from your current CDS model to the database (unlike native CAP on SQLite, which drops the whole data model on every deployment). Before we do the deployment, let’s examine the changes on the database level by using the diff command:

npx cds-dbm diff

This shows a detailed list of all changes between the current state of the database and your cds model. Basically, the Votes table and the corresponding view are missing, as to be expected.

To deploy the changes, we again use the cds-dbm deploy task, via:

npx cds-dbm deploy

All the additional entities should now be available in your service. Please restart the server (cds serve) and refresh your browser. When you closely look at the Projecs entity (http://localhost:4004/public/Projects), you will see, that all the data in the db_projectstable is still there, even the data that has been inserted via API. This is because cds-dbm does not only support delta deployments on a schema level, but is also able to keep your data available in tables, that will be filled with default (.csv) data).

A short summary

If you have followed this post until the very end, you should now have the basic understanding, that CAP on PostgreSQL is no more only an idea, but it’s a real thing. By leveraging cds-pg and cds-dbm, you are able to use the power of CAP in combination with PostgreSQL as a database. And while there are some differences in the development workflow, things pretty much stick to the native feeling of working with CAP.

What’s next?

Update: 31.11.2020
With the latest developments it is possible to deploy and run your application on SAP BTP Cloud Foundry. Checkout this blogpost for more details.

But even when there is already lots of functionality available, CAP on PostgreSQL is not done yet and needs more support (draft functionality, multitenancy support…).

From here on, there are multiple paths:

Start using it

Even if the libraries are not mature yet, feel free to enhance the devtoberfest application or start building your own projects. If you have feature requests or encounter bugs/errors, please add them as issues to the respective github projects of cds-pg or cds-dbm and help us, making the libraries more mature.

Jump in and start contributing

Engaging in Open Source projects can be seen as spending not payed time on stuff, that others use. But it can also be seen as taking part in and shaping projects, that have a real impact on things, that matter to you (and your company). It is also a thing to get in contact with great people, learn from others, be supportive and make yourself a name in the (SAP) community.
So if you are liking the concepts behind CAP and also the idea of running CAP on PostgreSQL (or any other DB), then jump in and start contributing:

A final word to SAP

CAP is awesome. And it would be even more awesome, if it would be more open. I think it’s understandable, that CAP cannot be completely open sourced, because for SAP it needs to have the focus on SAP related technologies. But it definitely can be more open, by having well defined and better documented APIs.

Come on SAP, take a look at what we, the SAP community, are able to come up with…and we can even do better, if you let us by opening things up…

Assigned Tags

      62 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Matthew Reddy
      Matthew Reddy

      Great blog, thanks Mike!

      We have been thinking for a while now to get away from HANA as it is by far our largest expense for running our SaaS applications, but just haven't had the time to figure out the integration/deployment/etc. to any other type of DB. The blog and projects you have put together are now scheduled for my next weekend hack!

      And yes - 100% agree with your sentiment re: CAP being awesome and SAP needing to open it up more. I have spent a LOT of time troubleshooting and learning things that could have been easy fixes with better documentation.

      Author's profile photo Gregor Wolf
      Gregor Wolf

      Hi Matthew,

      if you have any suggestions regarding the documentation please post them in the SAP Cloud Application Programming Model Q&A and mention Iwona Hahn. She provides really good support here.

      Best regards
      Gregor

      Author's profile photo Matthew Reddy
      Matthew Reddy

      Thanks for the guidance as always, Gregor - will do

      Author's profile photo Mike Zaschka
      Mike Zaschka
      Blog Post Author

      Hey Matthew,

      as stated in the post, things are not yet ready for production and some core CAP features are still missing. But it would be awesome if you could start looking into this. Help will be much appreciated. 🙂

      Kind Regards,
      Mike

      Author's profile photo Matthew Reddy
      Matthew Reddy

      Will keep you posted!

      Author's profile photo Tejaswi Ayyapusetty
      Tejaswi Ayyapusetty

      Hello Mike Zaschka ,

      Can we use PostgresSQL adapter for productive applications?

      Best Regards,

      Tejaswi

      Author's profile photo Gregor Wolf
      Gregor Wolf

      Hi Tejaswi,

      you should do a thorough testing before productive use. If you face any issues please file them at https://github.com/sapmentors/cds-pg/issues.

      Best Regards
      Gregor

      Author's profile photo Helmut Tammen
      Helmut Tammen

      Thanks Mike for this great blog and thanks to all the contributers of the functionality for this great CAP feature pack

      Regards Helmut

      Author's profile photo Aditia Doni Satria
      Aditia Doni Satria

      If exponential growth volume data transaction, Do postgress have capabilities to handle it?

      Author's profile photo Mike Zaschka
      Mike Zaschka
      Blog Post Author

      This is not easy to be answered with the lack of more details. In general, PostgreSQL is a very mature Open Source database used by many small and large companies around the world. From a technical standpoint, PostgreSQL is able to handle billions of rows of data (e.g. the size limit of a table is 32 Terrabyte), but, as with every other database, you need to think about vertical or horizontal scaling.
      And I would also add financial scaling if you want to rely on a managed PostgreSQL service (e.g. the PostgreSQL Hyperscaler Option), since storage and memory usage comes with a price.

      Author's profile photo Marc Mauri
      Marc Mauri

      Thanks Mike for this illustrative blog and thanks for contributing this amazing module that brings us closer to PostgreSQL as a new option for CAP projects.

      Big thanks also to Gregor, Volker and rest of contributors for spending time on this.

      Best regards,

      Marc

      Author's profile photo Mike Zaschka
      Mike Zaschka
      Blog Post Author

      Hi Marc,

      thank you.
      And great to see your devtoberfest repo on GitHub.

      Kind Regards,

      Mike

      Author's profile photo G. Valer
      G. Valer

      Hi Mike,

      Do you have any advice on how to handle user authentication and authorization with CAP and Postgres?

      Thanks and regards.

      Author's profile photo Gregor Wolf
      Gregor Wolf

      As long as you run the app on SAP Cloud Platform - Cloud Foundry Environment it's not different as when you use HANA. If you're looking for other platforms you might find some value checking out my repository: cap-azure-ad-b2c.

      Author's profile photo G. Valer
      G. Valer

      Hi Gregor,

       

      Thanks a lot for your reply. I want to use SAP CAP in a non SAP system. If you can guide me please from where to start or what approach should I follow it will be very helpful.

      As I understood from Christian Georgi from this thread SAP license for CAP is allowing the use of this technology outside the SAP ecosystem without any support from SAP.

       

      Thank you very much for your help.

      Author's profile photo Gregor Wolf
      Gregor Wolf

      In addition to the already linked repository: cap-azure-ad-b2c I would suggest to check out pg-beershop which is a sample project that uses PostgreSQL and I've dployed it also to Azure. If you run into issues feel free to post questions in the CAP Questions here in the SAP Community.

      Author's profile photo G. Valer
      G. Valer

      Thanks a lot Gregor. I'll take a look at your repository.

      Author's profile photo Octav Onu
      Octav Onu

      Great job!

      I think that openui5 & cds-pg is the perfect marriage in web dev space.

       

      Thank you for your effort and time!

       

       

      Author's profile photo Sergey belyakov
      Sergey belyakov

      Good day!
      I'm trying to create a sample based on this tutorial - everything crashes at the first delpoy attempt.

      I am attaching an error.

      Author's profile photo Gregor Wolf
      Gregor Wolf

      Dear Sergey,

      please file an issue at https://github.com/sapmentors/cds-pg/issues. I guess it's an issue with the new CDS 5 release. So you might try with CDS 4. And you're welcome to contribute CDS 5 support.

      Best regards
      Gregor

      Author's profile photo Mike Zaschka
      Mike Zaschka
      Blog Post Author

      Hey Gregor Wolf

      I really was quick, but no one is as fast as you are. 😁
      I checked the tutorial with @sap/cds version 5.0.4 and everything worked as expected, so I would assume this is more of an infrastructure problem (see my comment below).

      Kind Regards,

      Mike

      Author's profile photo Mike Zaschka
      Mike Zaschka
      Blog Post Author

      Hi Sergey,

      I checked the tutorial with the latest version of @sap/cds (5.0.4) and everything worked fine.
      Looking at the error, it may be related to the issue in this StackOverflow question: https://stackoverflow.com/questions/48593016/postgresql-docker-role-does-not-exist

      So potentially, you already have a PostgreSQL instance running on your Mac that breaks things?

      Kind Regards,

      Mike

       

      Author's profile photo Sergey belyakov
      Sergey belyakov

      Добрый вечер!
      Несколько раз пытался воссоздать с нуля (более того, я перешел по вашей ссылке на StackOverFlow, остановил процесс brew postgresql), но все время застреваю в каких-то ошибках - прикрепляю скриншоты

      PS Одна из них сотрудничает с неправильным паролем - что странно, я использую все, как ваше, в учебнике. Единственное, что я изменил, так это имя db (вместо Projects - поставьте "Компанию")

      И можете раз вы ответили - ли вы мне сказать, как, например, привязать базу данных из другого облака? Вам тоже нужно развернуть его в докере?

      Спасибо заранее!

      P.S.S. Tried it from another macbook - with the command "npx cds-dbm deploy" and "npx cds-dbm deploy --create-db" it catches the error "Error: connect ECONNREFUSED 127.0.0.1:5432
      at TCPConnectWrap.afterConnect [as oncomplete] (net.js: 1113: 14) ", I also attach a screenshot.
      However, the next guide on deployment in cf turned out successfully (though now the question is how to connect a third-party database to postgresql from another cloud, and not insert data via .csv)

      Author's profile photo Gregor Wolf
      Gregor Wolf

      Hi,

      I've just updated my sample project pg-beershop to the latest cds version 5. Also I've upgraded my Node.JS runtime to 14 as recommended in the CAP release notes for the Spring 2021 release. It's working just fine running it locally. Please get the project and follow the description in the readme. The readme also shows different options to deploy to different Cloud Providers.

      Best regards
      Gregor

      Author's profile photo Sergey belyakov
      Sergey belyakov

      Thanks - answered with another comment.

      Author's profile photo Sergey belyakov
      Sergey belyakov

      Thank you Gregor Wolf и Mike Zaschka !

      I collected a project for this tutorial and published it in cloud foundry as follows, but my question is:
      If in this tutorial the data can be added to the adminer, and they will be displayed on the local host - how can the same data be transferred to deploy to Cloud Foundry services? Is it possible? Or just by adding .csv models?

      Thanks in advance!

      Author's profile photo Gregor Wolf
      Gregor Wolf

      You should use the initial data provisioning using CSV files only for development. The CSV files will reset the sontent of your database with each deployment. Use the generated OData API's to fill the data. You can create a client for API Access. Check out bookshop-demo#allow-api-access.

      Author's profile photo Sergey belyakov
      Sergey belyakov

      Okay.
      I looked at your link (on bookshop), created a tests folder with two files:
      one). xs-security.json;
      2). test.env (where I filled in the data that came after executing the commands in the VScode terminal (the data is as follows:

      { "apiurl": "https://api.authentication.eu10.hana.ondemand.com", ... )).

      How can you bind the generated ApiOdata and what in this context is meant as ApiOdata?
      Thanks in advance!

      Author's profile photo Carl Önnheim
      Carl Önnheim

      Hi,

      Great work on this Gregor Wolf and Mike Zaschka! I have one challenge with table names getting too long when using several levels of compositions. PGSQL has a limit of 63 characters (half of HANA to my knowledge).

      Table names are generated by cds-dbm as

      namespace_entityname_composition_subcomposition_subsubcomposition_and_so_on

      which runs out if there are many levels / long names.

      I can of course manage this by shortening the field names in the entity model, but since that also makes the API services less clear I was wondering if there is any way around this (e.g. with annotations forcing the name at the database level).

      Thanks in advance!

      //Carl

      Author's profile photo Gregor Wolf
      Gregor Wolf

      Hi Carl,

      thank you for the kudos.

      Please post this question in the SAP Cloud Application Programming Model Q&A to get also the attention of the SAP CAP developers.

      Best regards
      Gregor

      Author's profile photo Max Schnürle
      Max Schnürle

      Hi Mike Zaschka

      great Post! In reference to that I would like to understand the differences (if they exist) between PostGreSQL connection with Node.js and Java. Are there pros and cons for both programming languages? Is there an overview available? Does the CAP connection to postgresql work better with Node.js or Java?

      I would be very grateful to receive some insights.

      Best Regards

      Max

      Author's profile photo Gregor Wolf
      Gregor Wolf

      Hi Max,

      until now cds-pg is NodeJS only.

      Best Regards
      Gregor

      Author's profile photo Max Schnürle
      Max Schnürle

      Hi Gregor Wolf

      thanks for the quick response!

      does that mean PostGreSQL only works with Node.js and not Java? or the integration is at least easier with Node.js as it just requires the two modules cds-pg and cds-dbm?

       

      Best Regards

      Max

      Author's profile photo Gregor Wolf
      Gregor Wolf

      cds-pg is pure NodeJS as it builds on the NodeJS adapter for PostgreSQL. cds-dbm might help you even in Java for the Database migrations. In Java it might even be simpler as you could try to change to another Database with a JDBC driver. For the SAP Supported databases check the CAP documentation on Database Support.

      Author's profile photo Max Schnürle
      Max Schnürle

      Is there a Blog Post on how to get started with CAP in PostgreSQL with Java?

      Best Regards

      Author's profile photo Mike Zaschka
      Mike Zaschka
      Blog Post Author

      Hi Max,

      in the officiation documentation on the Java SDK you will find some comments on PostgreSQL: https://cap.cloud.sap/docs/java/development/#database-support

      There seems to be some kind of official support, but there are also some limitations. Since I haven't worked with the Java SDK, I cannot further comment on this. And I also do not know, if there is a blog post or any further information available on how to use CAP Java with PostgreSQL.

      As Gregor mentioned, this post and cds-pg/cds-dbm are all about the Node.js SDK. There is no official support for PostgreSQL on the SAP side, but we, as a Community, implemented the adapter as an Open Source initiative.
      The adapter currently also has its limitations, but you can easily jump start a project and, since it's all Open Source, also contribute, if you find missing features or bugs.

      Author's profile photo Fedor Shestov
      Fedor Shestov

      Hi. Does this support multitenancy? If so, how can I implement? Thanks

      Author's profile photo Gregor Wolf
      Gregor Wolf

      Hi Fedor,

      Austin Kloske is working on the Issue Multitenancy support #25 please get in touch with him. You can join the #cds-pg Slack Channel. Just get your invite for the SAP Mentors & Friends Slack here.

      Best Regards
      Gregor

      Author's profile photo Pankaj Valecha
      Pankaj Valecha

      Hi Mike Zaschka,

      I followed the tutorial for my local CAP project, installed docker, admirer is up and running but when I am try to run "npm cds-dbm deploy", I am getting this error:

      npm%20buildTask%20Error

      npm buildTask Error

      I tried with fresh installation, cloned beershop repo and cap-postgres repo but getting this same error.

      Please help me out, what I am doing wrong.

      Regards,

      Pankaj Valecha

      Author's profile photo Gregor Wolf
      Gregor Wolf

      Hi Pankaj,

      unfortunately there is an issue with the current CAP version. Check out: Build fails when using @sap/cds 5.3.x - Error message: Cannot read property 'features' of undefined #34 and perhaps you can help to solve the issue.

      Best regards
      Gregor

      Author's profile photo Luca Bonetta
      Luca Bonetta

      Hi Mike,

      Thanks for this great blog!

      Just mind that the property "dialect" is missing in your package.json snippet for cds configuration. Without this property, as stated in the cds-pg git repository documentation, the service will not work with cap version >= 5.1.

      I suggest to change the snippet to something like this:

        "cds": {
          "requires": {
            "db": {
              "kind": "postgres"
            },
            "postgres": {
              "dialect": "plain",
              "impl": "cds-pg",
              "model": [
                "srv"
              ],
              "credentials": {
                ...
              }
            }
          },

       

      I hope to see more on this topic in the time to come!

      Best Regards
      Bonny

      Author's profile photo Yeno Angel Gutierrez Bellido
      Yeno Angel Gutierrez Bellido

      Hi Luca,

       

      I try to set >=5.1 or 5.1, but it does not work.

      Could you help me please.

      Error

       

      Regards.

      Angel Gutierrez

      Error

      Author's profile photo Austin Kloske
      Austin Kloske

      Angel Gutierrez Bellido the github page (https://github.com/sapmentors/cds-pg) says:

      "dialect": "plain", // <- for cds >= 5.1

      not:

      "dialect": ">= 5.1"
      Author's profile photo Luca Bonetta
      Luca Bonetta

      Hi Angel,

      As Austin Kloske already said, you need to change the property "dialect" to "plain".

      Looking at your stack trace it seems that you're trying to use cds-dbm command to deploy the service schema to the postgres database. At the moment the npm release of the library cds-dbm is not compatible with the latest release of sap/cds (5.7.*)

      You should change your version of sap/cds to <=5.4 in order for this to work properly. You can also keep the latest sap/cds version and compile the cds-dbm library from the github repository instead (https://github.com/mikezaschka/cds-dbm)

      Regards,
      Bonny

      Author's profile photo Yeno Angel Gutierrez Bellido
      Yeno Angel Gutierrez Bellido

      Hi Luca,

      I did get lastest version to cds-dbm. I set to my project the lastest version and i tried to change my version sap/cds but i have the same problem.

      Could you give me steps.

      Error

      Error

      Regards,

      Angel

      Author's profile photo anton kopylov
      anton kopylov

      Error at command npx cds-dbm deploy.

      If you project located in folder with spaces, you will get error

      Error: Command failed: C:\project\SAP CAP\devtoberfest\node_modules\cds-dbm\liquibase\liquibase ......
      'C:\project\SAP' is not recognized as an internal or external command,
      operable program or batch file.
      Author's profile photo Matthias Hayk
      Matthias Hayk

      Hi Mike and Gregor and all other contributers.I wish to thank all of your  for your great work on making postgreSQL available for cap. So its possible to build small services that needs persistence for a payable price to customers instead to force them to use hana db.

      I developed a cap app and used adminer as described here for first look on deployed data, edit some test values and so on.

      my question: how can i use adminer with my deployed solution on btp (and using the 'postgresql on hyperscaler-option' service from sap) to have a look on productive data. Of course i can use odata-services. But i have some tables i don't want to expose to Odata for example.

      kind regards
      Matthias

      Author's profile photo Gregor Wolf
      Gregor Wolf

      Hi Matthias,

      have you tried if the pg-beershop-adminer module that I've added in my pg-beershop example mta.yaml works?

      CU
      Gregor

      Author's profile photo Matthias Hayk
      Matthias Hayk

      Hi Gregor,

      yes i had a look at it and also tried it with my values in "requires" and "name". But i'm not really sure how to call the admin ui then, because the app-module is stopped and has no route by your declaration. Interestingly i did not see such a construct until now. It seems to use a docker-container as an app?

      I use the "sap postgreSQL hyperscaler option" for the database.

      Greets
      Matthias

      Author's profile photo Austin Kloske
      Austin Kloske

      Hey Mattias,

      Within my project structure I use an AWS postgres instance. This connects to the CAP application through a user-defined-service.

      Check out the last section of part 2 in the blog i put together (Postgres Cloud) here for a walkthrough.

      Author's profile photo Matthias Hayk
      Matthias Hayk

      Hi Austin, and thx for answering.

      In your blog your postgreSQL-Database is hosted as a "seperate" entity at aws. So you have url, credentials and used it in a "user-provided-service".
      In our usecase we want that the customer does not need to have a 'separate' postgreSQL instance and the service is managed by sap. for this we use the 'postgreSQL hyperscaler option' as a service, where sap manages such an instance on aws or azure. Question is how to connect in this scenario with adminer to database.

      greets
      Matthias

      Author's profile photo Phani Vasabattula
      Phani Vasabattula

      Thank you so much for this blog!

      I am getting the following error when deploying the CSV file. Any idea how to fix this?

      TypeError: Cannot read properties of undefined (reading 'regularRegex')
      at smartId (C:\capDemos\firstApp\node_modules\cds-pg\node_modules\@sap\cds-compiler\lib\sql-identifier.js:66:9)
      at _smartId (C:\capDemos\firstApp\node_modules\cds-pg\node_modules\@sap\cds\libx\_runtime\common\utils\quotingStyles.js:19:23)
      at PGReferenceBuilder.plain [as _quoteElement] (C:\capDemos\firstApp\node_modules\cds-pg\node_modules\@sap\cds\libx\_runtime\common\utils\quotingStyles.js:46:12)
      at C:\capDemos\firstApp\node_modules\cds-pg\node_modules\@sap\cds\libx\_runtime\db\sql-builder\ReferenceBuilder.js:106:49
      at Array.map (<anonymous>)
      at PGReferenceBuilder._parseReference (C:\capDemos\firstApp\node_modules\cds-pg\node_modules\@sap\cds\libx\_runtime\db\sql-builder\ReferenceBuilder.js:106:34)
      at PGReferenceBuilder.build (C:\capDemos\firstApp\node_modules\cds-pg\lib\pg\sql-builder\ReferenceBuilder.js:44:52)
      at PGSelectBuilder._buildRefElement (C:\capDemos\firstApp\node_modules\cds-pg\node_modules\@sap\cds\libx\_runtime\db\sql-builder\SelectBuilder.js:272:68)
      at PGSelectBuilder._buildElement (C:\capDemos\firstApp\node_modules\cds-pg\node_modules\@sap\cds\libx\_runtime\db\sql-builder\SelectBuilder.js:246:18)
      at C:\capDemos\firstApp\node_modules\cds-pg\node_modules\@sap\cds\libx\_runtime\db\sql-builder\SelectBuilder.js:311:56

      Author's profile photo Sonja Deissenboeck
      Sonja Deissenboeck

      Hey Phani Vasabattula did you resolve your problem? We are facing the exact same error message.

      Would be happy about your input!

      Author's profile photo Gregor Wolf
      Gregor Wolf

      I suggest you file an incident at cds-dbm with a repeatable example. Please not that cds-pg does not yet support CAP 6.

      Author's profile photo Phani Vasabattula
      Phani Vasabattula

      Hello Sonja,

      I exactly don't remember how it got fixed, I got most of the answers from the queries above. Please try these options.

      • Check the dialect
      • Downgrade the CDS version to 5 ( i tried 5.1.1)
      • Check if there is any inconsitencies in your entity definition. If you deploying on BTP provisioned postgresSQL server, then check the db deployer logs.

       

      Author's profile photo Durgaprasad Sreedhara
      Durgaprasad Sreedhara

      Hello,

       

      I developed a simple MTA with postgres database and using the cds-pg. The application has 1 DB entity and 2 services entity as projects on the same db entity with different filters. I am able to deploy the application into local docker postgres database and test without problem. But when I deploy to cloud BTP with a postgresql db option with standard service (hyperscaler) I get this error. I did change the service to standard from trial .

      Please help

       

      deploy%20error.

      deploy error.

      Author's profile photo Durgaprasad Sreedhara
      Durgaprasad Sreedhara

      When I unzip the mtar file that was deployed the data.zip in it is actually empty. So it appears that this is a valid error. What makes up the data.zip? I tried downloaded the cap-devtoberfest and attempted the same. I get the same error.

      Also something to note, when I tried to build this, it was complaining about the missing gen/db and gen/srv folders. I created them manually.

      I also tried the pg-beershop and that does not complain about the gen/db and gen/srv. Please advise what I am missing.

       

      My mta.yaml has 1 module for the "srv" and 1 module for deployer. and one resource for the database in resources section. Both modules have the reference to resources as "required".

      Author's profile photo Durgaprasad Sreedhara
      Durgaprasad Sreedhara
      ---
      _schema-version: '3.1'
      ID: wbg_hpy_cal
      version: 1.0.0
      description: "A simple CAP project."
      parameters:
        enable-parallel-deployments: true
      build-parameters:
        before-all:
        - builder: custom
          commands:
          - npm install --production
          # use cds-dbm for building, not cds
          - npx cds-dbm build --production
      modules:
        - name: xxxxxxxxx-srv
          type: nodejs
          path: gen/srv
          parameters:
            buildpack: nodejs_buildpack
          #build-parameters:
          #  builder: npm-ci
          provides:
            - name: srv-api # required by consumers of CAP services (e.g. approuter)
              properties:
                srv-url: ${default-url}
          requires:
            - name: pg-database
        - name: xxxxxxxx-db-deployer
          type: custom
          path: gen/db
          parameters:
            buildpacks: [https://github.com/cloudfoundry/apt-buildpack#v0.2.2, nodejs_buildpack] 
            no-route: true
            no-start: true
            disk-quota: 2GB
            memory: 512MB
            tasks:
            - name: deploy_to_postgresql
              command: chmod 755 deploy.sh && ./deploy.sh
              disk-quota: 2GB
              memory: 512MB      
          build-parameters:
            ignore: ["node_modules/"]
          requires:
            - name: pg-database 
      resources:
        - name: pg-database
          parameters:
              path: ./pg-options.json
              service: postgresql-db
              service-plan: standard
              skip-service-updates:
                parameters: true
          type: org.cloudfoundry.managed-service
      
      Author's profile photo Durgaprasad Sreedhara
      Durgaprasad Sreedhara

      and yes. how do I troubleshoot  npx cds-dbm build? Should that be generating the gen/db and gen/srv?

      My gen/db and gen/srv folders are empty. And that explains why my data.zip is empty.

      Are those coming from cds-dbm build?

      Author's profile photo Yeno Angel Gutierrez Bellido
      Yeno Angel Gutierrez Bellido

      Hi Mike,

      When I deploy my app to btp o locally Which return this error.

      Can you help me.

      Regards,

       

      Yeno Angel Gutierrez Bellido

      Author's profile photo Yeno Angel Gutierrez Bellido
      Yeno Angel Gutierrez Bellido

      Hi Mike,

      When i try to get some enteties. the app retuned this error. I don't understand, how to solve this.

      Could you help me.

      Regards,

      Yeno Angel Gutierrez Bellido

      Author's profile photo Fedor Shestov
      Fedor Shestov

      Hi. How can I use credentials from a user-defined service or environmental variables? I already have AWS db and would like to connect without SAP services i.e. directly to the app.