1 /* 2 * Entity - Entity is an object-relational mapping tool for the D programming language. Referring to the design idea of JPA. 3 * 4 * Copyright (C) 2015-2018 Shanghai Putao Technology Co., Ltd 5 * 6 * Developer: HuntLabs.cn 7 * 8 * Licensed under the Apache-2.0 License. 9 * 10 */ 11 12 module hunt.entity.EntitySession; 13 14 import hunt.entity; 15 import hunt.database.base.Util; 16 import hunt.logging; 17 18 19 class EntitySession 20 { 21 22 private Database _db; 23 private Transaction _trans; 24 private SqlConnection _conn; 25 26 this(Database db) 27 { 28 assert(db !is null); 29 _db = db; 30 // _conn = _db.getConnection(); 31 } 32 33 ~this() 34 { 35 version(HUNT_ENTITY_DEBUG) Util.info("TODO: Closing EntitySession in ~this()"); 36 // version(HUNT_ENTITY_DEBUG) infof("Closing EntitySession in ~this()"); // bug 37 // close(); 38 } 39 40 void beginTransaction() 41 { 42 // alway return a new Transaction; 43 _trans = _db.getTransaction(getConnection()); 44 } 45 46 void commit() 47 { 48 assert(_trans !is null, "Execute beginTransaction first"); 49 checkConnection(); 50 _trans.commit(); 51 } 52 53 void rollback() 54 { 55 assert(_trans !is null, "Execute beginTransaction first"); 56 checkConnection(); 57 _trans.rollback(); 58 } 59 60 Statement prepare(string sql) 61 { 62 return _db.prepare(getConnection(), sql); 63 } 64 65 int execute(string sql) 66 { 67 version(HUNT_DEBUG) trace(sql); 68 RowSet rs = getConnection().query(sql); 69 return rs.rowCount(); 70 } 71 72 RowSet query(string sql) 73 { 74 version (HUNT_SQL_DEBUG) info(sql); 75 RowSet rs = getConnection().query(sql); 76 return rs; 77 } 78 79 SqlConnection getConnection() 80 { 81 if(_conn is null) 82 _conn = _db.getConnection(); 83 return _conn; 84 } 85 86 Transaction getTransaction() {return _trans;} 87 88 void close() 89 { 90 version(HUNT_ENTITY_DEBUG) Util.info("closing"); 91 if (_conn !is null && _db !is null) 92 { 93 version(HUNT_ENTITY_DEBUG) Util.info("closing connection"); 94 _db.relaseConnection(_conn); 95 } 96 _conn = null; 97 } 98 99 private void checkConnection() 100 { 101 if (_conn is null) 102 throw new EntityException("the entity connection haved been released."); 103 } 104 105 106 } 107 108 109