Coder Social home page Coder Social logo

oatpp / example-postgresql Goto Github PK

View Code? Open in Web Editor NEW
38.0 4.0 18.0 45 KB

A complete example of a "CRUD" service (UserService) built with Oat++ and using oatpp ORM with PostgreSQL.

Home Page: https://oatpp.io/

License: Apache License 2.0

CMake 7.74% Dockerfile 1.96% C++ 86.92% Shell 3.38%
oatpp cpp microservices postgresql swagger-ui orm

example-postgresql's Introduction

Stand With Ukraine


Oat++ Logo

 

oatpp build status Join the chat at https://gitter.im/oatpp-framework/Lobby

Oat++

Oat++ is a modern Web Framework for C++. It's fully loaded and contains all necessary components for effective production level development. It's also light and has a small memory footprint.

News

  • ⚠️ Attention! Oat++ main repo is bumping its version to 1.4.0. While 1.4.0 is IN DEVELOPMENT use 1.3.0-latest tag.
  • Follow the changelog for news and features in version 1.4.0.
  • Consider supporting Oat++ via the GitHub sponsors page.

Start

Support the Project

Maintaining and developing this project requires significant time and resources. If you enjoy using it and want to support its continued development, please consider supporting us through GitHub Sponsors.

Become a Sponsor on GitHub

Every contribution, big or small, helps us keep improving and maintaining the project. Thank you for your support!

About

Quick Overview

Shortcuts:

Build Powerful API And Document It With Swagger-UI

See ApiController for more details.

ENDPOINT_INFO(getUserById) {
  info->summary = "Get one User by userId";

  info->addResponse<Object<UserDto>>(Status::CODE_200, "application/json");
  info->addResponse<Object<StatusDto>>(Status::CODE_404, "application/json");
  info->addResponse<Object<StatusDto>>(Status::CODE_500, "application/json");

  info->pathParams["userId"].description = "User Identifier";
}
ENDPOINT("GET", "users/{userId}", getUserById,
         PATH(Int32, userId))
{
  return createDtoResponse(Status::CODE_200, m_userService.getUserById(userId));
}

Access Databases And Keep Your Data Consistent

See Oat++ ORM for more details.

QUERY(createUser,
      "INSERT INTO users (username, email, role) VALUES (:username, :email, :role);",
      PARAM(oatpp::String, username), 
      PARAM(oatpp::String, email), 
      PARAM(oatpp::Enum<UserRoles>::AsString, role))

Join Our Community

Examples

REST-API

  • REST Service - A complete example of a "CRUD" service (UserService) built with Oat++. REST + Swagger-UI + SQLite.
  • REST Client - Example project of how-to use Retrofit-like client wrapper (ApiClient) and how it works.

WebSocket

  • Can Chat - Feature-complete rooms-based chat for tens of thousands users. Client plus Server.
  • WebSocket - Collection of oatpp WebSocket examples.
  • YUV Websocket Stream - Example project how-to create a YUV image stream from a V4L device (i.E. Webcam) using websockets.

Databases

  • SQLite - A complete example of a "CRUD" service. REST + Swagger-UI + SQLite.
  • PostgreSQL - Example of a production-grade entity service storing information in PostgreSQL. With Swagger-UI and configuration profiles.
  • MongoDB - Example project how to work with MongoDB using oatpp-mongo mondule. Project is a web-service with basic CRUD and Swagger-UI.

IoT

  • Example-IoT-Hue - Example project how-to create an Philips Hue compatible REST-API that is discovered and controllable by Hue compatible Smart-Home devices like Amazon Alexa or Google Echo.

Streaming

  • HTTP Live Streaming Server - Example project on how to build an HLS-streaming server using Oat++ asynchronous API.
  • YUV Websocket Stream - Example project how-to create a YUV image stream from a V4L device (i.E. Webcam) using websockets.

TLS

  • TLS With Libressl - Example project how-to setup secure connection and serve via HTTPS.

Microservices

Asynchronous API

  • Async Service - Example project on how to use asynchronous API to handle a large number of simultaneous connections.

Frequently Asked Questions

Q: "Oat++" name?

  • "Oat" is something light, organic, and green. It can be easily cooked and consumed with no effort.
  • "++" gives a hint that it is "something" for C++.

Q: What is the main area of Oat++ application?

Oat++ is used for many different purposes, from building REST APIs that run on embedded devices to building microservices and highly-loaded cloud applications.

But the majority of use cases appears to be in IoT and Robotics.

Q: How portable is Oat++?

