From 98d4f814323c50c3ea5427896c0eba6c40224bdc Mon Sep 17 00:00:00 2001 From: Michiel Borkent Date: Wed, 20 May 2020 13:55:37 +0200 Subject: [PATCH] Add example --- examples/pod-lispyclouds-sqlite/README.md | 20 ++++++ .../pod-lispyclouds-sqlite.py | 61 +++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 examples/pod-lispyclouds-sqlite/README.md create mode 100755 examples/pod-lispyclouds-sqlite/pod-lispyclouds-sqlite.py diff --git a/examples/pod-lispyclouds-sqlite/README.md b/examples/pod-lispyclouds-sqlite/README.md new file mode 100644 index 0000000..0de0c5b --- /dev/null +++ b/examples/pod-lispyclouds-sqlite/README.md @@ -0,0 +1,20 @@ +# pod-lispyclouds-sqlite + +To run this: + +- Install python3 and sqlite3 +- Create a virtualenv: `python3 -m venv ~/.virtualenvs/babashka` +- Switch to it: `source ~/.virtualenvs/babashka/bin/activate` +- Run: `pip install bcoding` to install the bencode lib +- Create a new db: `sqlite3 /tmp/babashka.db "create table foo (foo int);"` + +Then run as pod: + +``` clojure +(babashka.pods/load-pod ["./pod-lispyclouds-sqlite.py"]) +(require '[pod.lispyclouds.sqlite :as sqlite]) +(sqlite/execute! "create table if not exists foo ( int foo )") +(sqlite/execute! "delete from foo") +(sqlite/execute! "insert into foo values (1), (2)") +(sqlite/execute! "select * from foo") ;;=> ([1] [2]) +``` diff --git a/examples/pod-lispyclouds-sqlite/pod-lispyclouds-sqlite.py b/examples/pod-lispyclouds-sqlite/pod-lispyclouds-sqlite.py new file mode 100755 index 0000000..0b0c65c --- /dev/null +++ b/examples/pod-lispyclouds-sqlite/pod-lispyclouds-sqlite.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 + +import json +import sqlite3 +import sys + +from bcoding import bencode, bdecode + + +def read(): + return dict(bdecode(sys.stdin.buffer)) + + +def write(obj): + sys.stdout.buffer.write(bencode(obj)) + sys.stdout.flush() + +def debug(*msg): + with open("/tmp/debug.log", "a") as f: + f.write(str(msg) + "\n") + +def main(): + while True: + msg = read() + debug("msg", msg) + + op = msg["op"] + + if op == "describe": + write( + { + "format": "json", + "namespaces": [{"name": "pod.lispyclouds.sqlite", + "vars": [{"name": "execute!"}]}]} + ) + elif op == "invoke": + var = msg["var"] + id = msg["id"] + args = json.loads(msg["args"]) + debug(args) + conn = sqlite3.connect("/tmp/babashka.db") + c = conn.cursor() + + result = None + + if var == "pod.lispyclouds.sqlite/execute!": + try: + result = c.execute(*args) + except Exception as e: + debug(e) + + value = json.dumps(result.fetchall()) + debug("value", value) + + write({"value": value, "id": id, "status": ["done"]}) + + conn.commit() + conn.close() + +if __name__ == "__main__": + main()