Created
May 5, 2020 12:27
-
-
Save lispyclouds/1b5125b1d7a8aba2741f86aade7e8359 to your computer and use it in GitHub Desktop.
A simple example for a SQLIte pod for Babashka
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To run this:
python3 -m venv ~/.virtualenvs/bb
source ~/.virtualenvs/bb/bin/activate
pip install bcoding
for the bencode libsqlite3 bb.db "CREATE TABLE foo (foo int);"