PDO.hx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. /*
  2. * Copyright (C)2005-2017 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. switch(dbname.toLowerCase())
  95. {
  96. case "sqlite":
  97. dbname = "SQLite";
  98. case "mysql":
  99. dbname = "MySQL";
  100. }
  101. }
  102. public function close() {
  103. pdo = null;
  104. untyped __call__("unset", pdo);
  105. }
  106. public function request( s : String ) : ResultSet {
  107. var result = pdo.query(s, untyped __php__("PDO::PARAM_STR"));
  108. if(untyped __physeq__(result, false))
  109. {
  110. var info = Lib.toHaxeArray(pdo.errorInfo());
  111. throw "Error while executing " + s + " (" + info[2] + ")";
  112. }
  113. var db = dbname.toLowerCase();
  114. switch(db)
  115. {
  116. case "sqlite":
  117. return new AllResultSet(result, new DBNativeStrategy(db));
  118. default: // mysql
  119. return new PDOResultSet(result, new PHPNativeStrategy());
  120. }
  121. }
  122. public function escape( s : String ) {
  123. var output = pdo.quote(s);
  124. return output.length > 2 ? output.substr(1, output.length-2) : output;
  125. }
  126. public function quote( s : String ) {
  127. if( s.indexOf("\000") >= 0 )
  128. return "x'"+untyped __call__('bin2hex', s)+"'";
  129. return pdo.quote(s);
  130. }
  131. public function addValue( s : StringBuf, v : Dynamic ) {
  132. if( untyped __call__("is_int", v) || __call__("is_null", v))
  133. s.add(v);
  134. else if( untyped __call__("is_bool", v) )
  135. s.add(if( v ) 1 else 0);
  136. else
  137. s.add(quote(Std.string(v)));
  138. }
  139. public function lastInsertId() {
  140. return cast(Std.parseInt(pdo.lastInsertId()), Int);
  141. }
  142. public function dbName() {
  143. return dbname;
  144. }
  145. public function startTransaction() {
  146. pdo.beginTransaction();
  147. }
  148. public function commit() {
  149. pdo.commit();
  150. }
  151. public function rollback() {
  152. pdo.rollBack();
  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. case "blob":
  174. return haxe.io.Bytes.ofString(v);
  175. default:
  176. return v;
  177. }
  178. }
  179. }
  180. private class PHPNativeStrategy extends TypeStrategy {
  181. static inline var KEY = "native_type";
  182. override function map(data : NativeArray) : Dynamic {
  183. if (!untyped __call__("isset", data[KEY])) {
  184. if (untyped __call__("isset", data["precision"])) {
  185. // if (untyped __call__("isset", data["len"]) && data["len"] == 1)
  186. // return "bool"
  187. // else
  188. return "int";
  189. } else
  190. return "string";
  191. }
  192. var pdo_type_str:Int = untyped __php__("PDO::PARAM_STR");
  193. var pdo_type : Int = untyped data["pdo_type"];
  194. var type : String = untyped data[KEY];
  195. type = type.toLowerCase();
  196. switch(type)
  197. {
  198. case "float", "decimal", "double", "newdecimal":
  199. return "float";
  200. case "date", "datetime", "timestamp":
  201. return "date";
  202. case "bool", "tinyint(1)":
  203. return "bool";
  204. case "int", "int24", "int32", "long", "longlong", "short", "tiny":
  205. return "int";
  206. case "blob" if (pdo_type == pdo_type_str):
  207. return "string";
  208. case "blob":
  209. return "blob";
  210. default:
  211. return "string";
  212. }
  213. }
  214. }
  215. private class DBNativeStrategy extends PHPNativeStrategy {
  216. static inline var SUFFIX = ":decl_type";
  217. var dbname : String;
  218. var key : String;
  219. public function new(dbname : String)
  220. {
  221. super();
  222. this.dbname = dbname.toLowerCase();
  223. this.key = dbname + SUFFIX;
  224. }
  225. override function map(data : NativeArray) : Dynamic {
  226. if (!untyped __call__("isset", data[key]))
  227. return super.map(data);
  228. var type : String = untyped data[key];
  229. type = type.toLowerCase();
  230. switch(type)
  231. {
  232. case "real":
  233. return "float";
  234. case "integer":
  235. return "int";
  236. default:
  237. return "string";
  238. }
  239. }
  240. }
  241. private class BaseResultSet implements ResultSet {
  242. var pdo : PDOStatement;
  243. var typeStrategy : TypeStrategy;
  244. var _fields : Int;
  245. var _columnNames : Array<String>;
  246. var _columnTypes : Array<String>;
  247. public var length(get, null) : Int;
  248. public var nfields(get, null) : Int;
  249. public function new(pdo : PDOStatement, typeStrategy : TypeStrategy)
  250. {
  251. this.pdo = pdo;
  252. this.typeStrategy = typeStrategy;
  253. this._fields = pdo.columnCount();
  254. this._columnNames = [];
  255. this._columnTypes = [];
  256. feedColumns();
  257. }
  258. private function feedColumns() {
  259. for (i in 0..._fields) {
  260. var data = pdo.getColumnMeta(i);
  261. _columnNames.push(data[untyped 'name']);
  262. _columnTypes.push(typeStrategy.map(data));
  263. }
  264. }
  265. public function getFloatResult(index : Int) : Float {
  266. return untyped __call__("floatval", getResult(index));
  267. }
  268. public function getIntResult(index : Int) : Int {
  269. return untyped __call__("intval", getResult(index));
  270. }
  271. public function getResult(index : Int) : String {
  272. return throw "must override";
  273. }
  274. public function hasNext() : Bool {
  275. return throw "must override";
  276. }
  277. function get_length() : Int {
  278. return throw "must override";
  279. }
  280. function nextRow() : NativeArray {
  281. return throw "must override";
  282. }
  283. public function next() : Dynamic {
  284. var row = nextRow();
  285. var o : Dynamic = { };
  286. for (i in 0..._fields)
  287. Reflect.setField(o, _columnNames[i], TypeStrategy.convert(row[i], _columnTypes[i]));
  288. return o;
  289. }
  290. function get_nfields() : Int {
  291. return _fields;
  292. }
  293. public function results() : List<Dynamic>
  294. {
  295. var list = new List();
  296. while (hasNext())
  297. list.add(next());
  298. return list;
  299. }
  300. public function getFieldsNames() : Array<String> {
  301. return throw "Not implemented";
  302. }
  303. }
  304. private class AllResultSet extends BaseResultSet {
  305. var all : NativeArray;
  306. var pos : Int;
  307. var _length : Int;
  308. public function new(pdo : PDOStatement, typeStrategy : TypeStrategy)
  309. {
  310. super(pdo, typeStrategy);
  311. this.all = pdo.fetchAll(untyped __php__("PDO::FETCH_NUM"));
  312. this.pos = 0;
  313. this._length = untyped __call__("count", all);
  314. }
  315. override function getResult(index : Int) : String {
  316. untyped if(__call__("isset", all[0]) && __call__("isset", all[0][index]))
  317. return all[0][index];
  318. else
  319. return null;
  320. }
  321. override function hasNext() : Bool {
  322. return pos < _length;
  323. }
  324. override function get_length() : Int {
  325. return _length;
  326. }
  327. override function nextRow() : NativeArray {
  328. return all[pos++];
  329. }
  330. }
  331. private class PDOResultSet extends BaseResultSet {
  332. private var cache : NativeArray;
  333. public function new(pdo : PDOStatement, typeStrategy : TypeStrategy)
  334. {
  335. super(pdo, typeStrategy);
  336. }
  337. override function getResult(index : Int) : String {
  338. if (!hasNext())
  339. return null;
  340. return cache[index];
  341. }
  342. override function hasNext() {
  343. if(untyped __physeq__(null, cache))
  344. cacheRow();
  345. return (untyped cache);
  346. }
  347. override function get_length() {
  348. if (untyped __physeq__(pdo, false))
  349. return 0;
  350. return pdo.rowCount();
  351. }
  352. private function cacheRow() {
  353. cache = untyped pdo.fetch(__php__("PDO::FETCH_NUM"), __php__("PDO::FETCH_ORI_NEXT"));
  354. }
  355. override function nextRow()
  356. {
  357. if (!hasNext())
  358. return null;
  359. else {
  360. var v = cache;
  361. cache = null;
  362. return v;
  363. }
  364. }
  365. }