SHARE
TWEET

Untitled

a guest Sep 3rd, 2018 97 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const { PostgreSQL } = require('mql2');
  2. const { CONNECT } = PostgreSQL;
  3. const POOL = await CONNECT({
  4.   host: 'localhost',
  5.   user: 'username',
  6.   password: '1234',
  7.   database: 'dbname'
  8. });
  9.    
  10. const { QUERY } = POOL;
  11. const id = 10;
  12. const posts = await QUERY `SELECT * FROM posts WHERE id = ${id}`;
  13. // [{ id: 10, ... }]
  14.    
  15. ASSOCIATE `
  16.   posts
  17.     - user
  18.     < comments
  19.      - user
  20.      p < likes
  21.       - user
  22.     p < likes
  23.       - user
  24.     x tags
  25. `;
  26.    
  27. ASSOCIATE `
  28.   posts ${SQL `WHERE is_hidden = false ORDER BY id DESC LIMIT ${10}`}
  29.     - user
  30.     < comments ${{
  31.       column: COLUMN('body', 'updated_at')
  32.     }}
  33.      - user
  34.      p < likes
  35.       - user
  36.     p < likes
  37.       - user
  38.     x tags
  39.    
  40. const posts = await ASSOCIATE `
  41.   posts ${{
  42.     table: 'articles'
  43.   }}
  44.     - user ${{
  45.       left_key: 'writer_id',
  46.       key: 'member_id',
  47.       table: 'members'
  48.     }}
  49.     < comments ${{
  50.       key: 'article_id'
  51.     }}
  52.       - user ${{
  53.         left_key: 'writer_id',
  54.         key: 'member_id',
  55.         table: 'members'
  56.       }}
  57.       p < likes ${{
  58.         poly_type: { parent_name: 'comments' },
  59.         key: 'parent_id'
  60.       }}
  61.     p < likes ${{
  62.       poly_type: { parent_name: 'articles' },
  63.       key: 'parent_id'
  64.     }}
  65.     x tags ${{
  66.       left_key: 'id',
  67.       left_xkey: 'article_id',
  68.       xtable: 'tags_articles',
  69.       xkey: 'tag_name',
  70.       key: 'name'
  71.     }}
  72. `;
  73.    
  74. const users = await ASSOCIATE `
  75.   users ${{hook: users => users.map(u =>
  76.     Object.assign({}, u, { _popular: !!u._.posts.find(p => p._is_best) })
  77.   )}}
  78.     < posts ${{hook: posts => posts.map(
  79.       p => Object.assign({}, p, { _is_best: p._.comments.length > 1 }))}}
  80.       - user
  81.       < comments
  82.        - user
  83. `;
  84.  
  85. users[0]._popular; // true
  86. users[0]._.posts[0]._is_best; // true
  87. users[0]._.posts[1]._is_best; // false
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top