2
0

Mysql.hx 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /*
  2. * Copyright (C)2005-2019 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 sys.db;
  23. import php.*;
  24. import sys.db.*;
  25. import php.db.*;
  26. import php.db.Mysqli_result;
  27. @:coreApi class Mysql {
  28. public static function connect(params:{
  29. host:String,
  30. ?port:Int,
  31. user:String,
  32. pass:String,
  33. ?socket:String,
  34. ?database:String
  35. }):Connection {
  36. return new MysqlConnection(params);
  37. }
  38. }
  39. private class MysqlConnection implements Connection {
  40. var db:Mysqli;
  41. public function new(params:{
  42. host:String,
  43. ?port:Int,
  44. user:String,
  45. pass:String,
  46. ?socket:String,
  47. ?database:String
  48. }):Void {
  49. if (params.port == null)
  50. params.port = Std.parseInt(Global.ini_get('mysqli.default_port'));
  51. if (params.socket == null)
  52. params.socket = Global.ini_get('mysqli.default_socket');
  53. if (params.database == null)
  54. params.database = "";
  55. db = new Mysqli(params.host, params.user, params.pass, params.database, params.port, params.socket);
  56. }
  57. public function request(s:String):ResultSet {
  58. var result = db.query(s);
  59. if (result == false)
  60. throw 'Failed to perform db query: ' + db.error;
  61. if (result == true) {
  62. return new WriteMysqlResultSet(db.affected_rows);
  63. }
  64. return new MysqlResultSet(result);
  65. }
  66. public function close():Void {
  67. db.close();
  68. }
  69. public function escape(s:String):String {
  70. return db.escape_string(s);
  71. }
  72. public function quote(s:String):String {
  73. if (s.indexOf("\000") >= 0)
  74. return "x'" + Global.bin2hex(s) + "'";
  75. return "'" + db.escape_string(s) + "'";
  76. }
  77. public function addValue(s:StringBuf, v:Dynamic):Void {
  78. if (Global.is_int(v) || Global.is_null(v)) {
  79. s.add(v);
  80. } else if (Global.is_bool(v)) {
  81. s.add(v ? 1 : 0);
  82. } else {
  83. s.add(quote(Std.string(v)));
  84. }
  85. }
  86. public function lastInsertId():Int {
  87. return db.insert_id;
  88. }
  89. public function dbName():String {
  90. return 'MySQL';
  91. }
  92. public function startTransaction():Void {
  93. var success = db.begin_transaction();
  94. if (!success)
  95. throw 'Failed to start transaction: ' + db.error;
  96. }
  97. public function commit():Void {
  98. var success = db.commit();
  99. if (!success)
  100. throw 'Failed to commit transaction: ' + db.error;
  101. }
  102. public function rollback():Void {
  103. var success = db.rollback();
  104. if (!success)
  105. throw 'Failed to rollback transaction: ' + db.error;
  106. }
  107. }
  108. private class MysqlResultSet implements ResultSet {
  109. static var hxAnonClassName = Boot.getHxAnon().phpClassName;
  110. public var length(get, null):Int;
  111. public var nfields(get, null):Int;
  112. var result:Mysqli_result;
  113. var fetchedRow:NativeAssocArray<Scalar>;
  114. var fieldsInfo:NativeAssocArray<MysqliFieldInfo>;
  115. public function new(result:Mysqli_result) {
  116. this.result = result;
  117. }
  118. public function hasNext():Bool {
  119. if (fetchedRow == null)
  120. fetchNext();
  121. return fetchedRow != null;
  122. }
  123. public function next():Dynamic {
  124. if (fetchedRow == null)
  125. fetchNext();
  126. return withdrawFetched();
  127. }
  128. public function results():List<Dynamic> {
  129. var list = new List();
  130. result.data_seek(0);
  131. var row = result.fetch_object(hxAnonClassName);
  132. while (row != null) {
  133. row = correctObjectTypes(row);
  134. list.add(row);
  135. row = result.fetch_object(hxAnonClassName);
  136. }
  137. return list;
  138. }
  139. public function getResult(n:Int):String {
  140. if (fetchedRow == null)
  141. fetchNext();
  142. return Global.array_values(fetchedRow)[n];
  143. }
  144. public function getIntResult(n:Int):Int {
  145. return Syntax.int(getResult(n));
  146. }
  147. public function getFloatResult(n:Int):Float {
  148. return Syntax.float(getResult(n));
  149. }
  150. public function getFieldsNames():Null<Array<String>> {
  151. var fields = result.fetch_fields();
  152. return [for (field in fields) field.name];
  153. }
  154. function fetchNext() {
  155. var row = result.fetch_assoc();
  156. if (row != null)
  157. fetchedRow = correctArrayTypes(row);
  158. }
  159. function withdrawFetched():Dynamic {
  160. if (fetchedRow == null)
  161. return null;
  162. var row = fetchedRow;
  163. fetchedRow = null;
  164. return Boot.createAnon(row);
  165. }
  166. function correctArrayTypes(row:NativeAssocArray<String>):NativeAssocArray<Scalar> {
  167. var fieldsInfo = getFieldsInfo();
  168. Syntax.foreach(row, function(field:String, value:String) {
  169. row[field] = correctType(value, fieldsInfo[field].type);
  170. });
  171. return cast row;
  172. }
  173. function correctObjectTypes(row:{}):{} {
  174. var fieldsInfo = getFieldsInfo();
  175. Syntax.foreach(row, function(field:String, value:String) {
  176. value = correctType(value, fieldsInfo[field].type);
  177. Syntax.setField(row, field, value);
  178. });
  179. return row;
  180. }
  181. inline function getFieldsInfo():NativeAssocArray<MysqliFieldInfo> {
  182. if (fieldsInfo == null) {
  183. fieldsInfo = cast Syntax.arrayDecl();
  184. Syntax.foreach(result.fetch_fields(), function(_, info) {
  185. fieldsInfo[info.name] = info;
  186. });
  187. }
  188. return fieldsInfo;
  189. }
  190. function correctType(value:String, type:Int):Scalar {
  191. if (value == null)
  192. return null;
  193. if (type == Const.MYSQLI_TYPE_BIT || type == Const.MYSQLI_TYPE_TINY || type == Const.MYSQLI_TYPE_SHORT || type == Const.MYSQLI_TYPE_LONG
  194. || type == Const.MYSQLI_TYPE_INT24 || type == Const.MYSQLI_TYPE_CHAR) {
  195. return Syntax.int(value);
  196. }
  197. if (type == Const.MYSQLI_TYPE_DECIMAL
  198. || type == Const.MYSQLI_TYPE_NEWDECIMAL
  199. || type == Const.MYSQLI_TYPE_FLOAT
  200. || type == Const.MYSQLI_TYPE_DOUBLE) {
  201. return Syntax.float(value);
  202. }
  203. return value;
  204. }
  205. function get_length()
  206. return result.num_rows;
  207. function get_nfields()
  208. return result.field_count;
  209. }
  210. private class WriteMysqlResultSet extends MysqlResultSet {
  211. var affectedRows:Int = 0;
  212. public function new(affectedRows:Int) {
  213. super(null);
  214. this.affectedRows = affectedRows;
  215. }
  216. override public function hasNext():Bool {
  217. return false;
  218. }
  219. override function fetchNext() {}
  220. override function get_length()
  221. return affectedRows;
  222. override function get_nfields()
  223. return 0;
  224. }