{"size": 1407, "ext": "js", "max_stars_repo_path": "server/src/store.js", "max_stars_repo_name": "miguelmota/ethmeet", "max_stars_repo_stars_event_min_datetime": "2017-06-11T04:23:02.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-04T09:51:53.000Z", "max_issues_repo_path": "server/src/store.js", "max_issues_repo_name": "miguelmota/eth.social", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/src/store.js", "max_forks_repo_name": "miguelmota/eth.social", "max_forks_repo_forks_event_min_datetime": "2017-12-24T15:34:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T13:09:03.000Z"}
{"max_stars_count": 16, "max_issues_count": null, "max_forks_count": 5, "avg_line_length": 19.8169014085, "max_line_length": 272, "alphanum_fraction": 0.6211798152}
const path = require('path')
const sqlite3 = require('sqlite3').verbose()
const pify = require('pify')

const dbpath = path.resolve(__dirname, '../sqlite.db')
const db = new sqlite3.Database(dbpath)

db.serialize(() => {
  db.run('CREATE TABLE IF NOT EXISTS posts (tx_hash TEXT, block_number INTEGER, id INTEGER, ipfs_hash TEXT, title TEXT, description TEXT, location TEXT, tags TEXT, image TEXT, start INTEGER, end INTEGER, created INTEGER, updated INTEGER, organizer TEXT, deleted INTEGER)')
})

//db.close()

function upsert ({
  txHash,
  blockNumber,
  id,
  ipfsHash,
  title,
  description,
  location,
  tags,
  image,
  start,
  end,
  created,
  updated,
  organizer,
  deleted
}) {
  const stmt = db.prepare('INSERT OR REPLACE INTO posts SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE NOT EXISTS(SELECT 1 FROM posts WHERE tx_hash = ?)')
  stmt.run(
    txHash,
    blockNumber,
    id,
    ipfsHash,
    title,
    description,
    location,
    tags,
    image,
    start,
    end,
    created,
    updated,
    organizer,
    deleted,
    txHash
  )
  console.log(`INSERT OR REPLACE: txHash=${txHash}`)
  stmt.finalize()
}

async function query (sql) {
  return new Promise((resolve, reject) => {
    db.all(sql, (error, rows) => {
      if (error) {
        console.error(error)
        return false
      }

      resolve(rows)
    })
  })
}

module.exports = {
  upsert,
  query
}
