Skip to content

Instantly share code, notes, and snippets.

@lispyclouds
Created May 5, 2020 12:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lispyclouds/1b5125b1d7a8aba2741f86aade7e8359 to your computer and use it in GitHub Desktop.
Save lispyclouds/1b5125b1d7a8aba2741f86aade7e8359 to your computer and use it in GitHub Desktop.
A simple example for a SQLIte pod for Babashka
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("debug.log", "a") as f:
f.write(str(msg) + "\n")
def main():
while True:
msg = read()
op = msg["op"]
if op == "describe":
write(
{
"format": "json",
"vars": [{"namespace": "pod.sqlite", "name": "execute!"}],
}
)
elif op == "invoke":
var = msg["var"]
id = msg["id"]
args = json.loads(msg["args"])
conn = sqlite3.connect("bb.db")
c = conn.cursor()
result = None
if var == "pod.sqlite/execute!":
try:
result = c.execute(*args)
except Exception as e:
debug(e)
write({"value": json.dumps(result.fetchall()), "id": id, "status": ["done"]})
conn.commit()
conn.close()
if __name__ == "__main__":
main()
@lispyclouds
Copy link
Author

lispyclouds commented May 5, 2020

To run this:

  • Install Python3
  • SQLite3
  • Create a virtualenv: python3 -m venv ~/.virtualenvs/bb
  • Switch to it: source ~/.virtualenvs/bb/bin/activate
  • Run pip install bcoding for the bencode lib
  • Create a new db: sqlite3 bb.db "CREATE TABLE foo (foo int);"
  • Can be tested as:
python3 pod-bb-python-sqlite.py  <<< $(bb -e '(bencode/write-bencode System/out {"op" "invoke" "var" "pod.sqlite/execute!" "id" 1 "args" ["insert into foo values(1)"]})')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment