Home

    PostgreSQL setup - Seven Databases in Seven Weeks

    I am reading the book, Seven Databases in Seven Weeks. I’m not familiar with the databases yet, so it took some time to figure out how to make “createdb book” and “psql book -c “SELECT ‘1’::cube;” work.

    Here is the cookbook for it. I installed the postgres and contrib packages using Synaptic in Ubuntu before being able to run the following commands.

    $ sudo -u postgres psql
    postgres=# CREATE USER <username>;
    postgres=# ALTER USER <username> WITH CREATEDB PASSWORD '<password>';
    postgres=# \q
    
    $ createdb book
    $ sudo -u postgres psql book
    postgres=# CREATE EXTENSION cube;
    postgres=# \q
    
    $ psql book -c "SELECT '1'::cube;"

    Using variadic templates with function calls using tuple

    After this, I started working on this code.

    template <class R>
    void function0_impl(sqlite3_context* ctx, int nargs, sqlite3_value** values)
    {
      boost::function<R ()>* f =
          static_cast<boost::function<R ()>*>(sqlite3_user_data(ctx));
      context c(ctx, nargs, values);
      c.result((*f)());
    }
    
    template <class R, class P1>
    void function1_impl(sqlite3_context* ctx, int nargs, sqlite3_value** values)
    {
      boost::function<R (P1)>* f =
          static_cast<boost::function<R (P1)>*>(sqlite3_user_data(ctx));
      context c(ctx, nargs, values);
      c.result((*f)(c.context::get<P1>(0)));
    }
    ...
    template <class R, class P1, class P2, class P3, class P4, class P5>
    void function5_impl(sqlite3_context* ctx, int nargs, sqlite3_value** values)
    {
      boost::function<R (P1, P2, P3, P4, P5)>* f =
          static_cast<boost::function<R (P1, P2, P3, P4, P5)>*>(sqlite3_user_data(ctx));
      context c(ctx, nargs, values);
      c.result((*f)(c.context::get<P1>(0), c.context::get<P2>(1), c.context::get<P3>(2), c.context::get<P4>(3), c.context::get<P5>(4)));
    }

    It was much harder since it had to be able to call a method per parameter using index.

    (*f)(c.context::get<P1>(0),
         c.context::get<P2>(1),
         c.context::get<P3>(2),
         ...);
    }

    So, I made a plan to do this in two steps.

    1. make a tuple for the params.
    2. and call the function using the tuple.

    Make a tuple for the params

    template <class... Ts>
    std::tuple<Ts...> to_tuple() {
      return to_tuple_impl(0, *this, std::tuple<Ts...>());
    }
    
    template<class H, class... Ts>
    static inline std::tuple<H, Ts...> to_tuple_impl(int index, const context& c, std::tuple<H, Ts...>&&)
    {
      auto h = std::make_tuple(c.context::get<H>(index));
      return std::tuple_cat(h, to_tuple_impl(++index, c, std::tuple<Ts...>()));
    }
    static inline std::tuple<> to_tuple_impl(int index, const context& c, std::tuple<>&&)
    {
      return std::tuple<>();
    }

    This is not the most efficient code that can do this but the cleanest one that I could write. Frankly, in modern C++, I’m not sure if I’m helping compiler optimize the code or doing opposite.

    Call the function using the tuple

    I found the solution for this by googling.

    template<size_t N>
    struct Apply {
      template<typename F, typename T, typename... A>
      static inline auto apply(F&& f, T&& t, A&&... a)
        -> decltype(Apply<N-1>::apply(std::forward<F>(f),
                                      std::forward<T>(t),
                                      std::get<N-1>(std::forward<T>(t)),
                                      std::forward<A>(a)...))
      {
        return Apply<N-1>::apply(std::forward<F>(f),
                                 std::forward<T>(t),
                                 std::get<N-1>(std::forward<T>(t)),
                                 std::forward<A>(a)...);
      }
    };
    
    template<>
    struct Apply<0> {
      template<typename F, typename T, typename... A>
      static inline auto apply(F&& f, T&&, A&&... a)
        -> decltype(std::forward<F>(f)(std::forward<A>(a)...))
      {
        return std::forward<F>(f)(std::forward<A>(a)...);
      }
    };
    
    template<typename F, typename T>
    inline auto apply(F&& f, T&& t)
      -> decltype(Apply<std::tuple_size<typename std::decay<T>::type>::value>::apply(std::forward<F>(f), std::forward<T>(t)))
    {
      return Apply<std::tuple_size<typename std::decay<T>::type>::value>::apply(
          std::forward<F>(f), std::forward<T>(t));
    }

    Nice code, isn’t it? See details in http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3915.pdf and http://stackoverflow.com/a/12650100. The second link has the version for C++14 too.

    Final code

    template <class R, class... Ps>
    void functionx_impl(sqlite3_context* ctx, int nargs, sqlite3_value** values)
    {
      context c(ctx, nargs, values);
      auto f = static_cast<std::function<R (Ps...)>*>(sqlite3_user_data(ctx));
      c.result(apply(*f, c.to_tuple<Ps...>()));
    }

    Using variadic templates with different parameter types

    I wrote a C++ wrapper for SQLite in 2007, when there were no such things like variadic templates. To support variable length of paramters for some methods, I had to repeat the methods like this.

    template <class T1>
    boost::tuple<T1> get_columns(int idx1) const {
      return boost::make_tuple(get(idx1, T1()));
    }
    
    template <class T1, class T2>
    boost::tuple<T1, T2> get_columns(int idx1, int idx2) const {
      return boost::make_tuple(get(idx1, T1()), get(idx2, T2()));
    }
    
    template <class T1, class T2, class T3>
    boost::tuple<T1, T2, T3> get_columns(int idx1, int idx2, int idx3) const {
      return boost::make_tuple(get(idx1, T1()), get(idx2, T2()), get(idx3, T3()));
    }
    ...
    template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8>
    boost::tuple<T1, T2, T3, T4, T5, T6, T7, T8> get_columns(int idx1, int idx2, int idx3, int idx4, int idx5, int idx6, int idx7, int idx8) const {
      return boost::make_tuple(get(idx1, T1()), get(idx2, T2()), get(idx3, T3()), get(idx4, T4()), get(idx5, T5()), get(idx6, T6()), get(idx7, T7()), get(idx8, T8()));
    }

    Since then, I started using Java at work, and recently I found that C++11 introduced the variadic templates. I had to give it a try. A friend introduced me this video and it helped me a lot.

    The following was my try and had some difficulties with coming up with ?? part. (You might already notice that boost:: namespaces were changed to std:: for tuple and make_tuple.)

    template <class... Ts>
    std::tuple<Ts...> get_columns(??... idxs) const {
      return std::make_tuple(get(idxs, Ts())...);
    }

    The friend gave me a simple trick for this too, which I liked a lot. The final updated code is this.

    template <class T>
    struct convert {
      using to_int = int;
    };
    
    template <class... Ts>
    std::tuple<Ts...> get_columns(typename convert<Ts>::to_int... idxs) const {
      return std::make_tuple(get(idxs, Ts())...);
    }

    A nice thing of using this trick is that you can extend this to map the template parameter types to types whatever we want by using template specializations for convert. For example,

    template <class T>
    struct convert;
    
    template <>
    struct convert<float> {
      using to = float;
    };
    
    template <>
    struct convert<double> {
      using to = double;
    };

    Frankly, I cannot think of any practical situations that need this yet. =)

    Show possible links in 404 page

    The ideathinking.com was hosted by Blogger and I am reusing the domain for this, which means I broke all the links that were in Blogger.

    There were not many pageviews so I might not have to be bothered but I decided to try my best. =)

    The old links in Blogger should be accessible using blogspot domain. That is, http://ideathinking.com/2009/10/arraysizeof-macro.html is accessible in http://idea-thinking.blogspot.com/2009/10/arraysizeof-macro.html.

    IIUC, it’s not possible to handle this in Jekyll since it’s a static site generator. So, I put a small javascript file, assets/javascripts/404.js.

    var URL = document.URL.replace(window.location.hostname, 'idea-thinking.blogspot.com');
    document.getElementById('404').innerHTML = '<a href="%%">%%</a>'.replace(/%%/g, URL);

    And in 404.md file,

    Try <b><span id="404"></span></b>
    <script type="text/javascript" src="/assets/javascripts/404.js"></script>

    You can see this in action in http://ideathinking.com/2009/10/arraysizeof-macro.html.

    How to show the latest N posts on homepage in Jekyll

    If you are like me, you might want to show the latest N posts on homepage in your blog. This is the simplest solution that I have found so far.

    Just put the code snippet below in your index.md file. Just don’t forget to delete the spaces between { and % in the code.

    ---
    layout: page
    title : Home
    header : Home
    group: navigation
    ---
    { % include JB/setup %}
    
    <ul class="posts">  
    	{ % for post in site.posts limit:5 %}
            <h1 class="entry-title">
    		{ % if post.title %}
    			<a href=""></a>
    		{ % endif %}
    	</h1>
    	<div class="entry-content"></div>
    	{ % endfor %}  
    </ul>