PDO.hx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. /*
  2. * Copyright (C)2005-2012 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package php.db;
  23. import php.NativeArray;
  24. import sys.db.Connection;
  25. import sys.db.ResultSet;
  26. import php.Lib;
  27. /**
  28. * PDO::FETCH_COLUMN = 7
  29. * PDO::FETCH_CLASS = 8
  30. * PDO::FETCH_INTO = 9
  31. * PDO::PARAM_STR = 2
  32. * PDO::FETCH_BOTH = 4
  33. * PDO::FETCH_ORI_NEXT = 0
  34. */
  35. class PDO
  36. {
  37. public static function open(dsn : String, ?user : String, ?password : String, ?options : Dynamic) : Connection {
  38. return new PDOConnection(dsn, user, password, options);
  39. }
  40. }
  41. extern class PDOClass
  42. {
  43. // public function new(dns : String, ?username : String, ?password : String, ?driver_options : NativeArray) : Void;
  44. public function beginTransaction() : Bool;
  45. public function commit() : Bool;
  46. public function errorCode() : Dynamic;
  47. public function errorInfo() : NativeArray;
  48. public function exec(statement : String) : Int;
  49. public function getAttribute(attribute : Int) : Dynamic;
  50. public function getAvailableDrivers() : NativeArray;
  51. public function lastInsertId(?name : String) : String;
  52. public function prepare(statement : String, driver_options : NativeArray) : PDOStatement;
  53. public function query(statement : String, mode : Int) : PDOStatement;
  54. public function quote(String : String, ?parameter_type : Int = 2) : String;
  55. public function rollBack() : Bool;
  56. public function setAttribute(attribute : Int, value : Dynamic) : Bool;
  57. }
  58. extern class PDOStatement
  59. {
  60. public function bindColumn(column : Dynamic, param : Dynamic, ?type : Int, ?maxlen : Int, ?driverdata : Dynamic) : Bool;
  61. public function bindParam(parameter : Dynamic, variable : Dynamic, ?data_type : Int, ?length : Int, ?driver_options : Dynamic) : Bool;
  62. public function bindValue(parameter : Dynamic, value : Dynamic, ?data_type : Int) : Bool;
  63. public function closeCursor() : Bool;
  64. public function columnCount() : Int;
  65. public function debugDumpParams() : Bool;
  66. public function errorCode() : String;
  67. public function errorInfo() : NativeArray;
  68. public function execute(input_parameters : NativeArray) : Bool;
  69. public function fetch(?fetch_style : Int = 4, ?cursor_orientation : Int = 0, ?cursor_offset : Int = 0) : Dynamic;
  70. public function fetchAll(?fetch_style : Int) : NativeArray;
  71. public function fetchColumn(?column_number : Int = 0) : String;
  72. public function fetchObject(?class_name : String, ?ctor_args : NativeArray) : Dynamic;
  73. public function getAttribute(attribute : Int) : Dynamic;
  74. public function getColumnMeta(column : Int) : NativeArray;
  75. public function nextRowset() : Bool;
  76. public function rowCount() : Int;
  77. public function setAttribute(attribute : Int, value : Dynamic) : Bool;
  78. public function setFetchMode(mode : Int, ?fetch : Dynamic, ?ctorargs : NativeArray) : Bool;
  79. }
  80. private class PDOConnection implements Connection {
  81. var pdo : PDOClass;
  82. var dbname : String;
  83. public function new(dsn : String, ?user : String, ?password : String, ?options : Dynamic) {
  84. if(null == options)
  85. pdo = untyped __call__("new PDO", dsn, user, password);
  86. else
  87. {
  88. var arr : NativeArray = untyped __call__("array");
  89. for (key in Reflect.fields(options))
  90. arr[untyped key] = Reflect.field(options, key);
  91. pdo = untyped __call__("new PDO", dsn, user, password, arr);
  92. }
  93. dbname = dsn.split(':').shift();
  94. }
  95. public function close() {
  96. pdo = null;
  97. untyped __call__("unset", pdo);
  98. }
  99. public function request( s : String ) : ResultSet {
  100. var result = pdo.query(s, untyped __php__("PDO::PARAM_STR"));
  101. if(untyped __physeq__(result, false))
  102. {
  103. var info = Lib.toHaxeArray(pdo.errorInfo());
  104. throw "Error while executing " + s + " (" + info[2] + ")";
  105. }
  106. var db = dbname.toLowerCase();
  107. switch(db)
  108. {
  109. case "sqlite":
  110. return new AllResultSet(result, new DBNativeStrategy(db));
  111. default: // mysql
  112. return new PDOResultSet(result, new PHPNativeStrategy());
  113. }
  114. }
  115. public function escape( s : String ) {
  116. var output = pdo.quote(s);
  117. return output.length > 2 ? output.substr(1, output.length-2) : output;
  118. }
  119. public function quote( s : String ) {
  120. if( s.indexOf("\000") >= 0 )
  121. return "x'"+base16_encode(s)+"'";
  122. return pdo.quote(s);
  123. }
  124. public function addValue( s : StringBuf, v : Dynamic ) {
  125. if( untyped __call__("is_int", v) || __call__("is_null", v))
  126. s.add(v);
  127. else if( untyped __call__("is_bool", v) )
  128. s.add(if( v ) 1 else 0);
  129. else
  130. s.add(quote(Std.string(v)));
  131. }
  132. public function lastInsertId() {
  133. return cast(Std.parseInt(pdo.lastInsertId()), Int);
  134. }
  135. public function dbName() {
  136. return dbname;
  137. }
  138. public function startTransaction() {
  139. pdo.beginTransaction();
  140. }
  141. public function commit() {
  142. pdo.commit();
  143. }
  144. public function rollback() {
  145. pdo.rollBack();
  146. }
  147. function base16_encode(str : String) {
  148. str = untyped __call__("unpack", "H"+(2 * str.length), str);
  149. str = untyped __call__("chunk_split", untyped str[1]);
  150. return str;
  151. }
  152. }
  153. private class TypeStrategy {
  154. public function new() {
  155. }
  156. public function map(data : NativeArray) : Dynamic
  157. {
  158. return throw "must override";
  159. }
  160. public static function convert(v : String, type : String) : Dynamic {
  161. if (v == null) return v;
  162. switch(type) {
  163. case "bool":
  164. return untyped __call__("(bool)", v);
  165. case "int":
  166. return untyped __call__("intval", v);
  167. case "float":
  168. return untyped __call__("floatval", v);
  169. case "date":
  170. return Date.fromString(v);
  171. default:
  172. return v;
  173. }
  174. }
  175. }
  176. private class PHPNativeStrategy extends TypeStrategy {
  177. static inline var KEY = "native_type";
  178. override function map(data : NativeArray) : Dynamic {
  179. if (!untyped __call__("isset", data[KEY])) {
  180. if (untyped __call__("isset", data["precision"])) {
  181. // if (untyped __call__("isset", data["len"]) && data["len"] == 1)
  182. // return "bool"
  183. // else
  184. return "int";
  185. } else
  186. return "string";
  187. }
  188. var type : String = untyped data[KEY];
  189. type = type.toLowerCase();
  190. switch(type)
  191. {
  192. case "float", "decimal", "double", "newdecimal":
  193. return "float";
  194. case "date", "datetime":
  195. return "date";
  196. case "bool":
  197. return "bool";
  198. case "int", "int24", "int32", "long", "longlong", "short":
  199. return "int";
  200. default:
  201. return "string";
  202. }
  203. }
  204. }
  205. private class DBNativeStrategy extends PHPNativeStrategy {
  206. static inline var SUFFIX = ":decl_type";
  207. var dbname : String;
  208. var key : String;
  209. public function new(dbname : String)
  210. {
  211. super();
  212. this.dbname = dbname.toLowerCase();
  213. this.key = dbname + SUFFIX;
  214. }
  215. override function map(data : NativeArray) : Dynamic {
  216. if (!untyped __call__("isset", data[key]))
  217. return super.map(data);
  218. var type : String = untyped data[key];
  219. type = type.toLowerCase();
  220. switch(type)
  221. {
  222. case "real":
  223. return "float";
  224. case "integer":
  225. return "int";
  226. default:
  227. return "string";
  228. }
  229. }
  230. }
  231. private class BaseResultSet implements ResultSet {
  232. var pdo : PDOStatement;
  233. var typeStrategy : TypeStrategy;
  234. var _fields : Int;
  235. var _columnNames : Array<String>;
  236. var _columnTypes : Array<String>;
  237. public var length(get, null) : Int;
  238. public var nfields(get, null) : Int;
  239. public function new(pdo : PDOStatement, typeStrategy : TypeStrategy)
  240. {
  241. this.pdo = pdo;
  242. this.typeStrategy = typeStrategy;
  243. this._fields = pdo.columnCount();
  244. this._columnNames = [];
  245. this._columnTypes = [];
  246. feedColumns();
  247. }
  248. private function feedColumns() {
  249. for (i in 0..._fields) {
  250. var data = pdo.getColumnMeta(i);
  251. _columnNames.push(data[untyped 'name']);
  252. _columnTypes.push(typeStrategy.map(data));
  253. }
  254. }
  255. public function getFloatResult(index : Int) : Float {
  256. return untyped __call__("floatval", getResult(index));
  257. }
  258. public function getIntResult(index : Int) : Int {
  259. return untyped __call__("intval", getResult(index));
  260. }
  261. public function getResult(index : Int) : String {
  262. return throw "must override";
  263. }
  264. public function hasNext() : Bool {
  265. return throw "must override";
  266. }
  267. function get_length() : Int {
  268. return throw "must override";
  269. }
  270. function nextRow() : NativeArray {
  271. return throw "must override";
  272. }
  273. public function next() : Dynamic {
  274. var row = nextRow();
  275. var o : Dynamic = { };
  276. for (i in 0..._fields)
  277. Reflect.setField(o, _columnNames[i], TypeStrategy.convert(row[i], _columnTypes[i]));
  278. return o;
  279. }
  280. function get_nfields() : Int {
  281. return _fields;
  282. }
  283. public function results() : List<Dynamic>
  284. {
  285. var list = new List();
  286. while (hasNext())
  287. list.add(next());
  288. return list;
  289. }
  290. public function getFieldsNames() : Array<String> {
  291. return throw "Not implemented";
  292. }
  293. }
  294. private class AllResultSet extends BaseResultSet {
  295. var all : NativeArray;
  296. var pos : Int;
  297. var _length : Int;
  298. public function new(pdo : PDOStatement, typeStrategy : TypeStrategy)
  299. {
  300. super(pdo, typeStrategy);
  301. this.all = pdo.fetchAll(untyped __php__("PDO::FETCH_NUM"));
  302. this.pos = 0;
  303. this._length = untyped __call__("count", all);
  304. }
  305. override function getResult(index : Int) : String {
  306. untyped if(__call__("isset", all[0]) && __call__("isset", all[0][index]))
  307. return all[0][index];
  308. else
  309. return null;
  310. }
  311. override function hasNext() : Bool {
  312. return pos < _length;
  313. }
  314. override function get_length() : Int {
  315. return _length;
  316. }
  317. override function nextRow() : NativeArray {
  318. return all[pos++];
  319. }
  320. }
  321. private class PDOResultSet extends BaseResultSet {
  322. private var cache : NativeArray;
  323. public function new(pdo : PDOStatement, typeStrategy : TypeStrategy)
  324. {
  325. super(pdo, typeStrategy);
  326. }
  327. override function getResult(index : Int) : String {
  328. if (!hasNext())
  329. return null;
  330. return cache[index];
  331. }
  332. override function hasNext() {
  333. if(untyped __physeq__(null, cache))
  334. cacheRow();
  335. return (untyped cache);
  336. }
  337. override function get_length() {
  338. if (untyped __physeq__(pdo, false))
  339. return 0;
  340. return pdo.rowCount();
  341. }
  342. private function cacheRow() {
  343. cache = untyped pdo.fetch(__php__("PDO::FETCH_NUM"), __php__("PDO::FETCH_ORI_NEXT"));
  344. }
  345. override function nextRow()
  346. {
  347. if (!hasNext())
  348. return null;
  349. else {
  350. var v = cache;
  351. cache = null;
  352. return v;
  353. }
  354. }
  355. }