2016-08-29 38 views
1

運行下面的python腳本兩次拋出這個錯誤:Peewee:外部事務不回滾內的事務(保存點)

peewee.ProgrammingError: relation "test_table" already exists 

,因爲該表沒有得到關於.rollback()刪除。刪除內部交易(與test_db.atomic())的作品。爲什麼內部交易(僅根據documentation的保存點)未得到回滾?

from datetime import datetime 
from peewee import Model, DateTimeField 
from playhouse.postgres_ext import PostgresqlExtDatabase 

""" 
CREATE ROLE test WITH LOGIN; 
DROP DATABASE IF EXISTS test; 
CREATE DATABASE test WITH OWNER test; 
""" 

CREDENTIALS = { 
    "database": "test", 
    "user": "test", 
    "password": None, 
    "host": "localhost", 
    "port": 5432, 
    "register_hstore": False, 
} 


test_db = PostgresqlExtDatabase(**CREDENTIALS) 
test_db.connect() 
test_db.set_autocommit(False) 
test_db.begin() # start transaction 

class TestTable(Model): 
    timestamp = DateTimeField(null=False, default=datetime(1970,1,1,0,0,0,)) 

    class Meta: 
     db_table = "test_table" 
     database = test_db 

with test_db.atomic(): 

    TestTable.create_table() 
    TestTable.create() 

test_db.rollback() # rollback transaction 

print TestTable.get().timestamp 
test_db.close() 

版本

peewee==2.8.3 
psycopg2==2.6.2 

PostgreSQL 9.5.1 on x86_64-apple-darwin15.3.0, compiled by Apple LLVM version 7.0.2 (clang-700.1.81), 64-bit 
+0

我這個玩耍了多一點,即使我添加第二個測試表**內部**外部事務,但_test_db.atomic()_外部** _它不會在* rollback *上被移除。兩個表都會在沒有* test_db.atomic()*語句的情況下被刪除。 – kev

回答

0

,取決於您所使用的數據庫,DDL(架構更改)可能會或可能無法回滾。

Postgresql和SQLite都似乎支持回滾DDL,但MySQL不支持。

但是,SQLite的Python驅動程序有一個錯誤,導致它在發出DDL時發出COMMIT。第一個補丁在2010年提交:http://bugs.python.org/issue10740

而且看看pysqlite2,這在本質上是一樣的標準庫sqlite3的:

https://github.com/ghaering/pysqlite/blob/ca5dc55b462a7e67072205bb1a9a0f62a7c6efc4/src/cursor.c#L537-L547

+0

我正在使用Postgres(PostgresqlExtDatabase)。 – kev