tsqlitebindatas.nim 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. discard """
  2. action: "run"
  3. exitcode: 0
  4. """
  5. import db_sqlite
  6. import random
  7. import os
  8. from stdtest/specialpaths import buildDir
  9. block tsqlitebindatas: ## db_sqlite binary data
  10. const dbName = buildDir / "tsqlitebindatas.db"
  11. let origName = "Bobby"
  12. var orig = newSeq[float64](150)
  13. randomize()
  14. for x in orig.mitems:
  15. x = rand(1.0)/10.0
  16. discard tryRemoveFile(dbName)
  17. let db = open(dbName, "", "", "")
  18. let createTableStr = sql"""CREATE TABLE test(
  19. id INTEGER NOT NULL PRIMARY KEY,
  20. name TEXT,
  21. data BLOB
  22. )
  23. """
  24. db.exec(createTableStr)
  25. var dbuf = newSeq[byte](orig.len*sizeof(float64))
  26. copyMem(unsafeAddr(dbuf[0]), unsafeAddr(orig[0]), dbuf.len)
  27. var insertStmt = db.prepare("INSERT INTO test (id, name, data) VALUES (?, ?, ?)")
  28. insertStmt.bindParams(1, origName, dbuf)
  29. let bres = db.tryExec(insertStmt)
  30. doAssert(bres)
  31. finalize(insertStmt)
  32. var nameTest = db.getValue(sql"SELECT name FROM test WHERE id = ?", 1)
  33. doAssert nameTest == origName
  34. var dataTest = db.getValue(sql"SELECT data FROM test WHERE id = ?", 1)
  35. let seqSize = int(dataTest.len*sizeof(byte)/sizeof(float64))
  36. var res: seq[float64] = newSeq[float64](seqSize)
  37. copyMem(unsafeAddr(res[0]), addr(dataTest[0]), dataTest.len)
  38. doAssert res.len == orig.len
  39. doAssert res == orig
  40. db.close()
  41. doAssert tryRemoveFile(dbName)