PDO.hx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /*
  2. * Copyright (c) 2005, The haXe Project Contributors
  3. * All rights reserved.
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are met:
  6. *
  7. * - Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * - Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. *
  13. * THIS SOFTWARE IS PROVIDED BY THE HAXE PROJECT CONTRIBUTORS "AS IS" AND ANY
  14. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  15. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  16. * DISCLAIMED. IN NO EVENT SHALL THE HAXE PROJECT CONTRIBUTORS BE LIABLE FOR
  17. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  18. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  19. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  20. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  21. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  22. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  23. * DAMAGE.
  24. */
  25. package php.db;
  26. import php.NativeArray;
  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. import php.Lib;
  81. import php.Sys;
  82. private class PDOConnection implements Connection {
  83. var pdo : PDOClass;
  84. var dbname : String;
  85. public function new(dsn : String, ?user : String, ?password : String, ?options : Dynamic) {
  86. if(null == options)
  87. pdo = untyped __call__("new PDO", dsn, user, password);
  88. else
  89. {
  90. var arr : NativeArray = untyped __call__("array");
  91. for (key in Reflect.fields(options))
  92. arr[untyped key] = Reflect.field(options, key);
  93. pdo = untyped __call__("new PDO", dsn, user, password, arr);
  94. }
  95. dbname = dsn.split(':').shift();
  96. }
  97. public function close() {
  98. pdo = null;
  99. untyped __call__("unset", pdo);
  100. }
  101. public function request( s : String ) : php.db.ResultSet {
  102. var result = pdo.query(s, untyped __php__("PDO::PARAM_STR"));
  103. if(untyped __physeq__(result, false))
  104. {
  105. var info = Lib.toHaxeArray(pdo.errorInfo());
  106. throw "Error while executing " + s + " (" + info[2] + ")";
  107. }
  108. var db = dbname.toLowerCase();
  109. switch(db)
  110. {
  111. case "sqlite":
  112. return new AllResultSet(result, new DBNativeStrategy(db));
  113. default: // mysql
  114. return new PDOResultSet(result, new PHPNativeStrategy());
  115. }
  116. }
  117. public function escape( s : String ) {
  118. var output = pdo.quote(s);
  119. return output.length > 2 ? output.substr(1, output.length-2) : output;
  120. }
  121. public function quote( s : String ) {
  122. if( s.indexOf("\000") >= 0 )
  123. return "x'"+base16_encode(s)+"'";
  124. return pdo.quote(s);
  125. }
  126. public function addValue( s : StringBuf, v : Dynamic ) {
  127. if( untyped __call__("is_int", v) || __call__("is_null", v))
  128. s.add(v);
  129. else if( untyped __call__("is_bool", v) )
  130. s.add(if( v ) 1 else 0);
  131. else
  132. s.add(quote(Std.string(v)));
  133. }
  134. public function lastInsertId() {
  135. return cast(Std.parseInt(pdo.lastInsertId()), Int);
  136. }
  137. public function dbName() {
  138. return dbname;
  139. }
  140. public function startTransaction() {
  141. pdo.beginTransaction();
  142. }
  143. public function commit() {
  144. pdo.commit();
  145. }
  146. public function rollback() {
  147. pdo.rollBack();
  148. }
  149. function base16_encode(str : String) {
  150. str = untyped __call__("unpack", "H"+(2 * str.length), str);
  151. str = untyped __call__("chunk_split", untyped str[1]);
  152. return str;
  153. }
  154. }
  155. private class TypeStrategy {
  156. public function new() {
  157. }
  158. public function map(data : NativeArray) : Dynamic
  159. {
  160. return throw "must override";
  161. }
  162. public static function convert(v : String, type : String) : Dynamic {
  163. if (v == null) return v;
  164. switch(type) {
  165. case "bool":
  166. return untyped __call__("(bool)", v);
  167. case "int":
  168. return untyped __call__("intval", v);
  169. case "float":
  170. return untyped __call__("floatval", v);
  171. case "date":
  172. return Date.fromString(v);
  173. default:
  174. return v;
  175. }
  176. }
  177. }
  178. private class PHPNativeStrategy extends TypeStrategy {
  179. static inline var KEY = "native_type";
  180. override function map(data : NativeArray) : Dynamic {
  181. if (!untyped __call__("isset", data[KEY])) {
  182. if (untyped __call__("isset", data["precision"])) {
  183. // if (untyped __call__("isset", data["len"]) && data["len"] == 1)
  184. // return "bool"
  185. // else
  186. return "int";
  187. } else
  188. return "string";
  189. }
  190. var type : String = untyped data[KEY];
  191. type = type.toLowerCase();
  192. switch(type)
  193. {
  194. case "float", "decimal", "double", "newdecimal":
  195. return "float";
  196. case "date", "datetime":
  197. return "date";
  198. case "bool":
  199. return "bool";
  200. case "int", "int24", "int32", "long", "longlong", "short":
  201. return "int";
  202. default:
  203. return "string";
  204. }
  205. }
  206. }
  207. private class DBNativeStrategy extends PHPNativeStrategy {
  208. static inline var SUFFIX = ":decl_type";
  209. var dbname : String;
  210. var key : String;
  211. public function new(dbname : String)
  212. {
  213. super();
  214. this.dbname = dbname.toLowerCase();
  215. this.key = dbname + SUFFIX;
  216. }
  217. override function map(data : NativeArray) : Dynamic {
  218. if (!untyped __call__("isset", data[key]))
  219. return super.map(data);
  220. var type : String = untyped data[key];
  221. type = type.toLowerCase();
  222. switch(type)
  223. {
  224. case "real":
  225. return "float";
  226. case "integer":
  227. return "int";
  228. default:
  229. return "string";
  230. }
  231. }
  232. }
  233. private class BaseResultSet implements php.db.ResultSet {
  234. var pdo : PDOStatement;
  235. var typeStrategy : TypeStrategy;
  236. var _fields : Int;
  237. var _columnNames : Array<String>;
  238. var _columnTypes : Array<String>;
  239. public var length(getLength, null) : Int;
  240. public var nfields(getNFields, null) : Int;
  241. public function new(pdo : PDOStatement, typeStrategy : TypeStrategy)
  242. {
  243. this.pdo = pdo;
  244. this.typeStrategy = typeStrategy;
  245. this._fields = pdo.columnCount();
  246. this._columnNames = [];
  247. this._columnTypes = [];
  248. feedColumns();
  249. }
  250. private function feedColumns() {
  251. for (i in 0..._fields) {
  252. var data = pdo.getColumnMeta(i);
  253. _columnNames.push(data[untyped 'name']);
  254. _columnTypes.push(typeStrategy.map(data));
  255. }
  256. }
  257. public function getFloatResult(index : Int) : Float {
  258. return untyped __call__("floatval", getResult(index));
  259. }
  260. public function getIntResult(index : Int) : Int {
  261. return untyped __call__("intval", getResult(index));
  262. }
  263. public function getResult(index : Int) : String {
  264. return throw "must override";
  265. }
  266. public function hasNext() : Bool {
  267. return throw "must override";
  268. }
  269. function getLength() : Int {
  270. return throw "must override";
  271. }
  272. function nextRow() : NativeArray {
  273. return throw "must override";
  274. }
  275. public function next() : Dynamic {
  276. var row = nextRow();
  277. var o : Dynamic = { };
  278. for (i in 0..._fields)
  279. Reflect.setField(o, _columnNames[i], TypeStrategy.convert(row[i], _columnTypes[i]));
  280. return o;
  281. }
  282. function getNFields() : Int {
  283. return _fields;
  284. }
  285. public function results() : List<Dynamic>
  286. {
  287. var list = new List();
  288. while (hasNext())
  289. list.add(next());
  290. return list;
  291. }
  292. public function getFieldsNames() : Array<String> {
  293. return throw "Not implemented";
  294. }
  295. }
  296. private class AllResultSet extends BaseResultSet {
  297. var all : NativeArray;
  298. var pos : Int;
  299. var _length : Int;
  300. public function new(pdo : PDOStatement, typeStrategy : TypeStrategy)
  301. {
  302. super(pdo, typeStrategy);
  303. this.all = pdo.fetchAll(untyped __php__("PDO::FETCH_NUM"));
  304. this.pos = 0;
  305. this._length = untyped __call__("count", all);
  306. }
  307. override function getResult(index : Int) : String {
  308. untyped if(__call__("isset", all[0]) && __call__("isset", all[0][index]))
  309. return all[0][index];
  310. else
  311. return null;
  312. }
  313. override function hasNext() : Bool {
  314. return pos < _length;
  315. }
  316. override function getLength() : Int {
  317. return _length;
  318. }
  319. override function nextRow() : NativeArray {
  320. return all[pos++];
  321. }
  322. }
  323. private class PDOResultSet extends BaseResultSet {
  324. private var cache : NativeArray;
  325. public function new(pdo : PDOStatement, typeStrategy : TypeStrategy)
  326. {
  327. super(pdo, typeStrategy);
  328. }
  329. override function getResult(index : Int) : String {
  330. if (!hasNext())
  331. return null;
  332. return cache[index];
  333. }
  334. override function hasNext() {
  335. if(untyped __physeq__(null, cache))
  336. cacheRow();
  337. return (untyped cache);
  338. }
  339. override function getLength() {
  340. if (untyped __physeq__(pdo, false))
  341. return 0;
  342. return pdo.rowCount();
  343. }
  344. private function cacheRow() {
  345. cache = untyped pdo.fetch(__php__("PDO::FETCH_NUM"), __php__("PDO::FETCH_ORI_NEXT"));
  346. }
  347. override function nextRow()
  348. {
  349. if (!hasNext())
  350. return null;
  351. else {
  352. var v = cache;
  353. cache = null;
  354. return v;
  355. }
  356. }
  357. }