Theoretically, Oat++ can be easily ported everywhere where you have threads and network stack. With an additional comparably small effort, it can be ported almost everywhere depending on how much you strip it and what would be the final binary size.

See supported platforms for additional info.

Q: What is the size of a minimal Oat++ application?

About 1Mb, depending on C/C++ std-lib and oatpp version.

Q: Which Oat++ API to choose, Simple or Async?

Always choose Simple API wherever possible. Simple API is more developed and makes the code cleaner.

Async API is designed for small, specific tasks that run at high concurrency levels ex.:

  • Serving file downloads to a large number of concurrent users (1K users and more).
  • Streaming to a large number of clients (1K or more).
  • Websocket Chat servers.

For all other purposes use simple API.

example-postgresql's People

Contributors

lganzzzo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

example-postgresql's Issues

No examples or support for select count(*)

I have looked all over for an example to simply do a basic select COUNT(*) query.

After wasting a good hour without any success, I'm throwing in the towel.

  QUERY(getAllUsersCount,
        "SELECT COUNT(*) FROM \"AppUser\";")

Over in the service....


  auto dbCountResult = m_database_postgres->getAllUsersCount();
  OATPP_ASSERT_HTTP(dbCountResult->isSuccess(), Status::CODE_500, dbCountResult->getErrorMessage());

Fails with error I can't have anything that's not a container.


  auto total_count = dbCountResult->fetch<oatpp::data::mapping::type::UInt32>(); 
  auto total_count_list = dbCountResult->fetch<oatpp::Vector<oatpp::Fields<oatpp::Any>>>(); 
  auto total_count_list = dbCountResult->fetch<oatpp::Vector<oatpp::Fields< oatpp::UInt32>>>(); 

Fails when I try to iterate the result, no methods begin/end and for each not working. Plus I expect one answer not many.

Why is this so hard?

oatpp-swagger not installing while building the docker image

I am trying to install and run the application but I am unable to because oatpp-swagger isn't found.

Which is caused because the cmake for oatpp-swagger module is failing.

############################################################################
## oatpp-swagger module. Resolving dependencies...


############################################################################

CMake Error at CMakeLists.txt:103 (add_compile_definitions):
  Unknown CMake command "add_compile_definitions".

Opened /bin/ash from the container to find the cmake version to be 3.11.1.

cmake version 3.11.1

According to this the cmake version needs to be >=3.12 to use "add_compile_definitions"

The docker image needs to be upgraded with a higher version of cmake. That should solve this issue.

CMake Error during docker compose up

❯ docker compose up
[+] Building 1.2s (11/12)                                                                                                                                   
 => [service internal] load build definition from Dockerfile                                                                                           0.0s
 => => transferring dockerfile: 281B                                                                                                                   0.0s
 => [service internal] load .dockerignore                                                                                                              0.0s
 => => transferring context: 46B                                                                                                                       0.0s
 => [service internal] load metadata for docker.io/lganzzzo/alpine-cmake:latest                                                                        0.5s
 => [service 1/8] FROM docker.io/lganzzzo/alpine-cmake:latest@sha256:8558b04111c2796787268961f362d03ef257a92db6312b43abb3a1430de9a144                  0.0s
 => [service internal] load build context                                                                                                              0.0s
 => => transferring context: 7.03kB                                                                                                                    0.0s
 => CACHED [service 2/8] RUN apk add postgresql-dev                                                                                                    0.0s
 => CACHED [service 3/8] ADD . /service                                                                                                                0.0s
 => CACHED [service 4/8] WORKDIR /service/utility                                                                                                      0.0s
 => CACHED [service 5/8] RUN ./install-oatpp-modules.sh                                                                                                0.0s
 => CACHED [service 6/8] WORKDIR /service/build                                                                                                        0.0s
 => ERROR [service 7/8] RUN cmake ..                                                                                                                   0.7s
------                                                                                                                                                      
 > [service 7/8] RUN cmake ..:                                                                                                                              
