Json workflow
#19
-
How well do this work with tao::json ? For example, how to do a "basic" insert returning id then select back. CREATE TABLE my_table {
id serial NOT NULL,
content jsonb NOT NULL,
CONSTRAINT my_table_pk PRIMARY KEY (id)
} With the json doc sample struct my_type
{
std::string title;
std::vector< int > values;
}; |
Beta Was this translation helpful? Give feedback.
Answered by
d-frey
Feb 4, 2020
Replies: 1 comment
-
The following code should now work using the latest version: // Copyright (c) 2020 Daniel Frey and Dr. Colin Hirsch
// Please see LICENSE for license or visit https://github.com/taocpp/taopq/
#include "../macros.hpp"
#include <tao/json.hpp>
#include <tao/pq.hpp>
#include <iostream>
namespace tao::json
{
std::string to_taopq_param( const value& v )
{
return to_string( v );
}
} // namespace tao::json
namespace tao::pq
{
template<>
struct result_traits< json::value >
{
[[nodiscard]] static json::value from( const char* value )
{
return json::from_string( value );
}
};
} // namespace tao::pq
void run()
{
// open a connection
const auto conn = tao::pq::connection::create( "dbname=template1" );
// execute statements directly
conn->execute( "DROP TABLE IF EXISTS tao_json" );
conn->execute( "CREATE TABLE tao_json ( id SERIAL PRIMARY KEY, content JSONB )" );
// preparing a statement is optional, but often recommended
conn->prepare( "insert", "INSERT INTO tao_json ( content ) VALUES ( $1 )" );
tao::json::value v = { { "foo", tao::json::value::array( { "bar", 42, true } ) } };
const auto res = conn->execute( "insert", v );
TEST_ASSERT( res.rows_affected() == 1 );
conn->execute( "insert", tao::json::value( 42 ) );
conn->execute( "insert", tao::json::value( true ) );
conn->execute( "insert", tao::json::value( "Hello, world!" ) );
for( const auto& row : conn->execute( "SELECT * FROM tao_json" ) ) {
// access fields by index or (less efficiently) by name
std::cout << row[ 0 ].as< int >() << ": " << row[ 1 ].as< tao::json::value >() << std::endl;
}
}
int main()
{
try {
run();
}
catch( const std::exception& e ) {
std::cerr << "exception: " << e.what() << std::endl;
throw;
}
catch( ... ) {
std::cerr << "unknown exception" << std::endl;
throw;
}
} Binding JSON values directly to structs should be explained in the JSON library's docs/examples. @ColinH might be able to explain that part better than me :) |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
d-frey
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The following code should now work using the latest version: