# -*- coding: utf-8 -*-
"""只操作本程序创建的临时对象；全部数据为合成样本。"""
import os, sys, json, sqlite3, tempfile, pathlib, subprocess, time, socket, stat
from pathlib import Path
def emit(**kw):
    print(json.dumps(kw, ensure_ascii=False, sort_keys=True))
with tempfile.TemporaryDirectory(prefix='ywebs-next132-b2-counter-') as d:
    p=str(Path(d)/'demo.db'); a=sqlite3.connect(p); b=sqlite3.connect(p)
    a.executescript("CREATE TABLE usage(tenant,bucket,n,UNIQUE(tenant,bucket)); INSERT INTO usage VALUES('A','day',0);")
    x=a.execute('SELECT n FROM usage').fetchone()[0]; y=b.execute('SELECT n FROM usage').fetchone()[0]
    a.execute('UPDATE usage SET n=?',(x+1,)); a.commit(); b.execute('UPDATE usage SET n=?',(y+1,)); b.commit(); lost=b.execute('SELECT n FROM usage').fetchone()[0]
    a.execute('UPDATE usage SET n=0'); a.commit()
    sql="INSERT INTO usage VALUES('A','day',1) ON CONFLICT(tenant,bucket) DO UPDATE SET n=usage.n+excluded.n"
    a.execute(sql); a.commit(); b.execute(sql); b.commit(); atomic=b.execute('SELECT n FROM usage').fetchone()[0]
    assert lost==1 and atomic==2; emit(lost=lost,atomic=atomic)
    a.close(); b.close()
