1 9 package com.ziclix.python.sql.pipe.db; 10 11 import com.ziclix.python.sql.PyConnection; 12 import com.ziclix.python.sql.pipe.Source; 13 import org.python.core.Py; 14 import org.python.core.PyObject; 15 import org.python.core.PyTuple; 16 17 23 public class DBSource extends BaseDB implements Source { 24 25 28 protected String sql; 29 30 33 protected boolean sentHeader; 34 35 38 protected PyObject params, include; 39 40 50 public DBSource(PyConnection connection, Class dataHandler, String tableName, String where, PyObject include, PyObject params) { 51 52 super(connection, dataHandler, tableName); 53 54 this.params = params; 55 this.include = include; 56 this.sentHeader = false; 57 this.sql = this.createSql(where); 58 } 59 60 63 protected String createSql(String where) { 64 65 StringBuffer sb = new StringBuffer ("select "); 67 68 if ((this.include == Py.None) || (this.include.__len__() == 0)) { 69 sb.append("*"); 70 } else { 71 for (int i = 1; i < this.include.__len__(); i++) { 72 sb.append(this.include.__getitem__(i)).append(","); 73 } 74 75 sb.append(this.include.__getitem__(this.include.__len__() - 1)); 76 } 77 78 sb.append(" from ").append(this.tableName); 79 sb.append(" where ").append((where == null) ? "(1=1)" : where); 80 81 String sql = sb.toString(); 82 83 return sql; 84 } 85 86 89 public PyObject next() { 90 91 if (this.sentHeader) { 92 93 return this.cursor.fetchone(); 95 } else { 96 this.cursor.execute(Py.newString(this.sql), this.params, Py.None, Py.None); 97 98 PyObject description = this.cursor.__findattr__("description"); 99 100 if ((description == Py.None) || (description.__len__() == 0)) { 102 103 return Py.None; 105 } 106 107 int len = description.__len__(); 108 PyObject[] columns = new PyObject[len]; 109 110 for (int i = 0; i < len; i++) { 111 PyObject[] colInfo = new PyObject[2]; 112 113 colInfo[0] = description.__getitem__(i).__getitem__(0); 115 116 colInfo[1] = description.__getitem__(i).__getitem__(1); 118 columns[i] = new PyTuple(colInfo); 119 } 120 121 PyObject row = new PyTuple(columns); 122 123 Py.writeDebug("db-source", row.toString()); 124 125 this.sentHeader = true; 126 127 return row; 128 } 129 } 130 131 134 public void start() { 135 } 136 137 140 public void end() { 141 142 if (this.cursor != null) { 143 this.cursor.close(); 144 } 145 } 146 } 147 | Popular Tags |