def test_autocommit_contextmanager(self): da = get_data_access().open(autocommit=False) cnst = dict(first_name=rand(), last_name=rand(), age=3) with transaction(da): with autocommit(da): da.insert("people", cnst) # Rollback should have no effect da.rollback() self.assertEqual(da.find("people", cnst).first_name, cnst["first_name"]) da.delete("people", cnst) da.commit()
def test_find_or_upsert(self): class UpsertTest(ModelBase): table_name = "upserts" attrs = { "name": None, "type": None } def insert(ma, name, type): return ma.insert_model(UpsertTest(name=name, type=type)) def upsert(ma, name, type, assign): with transaction(ma): assign.append(ma.find_or_upsert(UpsertTest, dict(name=name, type=type), comp=dict(name=name), return_status=True)) with get_model_access() as ma1, get_model_access() as ma2: with autocommit(ma1): ma1.execute("drop table if exists upserts") ma1.execute("create table upserts (id serial not null primary key, name text not null unique, type text not null, created_at timestamptz not null default now(), updated_at timestamptz not null default now());") ma1.execute("truncate table upserts") # 1) Two transactions: a) create b) upsert a) commit - check that a and b have same id # 2) Two transactions: a) create b) upsert a) rollback - check that a and b have differnet ids with transaction(ma1): mod1 = insert(ma1, "Trey", "person") mod2a = [] thread1 = Thread(target=lambda: upsert(ma2, "Trey", "person", mod2a)) thread1.start() sleep(0.25) self.assertTrue(thread1.is_alive()) thread1.join() mod2, mod2_status = mod2a[0] self.assertEqual(mod2_status, "duplicate") self.assertEqual(mod1.id, mod2.id) with transaction(ma1): mod3 = insert(ma1, "Julie", "person") mod4a = [] thread2 = Thread(target=lambda: upsert(ma2, "Julie", "person", mod4a)) thread2.start() sleep(0.25) self.assertTrue(thread2.is_alive()) raise RollbackTransaction() thread2.join() mod4, mod4_status = mod4a[0] self.assertEqual(mod4_status, "created") self.assertNotEqual(mod3.id, mod4.id) mod5a = [] upsert(ma1, "Trey", "person", mod5a) mod5, mod5_status = mod5a[0] self.assertEqual(mod5_status, "found") self.assertEqual(mod5.id, mod1.id)