0.154 -- The C compiler identification is GNU 6.4.0                                                                                                         
0.180 -- The CXX compiler identification is GNU 6.4.0                                                                                                       
0.183 -- Check for working C compiler: /usr/bin/cc                                                                                                          
0.213 -- Check for working C compiler: /usr/bin/cc -- works                                                                                                 
0.214 -- Detecting C compiler ABI info
0.244 -- Detecting C compiler ABI info - done
0.249 -- Detecting C compile features
0.342 -- Detecting C compile features - done
0.344 -- Check for working CXX compiler: /usr/bin/c++
0.377 -- Check for working CXX compiler: /usr/bin/c++ -- works
0.377 -- Detecting CXX compiler ABI info
0.410 -- Detecting CXX compiler ABI info - done
0.415 -- Detecting CXX compile features
0.563 -- Detecting CXX compile features - done
0.564 CMake Error at CMakeLists.txt:30 (find_package):
0.564   By not providing "Findoatpp.cmake" in CMAKE_MODULE_PATH this project has
0.564   asked CMake to find a package configuration file provided by "oatpp", but
0.564   CMake did not find one.
0.564 
0.564   Could not find a package configuration file provided by "oatpp" (requested
0.564   version 1.3.0) with any of the following names:
0.564 
0.564     oatppConfig.cmake
0.564     oatpp-config.cmake
0.564 
0.564   Add the installation prefix of "oatpp" to CMAKE_PREFIX_PATH or set
0.564   "oatpp_DIR" to a directory containing one of the above files.  If "oatpp"
0.564   provides a separate development package or SDK, be sure it has been
0.564   installed.
0.564 
0.564 
0.565 -- Configuring incomplete, errors occurred!
0.565 See also "/service/build/CMakeFiles/CMakeOutput.log".
------
failed to solve: process "/bin/sh -c cmake .." did not complete successfully: exit code: 1

[oatpp::postgresql::Executor::getConnection()]: Error. Can't connect.

reproduce:

$ docker build -t example-postgresql .
$ docker run -p 8000:8000 -e CONFIG_PROFILE='dev' -t example-postgresql

D |2021-10-20 04:43:45 1634705025742559| Server:Loading configuration profile 'dev'
terminate called after throwing an instance of 'std::runtime_error'
what(): [oatpp::postgresql::Executor::getConnection()]: Error. Can't connect.

image

How to add custom db and dto?

image

User defined entities are added in the controller, DB, dto and service directories respectively, but compilation errors are reported.

Deserilization to type String

I have added the column 'created' to the table 'AppUser' in the example-postgresql

CREATE TABLE IF NOT EXISTS AppUser (
    id                      varchar (256) PRIMARY KEY,
    username                varchar (256) NOT NULL,
    email                   varchar (256) NOT NULL,
    password                varchar (256) NOT NULL,
    role                    varchar (256) NULL,
    created                 timestamp DEFAULT now(), -- NEW COLUMN --
    CONSTRAINT              UK_APPUSER_USERNAME UNIQUE (username),
    CONSTRAINT              UK_APPUSER_EMAIL UNIQUE (email)
);

I have modified 'UserDto.hpp' to add the field as String DTO_FIELD(String, created, "created");

but when I try to test the endpoint of getUserById to select some user, I get the following error

{
  "status": "ERROR",
  "code": 500,
  "message": "[oatpp::postgresql::mapping::Deserializer::deserializeString()]: Error. Unknown OID."
}

as I understand from the error message I have to perform a conversion type to take the timestamp value to string

How can I do this?

Having Role enum name in createUser from swagger fails with error.

Hi dear Leo.
I have problem with enum in DTO_FIELD in createUser api execution.
If i remove the role from request, it works. couldn't figure it out why.
Also my db encoding is UTF8
Thanks in advance.

Request body:

{
  "username": "string2",
  "email": "string2",
  "password": "string2",
  "role": "ROLE_GUEST"
}

Response:

{
  "status": "ERROR",
  "code": 500,
  "message": "ERROR:  invalid byte sequence for encoding \"UTF8\": 0xdd 0xdd\nCONTEXT:  unnamed portal parameter $4\n"
}

And this is my DTO:

#include OATPP_CODEGEN_BEGIN(DTO)

ENUM(Role, v_int32,
     VALUE(GUEST, 0, "ROLE_GUEST"),
     VALUE(ADMIN, 1, "ROLE_ADMIN")
)

class UserDto : public oatpp::DTO {
  
  DTO_INIT(UserDto, DTO)

  DTO_FIELD(String, id);
  DTO_FIELD(String, userName, "username");
  DTO_FIELD(String, email, "email");
  DTO_FIELD(String, password, "password");
  DTO_FIELD(Enum<Role>::AsString, role, "role");

};

#include OATPP_CODEGEN_END(DTO)

UserDb:

  QUERY(createUser,
        "INSERT INTO AppUser"
        "(id, username, email, password, role) VALUES "
        "(uuid_generate_v4(), :user.username, :user.email, :user.password, :user.role)"
        "RETURNING *;",
        PREPARE(true), // user prepared statement!
        PARAM(oatpp::Object<UserDto>, user))

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.