node-mysql-2.0.0~alpha8/0000755000175000017500000000000012140003646013525 5ustar mikemikenode-mysql-2.0.0~alpha8/lib/0000755000175000017500000000000012140003646014273 5ustar mikemikenode-mysql-2.0.0~alpha8/lib/protocol/0000755000175000017500000000000012140003646016134 5ustar mikemikenode-mysql-2.0.0~alpha8/lib/protocol/constants/0000755000175000017500000000000012140003646020150 5ustar mikemikenode-mysql-2.0.0~alpha8/lib/protocol/constants/types.js0000644000175000017500000000303212140003646021650 0ustar mikemike// Manually extracted from mysql-5.5.23/include/mysql_com.h // some more info here: http://dev.mysql.com/doc/refman/5.5/en/c-api-prepared-statement-type-codes.html exports.DECIMAL = 0x00; // aka DECIMAL (http://dev.mysql.com/doc/refman/5.0/en/precision-math-decimal-changes.html) exports.TINY = 0x01; // aka TINYINT, 1 byte exports.SHORT = 0x02; // aka SMALLINT, 2 bytes exports.LONG = 0x03; // aka INT, 4 bytes exports.FLOAT = 0x04; // aka FLOAT, 4-8 bytes exports.DOUBLE = 0x05; // aka DOUBLE, 8 bytes exports.NULL = 0x06; // NULL (used for prepared statements, I think) exports.TIMESTAMP = 0x07; // aka TIMESTAMP exports.LONGLONG = 0x08; // aka BIGINT, 8 bytes exports.INT24 = 0x09; // aka MEDIUMINT, 3 bytes exports.DATE = 0x0a; // aka DATE exports.TIME = 0x0b; // aka TIME exports.DATETIME = 0x0c; // aka DATETIME exports.YEAR = 0x0d; // aka YEAR, 1 byte (don't ask) exports.NEWDATE = 0x0e; // aka ? exports.VARCHAR = 0x0f; // aka VARCHAR (?) exports.BIT = 0x10; // aka BIT, 1-8 byte exports.NEWDECIMAL = 0xf6; // aka DECIMAL exports.ENUM = 0xf7; // aka ENUM exports.SET = 0xf8; // aka SET exports.TINY_BLOB = 0xf9; // aka TINYBLOB, TINYTEXT exports.MEDIUM_BLOB = 0xfa; // aka MEDIUMBLOB, MEDIUMTEXT exports.LONG_BLOB = 0xfb; // aka LONGBLOG, LONGTEXT exports.BLOB = 0xfc; // aka BLOB, TEXT exports.VAR_STRING = 0xfd; // aka VARCHAR, VARBINARY exports.STRING = 0xfe; // aka CHAR, BINARY exports.GEOMETRY = 0xff; // aka GEOMETRY node-mysql-2.0.0~alpha8/lib/protocol/constants/errors.js0000644000175000017500000007526612140003646022042 0ustar mikemike// Generated by generate-error-constants.js, do not modify by hand exports[1000] = 'ER_HASHCHK'; exports[1001] = 'ER_NISAMCHK'; exports[1002] = 'ER_NO'; exports[1003] = 'ER_YES'; exports[1004] = 'ER_CANT_CREATE_FILE'; exports[1005] = 'ER_CANT_CREATE_TABLE'; exports[1006] = 'ER_CANT_CREATE_DB'; exports[1007] = 'ER_DB_CREATE_EXISTS'; exports[1008] = 'ER_DB_DROP_EXISTS'; exports[1009] = 'ER_DB_DROP_DELETE'; exports[1010] = 'ER_DB_DROP_RMDIR'; exports[1011] = 'ER_CANT_DELETE_FILE'; exports[1012] = 'ER_CANT_FIND_SYSTEM_REC'; exports[1013] = 'ER_CANT_GET_STAT'; exports[1014] = 'ER_CANT_GET_WD'; exports[1015] = 'ER_CANT_LOCK'; exports[1016] = 'ER_CANT_OPEN_FILE'; exports[1017] = 'ER_FILE_NOT_FOUND'; exports[1018] = 'ER_CANT_READ_DIR'; exports[1019] = 'ER_CANT_SET_WD'; exports[1020] = 'ER_CHECKREAD'; exports[1021] = 'ER_DISK_FULL'; exports[1022] = 'ER_DUP_KEY'; exports[1023] = 'ER_ERROR_ON_CLOSE'; exports[1024] = 'ER_ERROR_ON_READ'; exports[1025] = 'ER_ERROR_ON_RENAME'; exports[1026] = 'ER_ERROR_ON_WRITE'; exports[1027] = 'ER_FILE_USED'; exports[1028] = 'ER_FILSORT_ABORT'; exports[1029] = 'ER_FORM_NOT_FOUND'; exports[1030] = 'ER_GET_ERRNO'; exports[1031] = 'ER_ILLEGAL_HA'; exports[1032] = 'ER_KEY_NOT_FOUND'; exports[1033] = 'ER_NOT_FORM_FILE'; exports[1034] = 'ER_NOT_KEYFILE'; exports[1035] = 'ER_OLD_KEYFILE'; exports[1036] = 'ER_OPEN_AS_READONLY'; exports[1037] = 'ER_OUTOFMEMORY'; exports[1038] = 'ER_OUT_OF_SORTMEMORY'; exports[1039] = 'ER_UNEXPECTED_EOF'; exports[1040] = 'ER_CON_COUNT_ERROR'; exports[1041] = 'ER_OUT_OF_RESOURCES'; exports[1042] = 'ER_BAD_HOST_ERROR'; exports[1043] = 'ER_HANDSHAKE_ERROR'; exports[1044] = 'ER_DBACCESS_DENIED_ERROR'; exports[1045] = 'ER_ACCESS_DENIED_ERROR'; exports[1046] = 'ER_NO_DB_ERROR'; exports[1047] = 'ER_UNKNOWN_COM_ERROR'; exports[1048] = 'ER_BAD_NULL_ERROR'; exports[1049] = 'ER_BAD_DB_ERROR'; exports[1050] = 'ER_TABLE_EXISTS_ERROR'; exports[1051] = 'ER_BAD_TABLE_ERROR'; exports[1052] = 'ER_NON_UNIQ_ERROR'; exports[1053] = 'ER_SERVER_SHUTDOWN'; exports[1054] = 'ER_BAD_FIELD_ERROR'; exports[1055] = 'ER_WRONG_FIELD_WITH_GROUP'; exports[1056] = 'ER_WRONG_GROUP_FIELD'; exports[1057] = 'ER_WRONG_SUM_SELECT'; exports[1058] = 'ER_WRONG_VALUE_COUNT'; exports[1059] = 'ER_TOO_LONG_IDENT'; exports[1060] = 'ER_DUP_FIELDNAME'; exports[1061] = 'ER_DUP_KEYNAME'; exports[1062] = 'ER_DUP_ENTRY'; exports[1063] = 'ER_WRONG_FIELD_SPEC'; exports[1064] = 'ER_PARSE_ERROR'; exports[1065] = 'ER_EMPTY_QUERY'; exports[1066] = 'ER_NONUNIQ_TABLE'; exports[1067] = 'ER_INVALID_DEFAULT'; exports[1068] = 'ER_MULTIPLE_PRI_KEY'; exports[1069] = 'ER_TOO_MANY_KEYS'; exports[1070] = 'ER_TOO_MANY_KEY_PARTS'; exports[1071] = 'ER_TOO_LONG_KEY'; exports[1072] = 'ER_KEY_COLUMN_DOES_NOT_EXITS'; exports[1073] = 'ER_BLOB_USED_AS_KEY'; exports[1074] = 'ER_TOO_BIG_FIELDLENGTH'; exports[1075] = 'ER_WRONG_AUTO_KEY'; exports[1076] = 'ER_READY'; exports[1077] = 'ER_NORMAL_SHUTDOWN'; exports[1078] = 'ER_GOT_SIGNAL'; exports[1079] = 'ER_SHUTDOWN_COMPLETE'; exports[1080] = 'ER_FORCING_CLOSE'; exports[1081] = 'ER_IPSOCK_ERROR'; exports[1082] = 'ER_NO_SUCH_INDEX'; exports[1083] = 'ER_WRONG_FIELD_TERMINATORS'; exports[1084] = 'ER_BLOBS_AND_NO_TERMINATED'; exports[1085] = 'ER_TEXTFILE_NOT_READABLE'; exports[1086] = 'ER_FILE_EXISTS_ERROR'; exports[1087] = 'ER_LOAD_INFO'; exports[1088] = 'ER_ALTER_INFO'; exports[1089] = 'ER_WRONG_SUB_KEY'; exports[1090] = 'ER_CANT_REMOVE_ALL_FIELDS'; exports[1091] = 'ER_CANT_DROP_FIELD_OR_KEY'; exports[1092] = 'ER_INSERT_INFO'; exports[1093] = 'ER_UPDATE_TABLE_USED'; exports[1094] = 'ER_NO_SUCH_THREAD'; exports[1095] = 'ER_KILL_DENIED_ERROR'; exports[1096] = 'ER_NO_TABLES_USED'; exports[1097] = 'ER_TOO_BIG_SET'; exports[1098] = 'ER_NO_UNIQUE_LOGFILE'; exports[1099] = 'ER_TABLE_NOT_LOCKED_FOR_WRITE'; exports[1100] = 'ER_TABLE_NOT_LOCKED'; exports[1101] = 'ER_BLOB_CANT_HAVE_DEFAULT'; exports[1102] = 'ER_WRONG_DB_NAME'; exports[1103] = 'ER_WRONG_TABLE_NAME'; exports[1104] = 'ER_TOO_BIG_SELECT'; exports[1105] = 'ER_UNKNOWN_ERROR'; exports[1106] = 'ER_UNKNOWN_PROCEDURE'; exports[1107] = 'ER_WRONG_PARAMCOUNT_TO_PROCEDURE'; exports[1108] = 'ER_WRONG_PARAMETERS_TO_PROCEDURE'; exports[1109] = 'ER_UNKNOWN_TABLE'; exports[1110] = 'ER_FIELD_SPECIFIED_TWICE'; exports[1111] = 'ER_INVALID_GROUP_FUNC_USE'; exports[1112] = 'ER_UNSUPPORTED_EXTENSION'; exports[1113] = 'ER_TABLE_MUST_HAVE_COLUMNS'; exports[1114] = 'ER_RECORD_FILE_FULL'; exports[1115] = 'ER_UNKNOWN_CHARACTER_SET'; exports[1116] = 'ER_TOO_MANY_TABLES'; exports[1117] = 'ER_TOO_MANY_FIELDS'; exports[1118] = 'ER_TOO_BIG_ROWSIZE'; exports[1119] = 'ER_STACK_OVERRUN'; exports[1120] = 'ER_WRONG_OUTER_JOIN'; exports[1121] = 'ER_NULL_COLUMN_IN_INDEX'; exports[1122] = 'ER_CANT_FIND_UDF'; exports[1123] = 'ER_CANT_INITIALIZE_UDF'; exports[1124] = 'ER_UDF_NO_PATHS'; exports[1125] = 'ER_UDF_EXISTS'; exports[1126] = 'ER_CANT_OPEN_LIBRARY'; exports[1127] = 'ER_CANT_FIND_DL_ENTRY'; exports[1128] = 'ER_FUNCTION_NOT_DEFINED'; exports[1129] = 'ER_HOST_IS_BLOCKED'; exports[1130] = 'ER_HOST_NOT_PRIVILEGED'; exports[1131] = 'ER_PASSWORD_ANONYMOUS_USER'; exports[1132] = 'ER_PASSWORD_NOT_ALLOWED'; exports[1133] = 'ER_PASSWORD_NO_MATCH'; exports[1134] = 'ER_UPDATE_INFO'; exports[1135] = 'ER_CANT_CREATE_THREAD'; exports[1136] = 'ER_WRONG_VALUE_COUNT_ON_ROW'; exports[1137] = 'ER_CANT_REOPEN_TABLE'; exports[1138] = 'ER_INVALID_USE_OF_NULL'; exports[1139] = 'ER_REGEXP_ERROR'; exports[1140] = 'ER_MIX_OF_GROUP_FUNC_AND_FIELDS'; exports[1141] = 'ER_NONEXISTING_GRANT'; exports[1142] = 'ER_TABLEACCESS_DENIED_ERROR'; exports[1143] = 'ER_COLUMNACCESS_DENIED_ERROR'; exports[1144] = 'ER_ILLEGAL_GRANT_FOR_TABLE'; exports[1145] = 'ER_GRANT_WRONG_HOST_OR_USER'; exports[1146] = 'ER_NO_SUCH_TABLE'; exports[1147] = 'ER_NONEXISTING_TABLE_GRANT'; exports[1148] = 'ER_NOT_ALLOWED_COMMAND'; exports[1149] = 'ER_SYNTAX_ERROR'; exports[1150] = 'ER_DELAYED_CANT_CHANGE_LOCK'; exports[1151] = 'ER_TOO_MANY_DELAYED_THREADS'; exports[1152] = 'ER_ABORTING_CONNECTION'; exports[1153] = 'ER_NET_PACKET_TOO_LARGE'; exports[1154] = 'ER_NET_READ_ERROR_FROM_PIPE'; exports[1155] = 'ER_NET_FCNTL_ERROR'; exports[1156] = 'ER_NET_PACKETS_OUT_OF_ORDER'; exports[1157] = 'ER_NET_UNCOMPRESS_ERROR'; exports[1158] = 'ER_NET_READ_ERROR'; exports[1159] = 'ER_NET_READ_INTERRUPTED'; exports[1160] = 'ER_NET_ERROR_ON_WRITE'; exports[1161] = 'ER_NET_WRITE_INTERRUPTED'; exports[1162] = 'ER_TOO_LONG_STRING'; exports[1163] = 'ER_TABLE_CANT_HANDLE_BLOB'; exports[1164] = 'ER_TABLE_CANT_HANDLE_AUTO_INCREMENT'; exports[1165] = 'ER_DELAYED_INSERT_TABLE_LOCKED'; exports[1166] = 'ER_WRONG_COLUMN_NAME'; exports[1167] = 'ER_WRONG_KEY_COLUMN'; exports[1168] = 'ER_WRONG_MRG_TABLE'; exports[1169] = 'ER_DUP_UNIQUE'; exports[1170] = 'ER_BLOB_KEY_WITHOUT_LENGTH'; exports[1171] = 'ER_PRIMARY_CANT_HAVE_NULL'; exports[1172] = 'ER_TOO_MANY_ROWS'; exports[1173] = 'ER_REQUIRES_PRIMARY_KEY'; exports[1174] = 'ER_NO_RAID_COMPILED'; exports[1175] = 'ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE'; exports[1176] = 'ER_KEY_DOES_NOT_EXITS'; exports[1177] = 'ER_CHECK_NO_SUCH_TABLE'; exports[1178] = 'ER_CHECK_NOT_IMPLEMENTED'; exports[1179] = 'ER_CANT_DO_THIS_DURING_AN_TRANSACTION'; exports[1180] = 'ER_ERROR_DURING_COMMIT'; exports[1181] = 'ER_ERROR_DURING_ROLLBACK'; exports[1182] = 'ER_ERROR_DURING_FLUSH_LOGS'; exports[1183] = 'ER_ERROR_DURING_CHECKPOINT'; exports[1184] = 'ER_NEW_ABORTING_CONNECTION'; exports[1185] = 'ER_DUMP_NOT_IMPLEMENTED'; exports[1186] = 'ER_FLUSH_MASTER_BINLOG_CLOSED'; exports[1187] = 'ER_INDEX_REBUILD'; exports[1188] = 'ER_MASTER'; exports[1189] = 'ER_MASTER_NET_READ'; exports[1190] = 'ER_MASTER_NET_WRITE'; exports[1191] = 'ER_FT_MATCHING_KEY_NOT_FOUND'; exports[1192] = 'ER_LOCK_OR_ACTIVE_TRANSACTION'; exports[1193] = 'ER_UNKNOWN_SYSTEM_VARIABLE'; exports[1194] = 'ER_CRASHED_ON_USAGE'; exports[1195] = 'ER_CRASHED_ON_REPAIR'; exports[1196] = 'ER_WARNING_NOT_COMPLETE_ROLLBACK'; exports[1197] = 'ER_TRANS_CACHE_FULL'; exports[1198] = 'ER_SLAVE_MUST_STOP'; exports[1199] = 'ER_SLAVE_NOT_RUNNING'; exports[1200] = 'ER_BAD_SLAVE'; exports[1201] = 'ER_MASTER_INFO'; exports[1202] = 'ER_SLAVE_THREAD'; exports[1203] = 'ER_TOO_MANY_USER_CONNECTIONS'; exports[1204] = 'ER_SET_CONSTANTS_ONLY'; exports[1205] = 'ER_LOCK_WAIT_TIMEOUT'; exports[1206] = 'ER_LOCK_TABLE_FULL'; exports[1207] = 'ER_READ_ONLY_TRANSACTION'; exports[1208] = 'ER_DROP_DB_WITH_READ_LOCK'; exports[1209] = 'ER_CREATE_DB_WITH_READ_LOCK'; exports[1210] = 'ER_WRONG_ARGUMENTS'; exports[1211] = 'ER_NO_PERMISSION_TO_CREATE_USER'; exports[1212] = 'ER_UNION_TABLES_IN_DIFFERENT_DIR'; exports[1213] = 'ER_LOCK_DEADLOCK'; exports[1214] = 'ER_TABLE_CANT_HANDLE_FT'; exports[1215] = 'ER_CANNOT_ADD_FOREIGN'; exports[1216] = 'ER_NO_REFERENCED_ROW'; exports[1217] = 'ER_ROW_IS_REFERENCED'; exports[1218] = 'ER_CONNECT_TO_MASTER'; exports[1219] = 'ER_QUERY_ON_MASTER'; exports[1220] = 'ER_ERROR_WHEN_EXECUTING_COMMAND'; exports[1221] = 'ER_WRONG_USAGE'; exports[1222] = 'ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT'; exports[1223] = 'ER_CANT_UPDATE_WITH_READLOCK'; exports[1224] = 'ER_MIXING_NOT_ALLOWED'; exports[1225] = 'ER_DUP_ARGUMENT'; exports[1226] = 'ER_USER_LIMIT_REACHED'; exports[1227] = 'ER_SPECIFIC_ACCESS_DENIED_ERROR'; exports[1228] = 'ER_LOCAL_VARIABLE'; exports[1229] = 'ER_GLOBAL_VARIABLE'; exports[1230] = 'ER_NO_DEFAULT'; exports[1231] = 'ER_WRONG_VALUE_FOR_VAR'; exports[1232] = 'ER_WRONG_TYPE_FOR_VAR'; exports[1233] = 'ER_VAR_CANT_BE_READ'; exports[1234] = 'ER_CANT_USE_OPTION_HERE'; exports[1235] = 'ER_NOT_SUPPORTED_YET'; exports[1236] = 'ER_MASTER_FATAL_ERROR_READING_BINLOG'; exports[1237] = 'ER_SLAVE_IGNORED_TABLE'; exports[1238] = 'ER_INCORRECT_GLOBAL_LOCAL_VAR'; exports[1239] = 'ER_WRONG_FK_DEF'; exports[1240] = 'ER_KEY_REF_DO_NOT_MATCH_TABLE_REF'; exports[1241] = 'ER_OPERAND_COLUMNS'; exports[1242] = 'ER_SUBQUERY_NO_'; exports[1243] = 'ER_UNKNOWN_STMT_HANDLER'; exports[1244] = 'ER_CORRUPT_HELP_DB'; exports[1245] = 'ER_CYCLIC_REFERENCE'; exports[1246] = 'ER_AUTO_CONVERT'; exports[1247] = 'ER_ILLEGAL_REFERENCE'; exports[1248] = 'ER_DERIVED_MUST_HAVE_ALIAS'; exports[1249] = 'ER_SELECT_REDUCED'; exports[1250] = 'ER_TABLENAME_NOT_ALLOWED_HERE'; exports[1251] = 'ER_NOT_SUPPORTED_AUTH_MODE'; exports[1252] = 'ER_SPATIAL_CANT_HAVE_NULL'; exports[1253] = 'ER_COLLATION_CHARSET_MISMATCH'; exports[1254] = 'ER_SLAVE_WAS_RUNNING'; exports[1255] = 'ER_SLAVE_WAS_NOT_RUNNING'; exports[1256] = 'ER_TOO_BIG_FOR_UNCOMPRESS'; exports[1257] = 'ER_ZLIB_Z_MEM_ERROR'; exports[1258] = 'ER_ZLIB_Z_BUF_ERROR'; exports[1259] = 'ER_ZLIB_Z_DATA_ERROR'; exports[1260] = 'ER_CUT_VALUE_GROUP_CONCAT'; exports[1261] = 'ER_WARN_TOO_FEW_RECORDS'; exports[1262] = 'ER_WARN_TOO_MANY_RECORDS'; exports[1263] = 'ER_WARN_NULL_TO_NOTNULL'; exports[1264] = 'ER_WARN_DATA_OUT_OF_RANGE'; exports[1265] = 'WARN_DATA_TRUNCATED'; exports[1266] = 'ER_WARN_USING_OTHER_HANDLER'; exports[1267] = 'ER_CANT_AGGREGATE_'; exports[1268] = 'ER_DROP_USER'; exports[1269] = 'ER_REVOKE_GRANTS'; exports[1270] = 'ER_CANT_AGGREGATE_'; exports[1271] = 'ER_CANT_AGGREGATE_NCOLLATIONS'; exports[1272] = 'ER_VARIABLE_IS_NOT_STRUCT'; exports[1273] = 'ER_UNKNOWN_COLLATION'; exports[1274] = 'ER_SLAVE_IGNORED_SSL_PARAMS'; exports[1275] = 'ER_SERVER_IS_IN_SECURE_AUTH_MODE'; exports[1276] = 'ER_WARN_FIELD_RESOLVED'; exports[1277] = 'ER_BAD_SLAVE_UNTIL_COND'; exports[1278] = 'ER_MISSING_SKIP_SLAVE'; exports[1279] = 'ER_UNTIL_COND_IGNORED'; exports[1280] = 'ER_WRONG_NAME_FOR_INDEX'; exports[1281] = 'ER_WRONG_NAME_FOR_CATALOG'; exports[1282] = 'ER_WARN_QC_RESIZE'; exports[1283] = 'ER_BAD_FT_COLUMN'; exports[1284] = 'ER_UNKNOWN_KEY_CACHE'; exports[1285] = 'ER_WARN_HOSTNAME_WONT_WORK'; exports[1286] = 'ER_UNKNOWN_STORAGE_ENGINE'; exports[1287] = 'ER_WARN_DEPRECATED_SYNTAX'; exports[1288] = 'ER_NON_UPDATABLE_TABLE'; exports[1289] = 'ER_FEATURE_DISABLED'; exports[1290] = 'ER_OPTION_PREVENTS_STATEMENT'; exports[1291] = 'ER_DUPLICATED_VALUE_IN_TYPE'; exports[1292] = 'ER_TRUNCATED_WRONG_VALUE'; exports[1293] = 'ER_TOO_MUCH_AUTO_TIMESTAMP_COLS'; exports[1294] = 'ER_INVALID_ON_UPDATE'; exports[1295] = 'ER_UNSUPPORTED_PS'; exports[1296] = 'ER_GET_ERRMSG'; exports[1297] = 'ER_GET_TEMPORARY_ERRMSG'; exports[1298] = 'ER_UNKNOWN_TIME_ZONE'; exports[1299] = 'ER_WARN_INVALID_TIMESTAMP'; exports[1300] = 'ER_INVALID_CHARACTER_STRING'; exports[1301] = 'ER_WARN_ALLOWED_PACKET_OVERFLOWED'; exports[1302] = 'ER_CONFLICTING_DECLARATIONS'; exports[1303] = 'ER_SP_NO_RECURSIVE_CREATE'; exports[1304] = 'ER_SP_ALREADY_EXISTS'; exports[1305] = 'ER_SP_DOES_NOT_EXIST'; exports[1306] = 'ER_SP_DROP_FAILED'; exports[1307] = 'ER_SP_STORE_FAILED'; exports[1308] = 'ER_SP_LILABEL_MISMATCH'; exports[1309] = 'ER_SP_LABEL_REDEFINE'; exports[1310] = 'ER_SP_LABEL_MISMATCH'; exports[1311] = 'ER_SP_UNINIT_VAR'; exports[1312] = 'ER_SP_BADSELECT'; exports[1313] = 'ER_SP_BADRETURN'; exports[1314] = 'ER_SP_BADSTATEMENT'; exports[1315] = 'ER_UPDATE_LOG_DEPRECATED_IGNORED'; exports[1316] = 'ER_UPDATE_LOG_DEPRECATED_TRANSLATED'; exports[1317] = 'ER_QUERY_INTERRUPTED'; exports[1318] = 'ER_SP_WRONG_NO_OF_ARGS'; exports[1319] = 'ER_SP_COND_MISMATCH'; exports[1320] = 'ER_SP_NORETURN'; exports[1321] = 'ER_SP_NORETURNEND'; exports[1322] = 'ER_SP_BAD_CURSOR_QUERY'; exports[1323] = 'ER_SP_BAD_CURSOR_SELECT'; exports[1324] = 'ER_SP_CURSOR_MISMATCH'; exports[1325] = 'ER_SP_CURSOR_ALREADY_OPEN'; exports[1326] = 'ER_SP_CURSOR_NOT_OPEN'; exports[1327] = 'ER_SP_UNDECLARED_VAR'; exports[1328] = 'ER_SP_WRONG_NO_OF_FETCH_ARGS'; exports[1329] = 'ER_SP_FETCH_NO_DATA'; exports[1330] = 'ER_SP_DUP_PARAM'; exports[1331] = 'ER_SP_DUP_VAR'; exports[1332] = 'ER_SP_DUP_COND'; exports[1333] = 'ER_SP_DUP_CURS'; exports[1334] = 'ER_SP_CANT_ALTER'; exports[1335] = 'ER_SP_SUBSELECT_NYI'; exports[1336] = 'ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG'; exports[1337] = 'ER_SP_VARCOND_AFTER_CURSHNDLR'; exports[1338] = 'ER_SP_CURSOR_AFTER_HANDLER'; exports[1339] = 'ER_SP_CASE_NOT_FOUND'; exports[1340] = 'ER_FPARSER_TOO_BIG_FILE'; exports[1341] = 'ER_FPARSER_BAD_HEADER'; exports[1342] = 'ER_FPARSER_EOF_IN_COMMENT'; exports[1343] = 'ER_FPARSER_ERROR_IN_PARAMETER'; exports[1344] = 'ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER'; exports[1345] = 'ER_VIEW_NO_EXPLAIN'; exports[1346] = 'ER_FRM_UNKNOWN_TYPE'; exports[1347] = 'ER_WRONG_OBJECT'; exports[1348] = 'ER_NONUPDATEABLE_COLUMN'; exports[1349] = 'ER_VIEW_SELECT_DERIVED'; exports[1350] = 'ER_VIEW_SELECT_CLAUSE'; exports[1351] = 'ER_VIEW_SELECT_VARIABLE'; exports[1352] = 'ER_VIEW_SELECT_TMPTABLE'; exports[1353] = 'ER_VIEW_WRONG_LIST'; exports[1354] = 'ER_WARN_VIEW_MERGE'; exports[1355] = 'ER_WARN_VIEW_WITHOUT_KEY'; exports[1356] = 'ER_VIEW_INVALID'; exports[1357] = 'ER_SP_NO_DROP_SP'; exports[1358] = 'ER_SP_GOTO_IN_HNDLR'; exports[1359] = 'ER_TRG_ALREADY_EXISTS'; exports[1360] = 'ER_TRG_DOES_NOT_EXIST'; exports[1361] = 'ER_TRG_ON_VIEW_OR_TEMP_TABLE'; exports[1362] = 'ER_TRG_CANT_CHANGE_ROW'; exports[1363] = 'ER_TRG_NO_SUCH_ROW_IN_TRG'; exports[1364] = 'ER_NO_DEFAULT_FOR_FIELD'; exports[1365] = 'ER_DIVISION_BY_ZERO'; exports[1366] = 'ER_TRUNCATED_WRONG_VALUE_FOR_FIELD'; exports[1367] = 'ER_ILLEGAL_VALUE_FOR_TYPE'; exports[1368] = 'ER_VIEW_NONUPD_CHECK'; exports[1369] = 'ER_VIEW_CHECK_FAILED'; exports[1370] = 'ER_PROCACCESS_DENIED_ERROR'; exports[1371] = 'ER_RELAY_LOG_FAIL'; exports[1372] = 'ER_PASSWD_LENGTH'; exports[1373] = 'ER_UNKNOWN_TARGET_BINLOG'; exports[1374] = 'ER_IO_ERR_LOG_INDEX_READ'; exports[1375] = 'ER_BINLOG_PURGE_PROHIBITED'; exports[1376] = 'ER_FSEEK_FAIL'; exports[1377] = 'ER_BINLOG_PURGE_FATAL_ERR'; exports[1378] = 'ER_LOG_IN_USE'; exports[1379] = 'ER_LOG_PURGE_UNKNOWN_ERR'; exports[1380] = 'ER_RELAY_LOG_INIT'; exports[1381] = 'ER_NO_BINARY_LOGGING'; exports[1382] = 'ER_RESERVED_SYNTAX'; exports[1383] = 'ER_WSAS_FAILED'; exports[1384] = 'ER_DIFF_GROUPS_PROC'; exports[1385] = 'ER_NO_GROUP_FOR_PROC'; exports[1386] = 'ER_ORDER_WITH_PROC'; exports[1387] = 'ER_LOGGING_PROHIBIT_CHANGING_OF'; exports[1388] = 'ER_NO_FILE_MAPPING'; exports[1389] = 'ER_WRONG_MAGIC'; exports[1390] = 'ER_PS_MANY_PARAM'; exports[1391] = 'ER_KEY_PART_'; exports[1392] = 'ER_VIEW_CHECKSUM'; exports[1393] = 'ER_VIEW_MULTIUPDATE'; exports[1394] = 'ER_VIEW_NO_INSERT_FIELD_LIST'; exports[1395] = 'ER_VIEW_DELETE_MERGE_VIEW'; exports[1396] = 'ER_CANNOT_USER'; exports[1397] = 'ER_XAER_NOTA'; exports[1398] = 'ER_XAER_INVAL'; exports[1399] = 'ER_XAER_RMFAIL'; exports[1400] = 'ER_XAER_OUTSIDE'; exports[1401] = 'ER_XAER_RMERR'; exports[1402] = 'ER_XA_RBROLLBACK'; exports[1403] = 'ER_NONEXISTING_PROC_GRANT'; exports[1404] = 'ER_PROC_AUTO_GRANT_FAIL'; exports[1405] = 'ER_PROC_AUTO_REVOKE_FAIL'; exports[1406] = 'ER_DATA_TOO_LONG'; exports[1407] = 'ER_SP_BAD_SQLSTATE'; exports[1408] = 'ER_STARTUP'; exports[1409] = 'ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR'; exports[1410] = 'ER_CANT_CREATE_USER_WITH_GRANT'; exports[1411] = 'ER_WRONG_VALUE_FOR_TYPE'; exports[1412] = 'ER_TABLE_DEF_CHANGED'; exports[1413] = 'ER_SP_DUP_HANDLER'; exports[1414] = 'ER_SP_NOT_VAR_ARG'; exports[1415] = 'ER_SP_NO_RETSET'; exports[1416] = 'ER_CANT_CREATE_GEOMETRY_OBJECT'; exports[1417] = 'ER_FAILED_ROUTINE_BREAK_BINLOG'; exports[1418] = 'ER_BINLOG_UNSAFE_ROUTINE'; exports[1419] = 'ER_BINLOG_CREATE_ROUTINE_NEED_SUPER'; exports[1420] = 'ER_EXEC_STMT_WITH_OPEN_CURSOR'; exports[1421] = 'ER_STMT_HAS_NO_OPEN_CURSOR'; exports[1422] = 'ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG'; exports[1423] = 'ER_NO_DEFAULT_FOR_VIEW_FIELD'; exports[1424] = 'ER_SP_NO_RECURSION'; exports[1425] = 'ER_TOO_BIG_SCALE'; exports[1426] = 'ER_TOO_BIG_PRECISION'; exports[1427] = 'ER_M_BIGGER_THAN_D'; exports[1428] = 'ER_WRONG_LOCK_OF_SYSTEM_TABLE'; exports[1429] = 'ER_CONNECT_TO_FOREIGN_DATA_SOURCE'; exports[1430] = 'ER_QUERY_ON_FOREIGN_DATA_SOURCE'; exports[1431] = 'ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST'; exports[1432] = 'ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE'; exports[1433] = 'ER_FOREIGN_DATA_STRING_INVALID'; exports[1434] = 'ER_CANT_CREATE_FEDERATED_TABLE'; exports[1435] = 'ER_TRG_IN_WRONG_SCHEMA'; exports[1436] = 'ER_STACK_OVERRUN_NEED_MORE'; exports[1437] = 'ER_TOO_LONG_BODY'; exports[1438] = 'ER_WARN_CANT_DROP_DEFAULT_KEYCACHE'; exports[1439] = 'ER_TOO_BIG_DISPLAYWIDTH'; exports[1440] = 'ER_XAER_DUPID'; exports[1441] = 'ER_DATETIME_FUNCTION_OVERFLOW'; exports[1442] = 'ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG'; exports[1443] = 'ER_VIEW_PREVENT_UPDATE'; exports[1444] = 'ER_PS_NO_RECURSION'; exports[1445] = 'ER_SP_CANT_SET_AUTOCOMMIT'; exports[1446] = 'ER_MALFORMED_DEFINER'; exports[1447] = 'ER_VIEW_FRM_NO_USER'; exports[1448] = 'ER_VIEW_OTHER_USER'; exports[1449] = 'ER_NO_SUCH_USER'; exports[1450] = 'ER_FORBID_SCHEMA_CHANGE'; exports[1451] = 'ER_ROW_IS_REFERENCED_'; exports[1452] = 'ER_NO_REFERENCED_ROW_'; exports[1453] = 'ER_SP_BAD_VAR_SHADOW'; exports[1454] = 'ER_TRG_NO_DEFINER'; exports[1455] = 'ER_OLD_FILE_FORMAT'; exports[1456] = 'ER_SP_RECURSION_LIMIT'; exports[1457] = 'ER_SP_PROC_TABLE_CORRUPT'; exports[1458] = 'ER_SP_WRONG_NAME'; exports[1459] = 'ER_TABLE_NEEDS_UPGRADE'; exports[1460] = 'ER_SP_NO_AGGREGATE'; exports[1461] = 'ER_MAX_PREPARED_STMT_COUNT_REACHED'; exports[1462] = 'ER_VIEW_RECURSIVE'; exports[1463] = 'ER_NON_GROUPING_FIELD_USED'; exports[1464] = 'ER_TABLE_CANT_HANDLE_SPKEYS'; exports[1465] = 'ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA'; exports[1466] = 'ER_REMOVED_SPACES'; exports[1467] = 'ER_AUTOINC_READ_FAILED'; exports[1468] = 'ER_USERNAME'; exports[1469] = 'ER_HOSTNAME'; exports[1470] = 'ER_WRONG_STRING_LENGTH'; exports[1471] = 'ER_NON_INSERTABLE_TABLE'; exports[1472] = 'ER_ADMIN_WRONG_MRG_TABLE'; exports[1473] = 'ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT'; exports[1474] = 'ER_NAME_BECOMES_EMPTY'; exports[1475] = 'ER_AMBIGUOUS_FIELD_TERM'; exports[1476] = 'ER_FOREIGN_SERVER_EXISTS'; exports[1477] = 'ER_FOREIGN_SERVER_DOESNT_EXIST'; exports[1478] = 'ER_ILLEGAL_HA_CREATE_OPTION'; exports[1479] = 'ER_PARTITION_REQUIRES_VALUES_ERROR'; exports[1480] = 'ER_PARTITION_WRONG_VALUES_ERROR'; exports[1481] = 'ER_PARTITION_MAXVALUE_ERROR'; exports[1482] = 'ER_PARTITION_SUBPARTITION_ERROR'; exports[1483] = 'ER_PARTITION_SUBPART_MIX_ERROR'; exports[1484] = 'ER_PARTITION_WRONG_NO_PART_ERROR'; exports[1485] = 'ER_PARTITION_WRONG_NO_SUBPART_ERROR'; exports[1486] = 'ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR'; exports[1487] = 'ER_NO_CONST_EXPR_IN_RANGE_OR_LIST_ERROR'; exports[1488] = 'ER_FIELD_NOT_FOUND_PART_ERROR'; exports[1489] = 'ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR'; exports[1490] = 'ER_INCONSISTENT_PARTITION_INFO_ERROR'; exports[1491] = 'ER_PARTITION_FUNC_NOT_ALLOWED_ERROR'; exports[1492] = 'ER_PARTITIONS_MUST_BE_DEFINED_ERROR'; exports[1493] = 'ER_RANGE_NOT_INCREASING_ERROR'; exports[1494] = 'ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR'; exports[1495] = 'ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR'; exports[1496] = 'ER_PARTITION_ENTRY_ERROR'; exports[1497] = 'ER_MIX_HANDLER_ERROR'; exports[1498] = 'ER_PARTITION_NOT_DEFINED_ERROR'; exports[1499] = 'ER_TOO_MANY_PARTITIONS_ERROR'; exports[1500] = 'ER_SUBPARTITION_ERROR'; exports[1501] = 'ER_CANT_CREATE_HANDLER_FILE'; exports[1502] = 'ER_BLOB_FIELD_IN_PART_FUNC_ERROR'; exports[1503] = 'ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF'; exports[1504] = 'ER_NO_PARTS_ERROR'; exports[1505] = 'ER_PARTITION_MGMT_ON_NONPARTITIONED'; exports[1506] = 'ER_FOREIGN_KEY_ON_PARTITIONED'; exports[1507] = 'ER_DROP_PARTITION_NON_EXISTENT'; exports[1508] = 'ER_DROP_LAST_PARTITION'; exports[1509] = 'ER_COALESCE_ONLY_ON_HASH_PARTITION'; exports[1510] = 'ER_REORG_HASH_ONLY_ON_SAME_NO'; exports[1511] = 'ER_REORG_NO_PARAM_ERROR'; exports[1512] = 'ER_ONLY_ON_RANGE_LIST_PARTITION'; exports[1513] = 'ER_ADD_PARTITION_SUBPART_ERROR'; exports[1514] = 'ER_ADD_PARTITION_NO_NEW_PARTITION'; exports[1515] = 'ER_COALESCE_PARTITION_NO_PARTITION'; exports[1516] = 'ER_REORG_PARTITION_NOT_EXIST'; exports[1517] = 'ER_SAME_NAME_PARTITION'; exports[1518] = 'ER_NO_BINLOG_ERROR'; exports[1519] = 'ER_CONSECUTIVE_REORG_PARTITIONS'; exports[1520] = 'ER_REORG_OUTSIDE_RANGE'; exports[1521] = 'ER_PARTITION_FUNCTION_FAILURE'; exports[1522] = 'ER_PART_STATE_ERROR'; exports[1523] = 'ER_LIMITED_PART_RANGE'; exports[1524] = 'ER_PLUGIN_IS_NOT_LOADED'; exports[1525] = 'ER_WRONG_VALUE'; exports[1526] = 'ER_NO_PARTITION_FOR_GIVEN_VALUE'; exports[1527] = 'ER_FILEGROUP_OPTION_ONLY_ONCE'; exports[1528] = 'ER_CREATE_FILEGROUP_FAILED'; exports[1529] = 'ER_DROP_FILEGROUP_FAILED'; exports[1530] = 'ER_TABLESPACE_AUTO_EXTEND_ERROR'; exports[1531] = 'ER_WRONG_SIZE_NUMBER'; exports[1532] = 'ER_SIZE_OVERFLOW_ERROR'; exports[1533] = 'ER_ALTER_FILEGROUP_FAILED'; exports[1534] = 'ER_BINLOG_ROW_LOGGING_FAILED'; exports[1535] = 'ER_BINLOG_ROW_WRONG_TABLE_DEF'; exports[1536] = 'ER_BINLOG_ROW_RBR_TO_SBR'; exports[1537] = 'ER_EVENT_ALREADY_EXISTS'; exports[1538] = 'ER_EVENT_STORE_FAILED'; exports[1539] = 'ER_EVENT_DOES_NOT_EXIST'; exports[1540] = 'ER_EVENT_CANT_ALTER'; exports[1541] = 'ER_EVENT_DROP_FAILED'; exports[1542] = 'ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG'; exports[1543] = 'ER_EVENT_ENDS_BEFORE_STARTS'; exports[1544] = 'ER_EVENT_EXEC_TIME_IN_THE_PAST'; exports[1545] = 'ER_EVENT_OPEN_TABLE_FAILED'; exports[1546] = 'ER_EVENT_NEITHER_M_EXPR_NOR_M_AT'; exports[1547] = 'ER_COL_COUNT_DOESNT_MATCH_CORRUPTED'; exports[1548] = 'ER_CANNOT_LOAD_FROM_TABLE'; exports[1549] = 'ER_EVENT_CANNOT_DELETE'; exports[1550] = 'ER_EVENT_COMPILE_ERROR'; exports[1551] = 'ER_EVENT_SAME_NAME'; exports[1552] = 'ER_EVENT_DATA_TOO_LONG'; exports[1553] = 'ER_DROP_INDEX_FK'; exports[1554] = 'ER_WARN_DEPRECATED_SYNTAX_WITH_VER'; exports[1555] = 'ER_CANT_WRITE_LOCK_LOG_TABLE'; exports[1556] = 'ER_CANT_LOCK_LOG_TABLE'; exports[1557] = 'ER_FOREIGN_DUPLICATE_KEY'; exports[1558] = 'ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE'; exports[1559] = 'ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR'; exports[1560] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT'; exports[1561] = 'ER_NDB_CANT_SWITCH_BINLOG_FORMAT'; exports[1562] = 'ER_PARTITION_NO_TEMPORARY'; exports[1563] = 'ER_PARTITION_CONST_DOMAIN_ERROR'; exports[1564] = 'ER_PARTITION_FUNCTION_IS_NOT_ALLOWED'; exports[1565] = 'ER_DDL_LOG_ERROR'; exports[1566] = 'ER_NULL_IN_VALUES_LESS_THAN'; exports[1567] = 'ER_WRONG_PARTITION_NAME'; exports[1568] = 'ER_CANT_CHANGE_TX_ISOLATION'; exports[1569] = 'ER_DUP_ENTRY_AUTOINCREMENT_CASE'; exports[1570] = 'ER_EVENT_MODIFY_QUEUE_ERROR'; exports[1571] = 'ER_EVENT_SET_VAR_ERROR'; exports[1572] = 'ER_PARTITION_MERGE_ERROR'; exports[1573] = 'ER_CANT_ACTIVATE_LOG'; exports[1574] = 'ER_RBR_NOT_AVAILABLE'; exports[1575] = 'ER_BASE'; exports[1576] = 'ER_EVENT_RECURSION_FORBIDDEN'; exports[1577] = 'ER_EVENTS_DB_ERROR'; exports[1578] = 'ER_ONLY_INTEGERS_ALLOWED'; exports[1579] = 'ER_UNSUPORTED_LOG_ENGINE'; exports[1580] = 'ER_BAD_LOG_STATEMENT'; exports[1581] = 'ER_CANT_RENAME_LOG_TABLE'; exports[1582] = 'ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT'; exports[1583] = 'ER_WRONG_PARAMETERS_TO_NATIVE_FCT'; exports[1584] = 'ER_WRONG_PARAMETERS_TO_STORED_FCT'; exports[1585] = 'ER_NATIVE_FCT_NAME_COLLISION'; exports[1586] = 'ER_DUP_ENTRY_WITH_KEY_NAME'; exports[1587] = 'ER_BINLOG_PURGE_EMFILE'; exports[1588] = 'ER_EVENT_CANNOT_CREATE_IN_THE_PAST'; exports[1589] = 'ER_EVENT_CANNOT_ALTER_IN_THE_PAST'; exports[1590] = 'ER_SLAVE_INCIDENT'; exports[1591] = 'ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT'; exports[1592] = 'ER_BINLOG_UNSAFE_STATEMENT'; exports[1593] = 'ER_SLAVE_FATAL_ERROR'; exports[1594] = 'ER_SLAVE_RELAY_LOG_READ_FAILURE'; exports[1595] = 'ER_SLAVE_RELAY_LOG_WRITE_FAILURE'; exports[1596] = 'ER_SLAVE_CREATE_EVENT_FAILURE'; exports[1597] = 'ER_SLAVE_MASTER_COM_FAILURE'; exports[1598] = 'ER_BINLOG_LOGGING_IMPOSSIBLE'; exports[1599] = 'ER_VIEW_NO_CREATION_CTX'; exports[1600] = 'ER_VIEW_INVALID_CREATION_CTX'; exports[1601] = 'ER_SR_INVALID_CREATION_CTX'; exports[1602] = 'ER_TRG_CORRUPTED_FILE'; exports[1603] = 'ER_TRG_NO_CREATION_CTX'; exports[1604] = 'ER_TRG_INVALID_CREATION_CTX'; exports[1605] = 'ER_EVENT_INVALID_CREATION_CTX'; exports[1606] = 'ER_TRG_CANT_OPEN_TABLE'; exports[1607] = 'ER_CANT_CREATE_SROUTINE'; exports[1608] = 'ER_NEVER_USED'; exports[1609] = 'ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT'; exports[1610] = 'ER_SLAVE_CORRUPT_EVENT'; exports[1611] = 'ER_LOAD_DATA_INVALID_COLUMN'; exports[1612] = 'ER_LOG_PURGE_NO_FILE'; exports[1613] = 'ER_XA_RBTIMEOUT'; exports[1614] = 'ER_XA_RBDEADLOCK'; exports[1615] = 'ER_NEED_REPREPARE'; exports[1616] = 'ER_DELAYED_NOT_SUPPORTED'; exports[1617] = 'WARN_NO_MASTER_INFO'; exports[1618] = 'WARN_OPTION_IGNORED'; exports[1619] = 'WARN_PLUGIN_DELETE_BUILTIN'; exports[1620] = 'WARN_PLUGIN_BUSY'; exports[1621] = 'ER_VARIABLE_IS_READONLY'; exports[1622] = 'ER_WARN_ENGINE_TRANSACTION_ROLLBACK'; exports[1623] = 'ER_SLAVE_HEARTBEAT_FAILURE'; exports[1624] = 'ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE'; exports[1625] = 'ER_NDB_REPLICATION_SCHEMA_ERROR'; exports[1626] = 'ER_CONFLICT_FN_PARSE_ERROR'; exports[1627] = 'ER_EXCEPTIONS_WRITE_ERROR'; exports[1628] = 'ER_TOO_LONG_TABLE_COMMENT'; exports[1629] = 'ER_TOO_LONG_FIELD_COMMENT'; exports[1630] = 'ER_FUNC_INEXISTENT_NAME_COLLISION'; exports[1631] = 'ER_DATABASE_NAME'; exports[1632] = 'ER_TABLE_NAME'; exports[1633] = 'ER_PARTITION_NAME'; exports[1634] = 'ER_SUBPARTITION_NAME'; exports[1635] = 'ER_TEMPORARY_NAME'; exports[1636] = 'ER_RENAMED_NAME'; exports[1637] = 'ER_TOO_MANY_CONCURRENT_TRXS'; exports[1638] = 'WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED'; exports[1639] = 'ER_DEBUG_SYNC_TIMEOUT'; exports[1640] = 'ER_DEBUG_SYNC_HIT_LIMIT'; exports[1641] = 'ER_DUP_SIGNAL_SET'; exports[1642] = 'ER_SIGNAL_WARN'; exports[1643] = 'ER_SIGNAL_NOT_FOUND'; exports[1644] = 'ER_SIGNAL_EXCEPTION'; exports[1645] = 'ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER'; exports[1646] = 'ER_SIGNAL_BAD_CONDITION_TYPE'; exports[1647] = 'WARN_COND_ITEM_TRUNCATED'; exports[1648] = 'ER_COND_ITEM_TOO_LONG'; exports[1649] = 'ER_UNKNOWN_LOCALE'; exports[1650] = 'ER_SLAVE_IGNORE_SERVER_IDS'; exports[1651] = 'ER_QUERY_CACHE_DISABLED'; exports[1652] = 'ER_SAME_NAME_PARTITION_FIELD'; exports[1653] = 'ER_PARTITION_COLUMN_LIST_ERROR'; exports[1654] = 'ER_WRONG_TYPE_COLUMN_VALUE_ERROR'; exports[1655] = 'ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR'; exports[1656] = 'ER_MAXVALUE_IN_VALUES_IN'; exports[1657] = 'ER_TOO_MANY_VALUES_ERROR'; exports[1658] = 'ER_ROW_SINGLE_PARTITION_FIELD_ERROR'; exports[1659] = 'ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD'; exports[1660] = 'ER_PARTITION_FIELDS_TOO_LONG'; exports[1661] = 'ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE'; exports[1662] = 'ER_BINLOG_ROW_MODE_AND_STMT_ENGINE'; exports[1663] = 'ER_BINLOG_UNSAFE_AND_STMT_ENGINE'; exports[1664] = 'ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE'; exports[1665] = 'ER_BINLOG_STMT_MODE_AND_ROW_ENGINE'; exports[1666] = 'ER_BINLOG_ROW_INJECTION_AND_STMT_MODE'; exports[1667] = 'ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE'; exports[1668] = 'ER_BINLOG_UNSAFE_LIMIT'; exports[1669] = 'ER_BINLOG_UNSAFE_INSERT_DELAYED'; exports[1670] = 'ER_BINLOG_UNSAFE_SYSTEM_TABLE'; exports[1671] = 'ER_BINLOG_UNSAFE_AUTOINC_COLUMNS'; exports[1672] = 'ER_BINLOG_UNSAFE_UDF'; exports[1673] = 'ER_BINLOG_UNSAFE_SYSTEM_VARIABLE'; exports[1674] = 'ER_BINLOG_UNSAFE_SYSTEM_FUNCTION'; exports[1675] = 'ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS'; exports[1676] = 'ER_MESSAGE_AND_STATEMENT'; exports[1677] = 'ER_SLAVE_CONVERSION_FAILED'; exports[1678] = 'ER_SLAVE_CANT_CREATE_CONVERSION'; exports[1679] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT'; exports[1680] = 'ER_PATH_LENGTH'; exports[1681] = 'ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT'; exports[1682] = 'ER_WRONG_NATIVE_TABLE_STRUCTURE'; exports[1683] = 'ER_WRONG_PERFSCHEMA_USAGE'; exports[1684] = 'ER_WARN_I_S_SKIPPED_TABLE'; exports[1685] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT'; exports[1686] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT'; exports[1687] = 'ER_SPATIAL_MUST_HAVE_GEOM_COL'; exports[1688] = 'ER_TOO_LONG_INDEX_COMMENT'; exports[1689] = 'ER_LOCK_ABORTED'; exports[1690] = 'ER_DATA_OUT_OF_RANGE'; exports[1691] = 'ER_WRONG_SPVAR_TYPE_IN_LIMIT'; exports[1692] = 'ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE'; exports[1693] = 'ER_BINLOG_UNSAFE_MIXED_STATEMENT'; exports[1694] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN'; exports[1695] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN'; exports[1696] = 'ER_FAILED_READ_FROM_PAR_FILE'; exports[1697] = 'ER_VALUES_IS_NOT_INT_TYPE_ERROR'; exports[1698] = 'ER_ACCESS_DENIED_NO_PASSWORD_ERROR'; exports[1699] = 'ER_SET_PASSWORD_AUTH_PLUGIN'; exports[1700] = 'ER_GRANT_PLUGIN_USER_EXISTS'; exports[1701] = 'ER_TRUNCATE_ILLEGAL_FK'; exports[1702] = 'ER_PLUGIN_IS_PERMANENT'; exports[1703] = 'ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN'; exports[1704] = 'ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX'; exports[1705] = 'ER_STMT_CACHE_FULL'; exports[1706] = 'ER_MULTI_UPDATE_KEY_CONFLICT'; exports[1707] = 'ER_TABLE_NEEDS_REBUILD'; exports[1708] = 'WARN_OPTION_BELOW_LIMIT'; exports[1709] = 'ER_INDEX_COLUMN_TOO_LONG'; exports[1710] = 'ER_ERROR_IN_TRIGGER_BODY'; exports[1711] = 'ER_ERROR_IN_UNKNOWN_TRIGGER_BODY'; exports[1712] = 'ER_INDEX_CORRUPT'; exports[1713] = 'ER_UNDO_RECORD_TOO_BIG'; exports[1714] = 'ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT'; exports[1715] = 'ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE'; exports[1716] = 'ER_BINLOG_UNSAFE_REPLACE_SELECT'; exports[1717] = 'ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT'; exports[1718] = 'ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT'; exports[1719] = 'ER_BINLOG_UNSAFE_UPDATE_IGNORE'; exports[1720] = 'ER_PLUGIN_NO_UNINSTALL'; exports[1721] = 'ER_PLUGIN_NO_INSTALL'; exports[1722] = 'ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT'; exports[1723] = 'ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC';node-mysql-2.0.0~alpha8/lib/protocol/constants/client.js0000644000175000017500000000313512140003646021766 0ustar mikemike// Manually extracted from mysql-5.5.23/include/mysql_com.h exports.CLIENT_LONG_PASSWORD = 1; /* new more secure passwords */ exports.CLIENT_FOUND_ROWS = 2; /* Found instead of affected rows */ exports.CLIENT_LONG_FLAG = 4; /* Get all column flags */ exports.CLIENT_CONNECT_WITH_DB = 8; /* One can specify db on connect */ exports.CLIENT_NO_SCHEMA = 16; /* Don't allow database.table.column */ exports.CLIENT_COMPRESS = 32; /* Can use compression protocol */ exports.CLIENT_ODBC = 64; /* Odbc client */ exports.CLIENT_LOCAL_FILES = 128; /* Can use LOAD DATA LOCAL */ exports.CLIENT_IGNORE_SPACE = 256; /* Ignore spaces before '(' */ exports.CLIENT_PROTOCOL_41 = 512; /* New 4.1 protocol */ exports.CLIENT_INTERACTIVE = 1024; /* This is an interactive client */ exports.CLIENT_SSL = 2048; /* Switch to SSL after handshake */ exports.CLIENT_IGNORE_SIGPIPE = 4096; /* IGNORE sigpipes */ exports.CLIENT_TRANSACTIONS = 8192; /* Client knows about transactions */ exports.CLIENT_RESERVED = 16384; /* Old flag for 4.1 protocol */ exports.CLIENT_SECURE_CONNECTION = 32768; /* New 4.1 authentication */ exports.CLIENT_MULTI_STATEMENTS = 65536; /* Enable/disable multi-stmt support */ exports.CLIENT_MULTI_RESULTS = 131072; /* Enable/disable multi-results */ exports.CLIENT_PS_MULTI_RESULTS = 262144; /* Multi-results in PS-protocol */ exports.CLIENT_PLUGIN_AUTH = 524288; /* Client supports plugin authentication */ exports.CLIENT_SSL_VERIFY_SERVER_CERT = 1073741824; exports.CLIENT_REMEMBER_OPTIONS = 2147483648; node-mysql-2.0.0~alpha8/lib/protocol/constants/charsets.js0000644000175000017500000001621112140003646022323 0ustar mikemikeexports.BIG5_CHINESE_CI = 1; exports.LATIN2_CZECH_CS = 2; exports.DEC8_SWEDISH_CI = 3; exports.CP850_GENERAL_CI = 4; exports.LATIN1_GERMAN1_CI = 5; exports.HP8_ENGLISH_CI = 6; exports.KOI8R_GENERAL_CI = 7; exports.LATIN1_SWEDISH_CI = 8; exports.LATIN2_GENERAL_CI = 9; exports.SWE7_SWEDISH_CI = 10; exports.ASCII_GENERAL_CI = 11; exports.UJIS_JAPANESE_CI = 12; exports.SJIS_JAPANESE_CI = 13; exports.CP1251_BULGARIAN_CI = 14; exports.LATIN1_DANISH_CI = 15; exports.HEBREW_GENERAL_CI = 16; exports.TIS620_THAI_CI = 18; exports.EUCKR_KOREAN_CI = 19; exports.LATIN7_ESTONIAN_CS = 20; exports.LATIN2_HUNGARIAN_CI = 21; exports.KOI8U_GENERAL_CI = 22; exports.CP1251_UKRAINIAN_CI = 23; exports.GB2312_CHINESE_CI = 24; exports.GREEK_GENERAL_CI = 25; exports.CP1250_GENERAL_CI = 26; exports.LATIN2_CROATIAN_CI = 27; exports.GBK_CHINESE_CI = 28; exports.CP1257_LITHUANIAN_CI = 29; exports.LATIN5_TURKISH_CI = 30; exports.LATIN1_GERMAN2_CI = 31; exports.ARMSCII8_GENERAL_CI = 32; exports.UTF8_GENERAL_CI = 33; exports.CP1250_CZECH_CS = 34; exports.UCS2_GENERAL_CI = 35; exports.CP866_GENERAL_CI = 36; exports.KEYBCS2_GENERAL_CI = 37; exports.MACCE_GENERAL_CI = 38; exports.MACROMAN_GENERAL_CI = 39; exports.CP852_GENERAL_CI = 40; exports.LATIN7_GENERAL_CI = 41; exports.LATIN7_GENERAL_CS = 42; exports.MACCE_BIN = 43; exports.CP1250_CROATIAN_CI = 44; exports.UTF8MB4_GENERAL_CI = 45; exports.UTF8MB4_BIN = 46; exports.LATIN1_BIN = 47; exports.LATIN1_GENERAL_CI = 48; exports.LATIN1_GENERAL_CS = 49; exports.CP1251_BIN = 50; exports.CP1251_GENERAL_CI = 51; exports.CP1251_GENERAL_CS = 52; exports.MACROMAN_BIN = 53; exports.UTF16_GENERAL_CI = 54; exports.UTF16_BIN = 55; exports.CP1256_GENERAL_CI = 57; exports.CP1257_BIN = 58; exports.CP1257_GENERAL_CI = 59; exports.UTF32_GENERAL_CI = 60; exports.UTF32_BIN = 61; exports.BINARY = 63; exports.ARMSCII8_BIN = 64; exports.ASCII_BIN = 65; exports.CP1250_BIN = 66; exports.CP1256_BIN = 67; exports.CP866_BIN = 68; exports.DEC8_BIN = 69; exports.GREEK_BIN = 70; exports.HEBREW_BIN = 71; exports.HP8_BIN = 72; exports.KEYBCS2_BIN = 73; exports.KOI8R_BIN = 74; exports.KOI8U_BIN = 75; exports.LATIN2_BIN = 77; exports.LATIN5_BIN = 78; exports.LATIN7_BIN = 79; exports.CP850_BIN = 80; exports.CP852_BIN = 81; exports.SWE7_BIN = 82; exports.UTF8_BIN = 83; exports.BIG5_BIN = 84; exports.EUCKR_BIN = 85; exports.GB2312_BIN = 86; exports.GBK_BIN = 87; exports.SJIS_BIN = 88; exports.TIS620_BIN = 89; exports.UCS2_BIN = 90; exports.UJIS_BIN = 91; exports.GEOSTD8_GENERAL_CI = 92; exports.GEOSTD8_BIN = 93; exports.LATIN1_SPANISH_CI = 94; exports.CP932_JAPANESE_CI = 95; exports.CP932_BIN = 96; exports.EUCJPMS_JAPANESE_CI = 97; exports.EUCJPMS_BIN = 98; exports.CP1250_POLISH_CI = 99; exports.UTF16_UNICODE_CI = 101; exports.UTF16_ICELANDIC_CI = 102; exports.UTF16_LATVIAN_CI = 103; exports.UTF16_ROMANIAN_CI = 104; exports.UTF16_SLOVENIAN_CI = 105; exports.UTF16_POLISH_CI = 106; exports.UTF16_ESTONIAN_CI = 107; exports.UTF16_SPANISH_CI = 108; exports.UTF16_SWEDISH_CI = 109; exports.UTF16_TURKISH_CI = 110; exports.UTF16_CZECH_CI = 111; exports.UTF16_DANISH_CI = 112; exports.UTF16_LITHUANIAN_CI = 113; exports.UTF16_SLOVAK_CI = 114; exports.UTF16_SPANISH2_CI = 115; exports.UTF16_ROMAN_CI = 116; exports.UTF16_PERSIAN_CI = 117; exports.UTF16_ESPERANTO_CI = 118; exports.UTF16_HUNGARIAN_CI = 119; exports.UTF16_SINHALA_CI = 120; exports.UCS2_UNICODE_CI = 128; exports.UCS2_ICELANDIC_CI = 129; exports.UCS2_LATVIAN_CI = 130; exports.UCS2_ROMANIAN_CI = 131; exports.UCS2_SLOVENIAN_CI = 132; exports.UCS2_POLISH_CI = 133; exports.UCS2_ESTONIAN_CI = 134; exports.UCS2_SPANISH_CI = 135; exports.UCS2_SWEDISH_CI = 136; exports.UCS2_TURKISH_CI = 137; exports.UCS2_CZECH_CI = 138; exports.UCS2_DANISH_CI = 139; exports.UCS2_LITHUANIAN_CI = 140; exports.UCS2_SLOVAK_CI = 141; exports.UCS2_SPANISH2_CI = 142; exports.UCS2_ROMAN_CI = 143; exports.UCS2_PERSIAN_CI = 144; exports.UCS2_ESPERANTO_CI = 145; exports.UCS2_HUNGARIAN_CI = 146; exports.UCS2_SINHALA_CI = 147; exports.UTF32_UNICODE_CI = 160; exports.UTF32_ICELANDIC_CI = 161; exports.UTF32_LATVIAN_CI = 162; exports.UTF32_ROMANIAN_CI = 163; exports.UTF32_SLOVENIAN_CI = 164; exports.UTF32_POLISH_CI = 165; exports.UTF32_ESTONIAN_CI = 166; exports.UTF32_SPANISH_CI = 167; exports.UTF32_SWEDISH_CI = 168; exports.UTF32_TURKISH_CI = 169; exports.UTF32_CZECH_CI = 170; exports.UTF32_DANISH_CI = 171; exports.UTF32_LITHUANIAN_CI = 172; exports.UTF32_SLOVAK_CI = 173; exports.UTF32_SPANISH2_CI = 174; exports.UTF32_ROMAN_CI = 175; exports.UTF32_PERSIAN_CI = 176; exports.UTF32_ESPERANTO_CI = 177; exports.UTF32_HUNGARIAN_CI = 178; exports.UTF32_SINHALA_CI = 179; exports.UTF8_UNICODE_CI = 192; exports.UTF8_ICELANDIC_CI = 193; exports.UTF8_LATVIAN_CI = 194; exports.UTF8_ROMANIAN_CI = 195; exports.UTF8_SLOVENIAN_CI = 196; exports.UTF8_POLISH_CI = 197; exports.UTF8_ESTONIAN_CI = 198; exports.UTF8_SPANISH_CI = 199; exports.UTF8_SWEDISH_CI = 200; exports.UTF8_TURKISH_CI = 201; exports.UTF8_CZECH_CI = 202; exports.UTF8_DANISH_CI = 203; exports.UTF8_LITHUANIAN_CI = 204; exports.UTF8_SLOVAK_CI = 205; exports.UTF8_SPANISH2_CI = 206; exports.UTF8_ROMAN_CI = 207; exports.UTF8_PERSIAN_CI = 208; exports.UTF8_ESPERANTO_CI = 209; exports.UTF8_HUNGARIAN_CI = 210; exports.UTF8_SINHALA_CI = 211; exports.UTF8MB4_UNICODE_CI = 224; exports.UTF8MB4_ICELANDIC_CI = 225; exports.UTF8MB4_LATVIAN_CI = 226; exports.UTF8MB4_ROMANIAN_CI = 227; exports.UTF8MB4_SLOVENIAN_CI = 228; exports.UTF8MB4_POLISH_CI = 229; exports.UTF8MB4_ESTONIAN_CI = 230; exports.UTF8MB4_SPANISH_CI = 231; exports.UTF8MB4_SWEDISH_CI = 232; exports.UTF8MB4_TURKISH_CI = 233; exports.UTF8MB4_CZECH_CI = 234; exports.UTF8MB4_DANISH_CI = 235; exports.UTF8MB4_LITHUANIAN_CI = 236; exports.UTF8MB4_SLOVAK_CI = 237; exports.UTF8MB4_SPANISH2_CI = 238; exports.UTF8MB4_ROMAN_CI = 239; exports.UTF8MB4_PERSIAN_CI = 240; exports.UTF8MB4_ESPERANTO_CI = 241; exports.UTF8MB4_HUNGARIAN_CI = 242; exports.UTF8MB4_SINHALA_CI = 243;node-mysql-2.0.0~alpha8/lib/protocol/constants/server_status.js0000644000175000017500000000265212140003646023424 0ustar mikemike// Manually extracted from mysql-5.5.23/include/mysql_com.h /** Is raised when a multi-statement transaction has been started, either explicitly, by means of BEGIN or COMMIT AND CHAIN, or implicitly, by the first transactional statement, when autocommit=off. */ exports.SERVER_STATUS_IN_TRANS = 1; exports.SERVER_STATUS_AUTOCOMMIT = 2; /* Server in auto_commit mode */ exports.SERVER_MORE_RESULTS_EXISTS = 8; /* Multi query - next query exists */ exports.SERVER_QUERY_NO_GOOD_INDEX_USED = 16; exports.SERVER_QUERY_NO_INDEX_USED = 32; /** The server was able to fulfill the clients request and opened a read-only non-scrollable cursor for a query. This flag comes in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands. */ exports.SERVER_STATUS_CURSOR_EXISTS = 64; /** This flag is sent when a read-only cursor is exhausted, in reply to COM_STMT_FETCH command. */ exports.SERVER_STATUS_LAST_ROW_SENT = 128; exports.SERVER_STATUS_DB_DROPPED = 256; /* A database was dropped */ exports.SERVER_STATUS_NO_BACKSLASH_ESCAPES = 512; /** Sent to the client if after a prepared statement reprepare we discovered that the new statement returns a different number of result set columns. */ exports.SERVER_STATUS_METADATA_CHANGED = 1024; exports.SERVER_QUERY_WAS_SLOW = 2048; /** To mark ResultSet containing output parameter values. */ exports.SERVER_PS_OUT_PARAMS = 4096; node-mysql-2.0.0~alpha8/lib/protocol/constants/field_flags.js0000644000175000017500000000205212140003646022744 0ustar mikemike// Manually extracted from mysql-5.5.23/include/mysql_com.h exports.NOT_NULL_FLAG = 1; /* Field can't be NULL */ exports.PRI_KEY_FLAG = 2; /* Field is part of a primary key */ exports.UNIQUE_KEY_FLAG = 4; /* Field is part of a unique key */ exports.MULTIPLE_KEY_FLAG = 8; /* Field is part of a key */ exports.BLOB_FLAG = 16; /* Field is a blob */ exports.UNSIGNED_FLAG = 32; /* Field is unsigned */ exports.ZEROFILL_FLAG = 64; /* Field is zerofill */ exports.BINARY_FLAG = 128; /* Field is binary */ /* The following are only sent to new clients */ exports.ENUM_FLAG = 256; /* field is an enum */ exports.AUTO_INCREMENT_FLAG = 512; /* field is a autoincrement field */ exports.TIMESTAMP_FLAG = 1024; /* Field is a timestamp */ exports.SET_FLAG = 2048; /* field is a set */ exports.NO_DEFAULT_VALUE_FLAG = 4096; /* Field doesn't have default value */ exports.ON_UPDATE_NOW_FLAG = 8192; /* Field is set to NOW on UPDATE */ exports.NUM_FLAG = 32768; /* Field is num (for clients) */ node-mysql-2.0.0~alpha8/lib/protocol/ResultSet.js0000644000175000017500000000035112140003646020423 0ustar mikemikemodule.exports = ResultSet; function ResultSet(resultSetHeaderPacket) { this.resultSetHeaderPacket = resultSetHeaderPacket; this.fieldPackets = []; this.eofPackets = []; this.rows = []; } node-mysql-2.0.0~alpha8/lib/protocol/PacketWriter.js0000644000175000017500000001166612140003646021110 0ustar mikemikevar BIT_16 = Math.pow(2, 16); var BIT_24 = Math.pow(2, 24); // The maximum precision JS Numbers can hold precisely // Don't panic: Good enough to represent byte values up to 8192 TB var IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53); var MAX_PACKET_LENGTH = Math.pow(2, 24) - 1; module.exports = PacketWriter; function PacketWriter() { this._buffer = new Buffer(0); this._offset = 0; } PacketWriter.prototype.toBuffer = function(parser) { var packets = Math.floor(this._buffer.length / MAX_PACKET_LENGTH) + 1; var buffer = this._buffer; this._buffer = new Buffer(this._buffer.length + packets * 4); for (var packet = 0; packet < packets; packet++) { this._offset = packet * (MAX_PACKET_LENGTH + 4); var isLast = (packet + 1 === packets); var packetLength = (isLast) ? buffer.length % MAX_PACKET_LENGTH : MAX_PACKET_LENGTH; var packetNumber = parser.incrementPacketNumber(); this.writeUnsignedNumber(3, packetLength); this.writeUnsignedNumber(1, packetNumber); var start = packet * MAX_PACKET_LENGTH; var end = start + packetLength; this.writeBuffer(buffer.slice(start, end)); } return this._buffer; }; PacketWriter.prototype.writeUnsignedNumber = function(bytes, value) { this._allocate(bytes); for (var i = 0; i < bytes; i++) { this._buffer[this._offset++] = (value >> (i * 8)) & 0xff; } }; PacketWriter.prototype.writeFiller = function(bytes) { this._allocate(bytes); for (var i = 0; i < bytes; i++) { this._buffer[this._offset++] = 0x00; } }; PacketWriter.prototype.writeNullTerminatedString = function(value, encoding) { // Typecast undefined into '' and numbers into strings value = value || ''; value = value + ''; var bytes = Buffer.byteLength(value, encoding || 'utf-8') + 1; this._allocate(bytes); this._buffer.write(value, this._offset, encoding); this._buffer[this._offset + bytes - 1] = 0x00; this._offset += bytes; }; PacketWriter.prototype.writeString = function(value) { // Typecast undefined into '' and numbers into strings value = value || ''; value = value + ''; var bytes = Buffer.byteLength(value, 'utf-8'); this._allocate(bytes); this._buffer.write(value, this._offset, 'utf-8'); this._offset += bytes; }; PacketWriter.prototype.writeBuffer = function(value) { var bytes = value.length; this._allocate(bytes); value.copy(this._buffer, this._offset); this._offset += bytes; }; PacketWriter.prototype.writeLengthCodedNumber = function(value) { if (value === null) { this._allocate(1); this._buffer[this._offset++] = 251; return; } if (value <= 250) { this._allocate(1); this._buffer[this._offset++] = value; return; } if (value > IEEE_754_BINARY_64_PRECISION) { throw new Error( 'writeLengthCodedNumber: JS precision range exceeded, your ' + 'number is > 53 bit: "' + value + '"' ); } if (value <= BIT_16) { this._allocate(3) this._buffer[this._offset++] = 252; } else if (value <= BIT_24) { this._allocate(4) this._buffer[this._offset++] = 253; } else { this._allocate(9); this._buffer[this._offset++] = 254; } // 16 Bit this._buffer[this._offset++] = value & 0xff; this._buffer[this._offset++] = (value >> 8) & 0xff; if (value <= BIT_16) return; // 24 Bit this._buffer[this._offset++] = (value >> 16) & 0xff; if (value <= BIT_24) return; this._buffer[this._offset++] = (value >> 24) & 0xff; // Hack: Get the most significant 32 bit (JS bitwise operators are 32 bit) value = value.toString(2); value = value.substr(0, value.length - 32); value = parseInt(value, 2); this._buffer[this._offset++] = value & 0xff; this._buffer[this._offset++] = (value >> 8) & 0xff; this._buffer[this._offset++] = (value >> 16) & 0xff; // Set last byte to 0, as we can only support 53 bits in JS (see above) this._buffer[this._offset++] = 0; }; PacketWriter.prototype.writeLengthCodedBuffer = function(value) { var bytes = value.length; this.writeLengthCodedNumber(bytes); this.writeBuffer(value); }; PacketWriter.prototype.writeNullTerminatedBuffer = function(value) { this.writeBuffer(value); this.writeFiller(1); // 0x00 terminator }; PacketWriter.prototype.writeLengthCodedString = function(value) { if (value === null) { this.writeLengthCodedNumber(null); return; } value = (value === undefined) ? '' : String(value); var bytes = Buffer.byteLength(value, 'utf-8'); this.writeLengthCodedNumber(bytes); if (!bytes) { return; } this._allocate(bytes); this._buffer.write(value, this._offset, 'utf-8'); this._offset += bytes; }; PacketWriter.prototype._allocate = function(bytes) { if (!this._buffer) { this._buffer = new Buffer(bytes); return; } var bytesRemaining = this._buffer.length - this._offset; if (bytesRemaining >= bytes) { return; } var oldBuffer = this._buffer; this._buffer = new Buffer(oldBuffer.length + bytes); oldBuffer.copy(this._buffer); }; node-mysql-2.0.0~alpha8/lib/protocol/Parser.js0000644000175000017500000002435712140003646017741 0ustar mikemikevar IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53); var MAX_PACKET_LENGTH = Math.pow(2, 24) - 1; var PacketHeader = require('./PacketHeader'); var BigNumber = require("bignumber.js"); module.exports = Parser; function Parser(options) { options = options || {}; this._supportBigNumbers = options.config && options.config.supportBigNumbers; this._buffer = new Buffer(0); this._longPacketBuffers = []; this._offset = 0; this._packetEnd = null; this._packetHeader = null; this._onPacket = options.onPacket || function() {}; this._nextPacketNumber = 0; this._encoding = 'utf-8'; this._paused = false; } Parser.prototype.write = function(buffer) { this.append(buffer); while (true) { if (this._paused) { return; } if (!this._packetHeader) { if (this._bytesRemaining() < 4) { break; } this._packetHeader = new PacketHeader( this.parseUnsignedNumber(3), this.parseUnsignedNumber(1) ); this._trackAndVerifyPacketNumber(this._packetHeader.number); } if (this._bytesRemaining() < this._packetHeader.length) { break; } this._packetEnd = this._offset + this._packetHeader.length; if (this._packetHeader.length === MAX_PACKET_LENGTH) { this._longPacketBuffers.push(this._buffer.slice(this._offset, this._packetEnd)); this._advanceToNextPacket(); continue; } this._combineLongPacketBuffers(); // Try...finally to ensure exception safety. Unfortunately this is costing // us up to ~10% performance in some benchmarks. var hadException = true; try { this._onPacket(this._packetHeader); hadException = false; } finally { this._advanceToNextPacket(); // If we had an exception, the parser while loop will be broken out // of after the finally block. So we need to make sure to re-enter it // to continue parsing any bytes that may already have been received. if (hadException) { process.nextTick(this.write.bind(this)); } } } }; Parser.prototype.append = function(newBuffer) { // If resume() is called, we don't pass a buffer to write() if (!newBuffer) { return; } var oldBuffer = this._buffer; var bytesRemaining = this._bytesRemaining(); var newLength = bytesRemaining + newBuffer.length; var combinedBuffer = (this._offset > newLength) ? oldBuffer.slice(0, newLength) : new Buffer(newLength); oldBuffer.copy(combinedBuffer, 0, this._offset); newBuffer.copy(combinedBuffer, bytesRemaining); this._buffer = combinedBuffer; this._offset = 0; }; Parser.prototype.pause = function() { this._paused = true; }; Parser.prototype.resume = function() { this._paused = false; // nextTick() to avoid entering write() multiple times within the same stack // which would cause problems as write manipulates the state of the object. process.nextTick(this.write.bind(this)); }; Parser.prototype.peak = function() { return this._buffer[this._offset]; }; Parser.prototype.parseUnsignedNumber = function(bytes) { var bytesRead = 0; var value = 0; while (bytesRead < bytes) { var byte = this._buffer[this._offset++]; value += byte * Math.pow(256, bytesRead); bytesRead++; } return value; }; Parser.prototype.parseLengthCodedString = function() { var length = this.parseLengthCodedNumber(); if (length === null) { return null; } return this.parseString(length); }; Parser.prototype.parseLengthCodedBuffer = function() { var length = this.parseLengthCodedNumber(); if (length === null) { return null; } return this.parseBuffer(length); }; Parser.prototype.parseLengthCodedNumber = function() { var bits = this._buffer[this._offset++]; if (bits <= 251) { return (bits === 251) ? null : bits; } var length; var bigNumber = false; var value = 0; if (bits === 252) { length = 2; } else if (bits === 253) { length = 3; } else if (bits === 254) { length = 8; if (this._supportBigNumbers) { if (this._buffer[this._offset + 6] > 31 || this._buffer[this._offset + 7]) { value = new BigNumber(0); bigNumber = true; } } } else { throw new Error('parseLengthCodedNumber: Unexpected first byte: ' + bits); } for (var bytesRead = 0; bytesRead < length; bytesRead++) { bits = this._buffer[this._offset++]; if (bigNumber) { value = value.plus((new BigNumber(256)).pow(bytesRead).times(bits)); } else { value += Math.pow(256, bytesRead) * bits; } } if (bigNumber) { return value.toString(); } if (value >= IEEE_754_BINARY_64_PRECISION) { throw new Error( 'parseLengthCodedNumber: JS precision range exceeded, ' + 'number is >= 53 bit: "' + value + '"' ); } return value; }; Parser.prototype.parseFiller = function(length) { return this.parseBuffer(length); }; Parser.prototype.parseNullTerminatedBuffer = function() { var end = this._nullByteOffset(); var value = this._buffer.slice(this._offset, end); this._offset = end + 1; return value; }; Parser.prototype.parseNullTerminatedString = function() { var end = this._nullByteOffset(); var value = this._buffer.toString(this._encoding, this._offset, end); this._offset = end + 1; return value; }; Parser.prototype._nullByteOffset = function() { var offset = this._offset; while (this._buffer[offset] !== 0x00) { offset++; if (offset >= this._buffer.length) { throw new Error('Offset of null terminated string not found.'); } } return offset; }; Parser.prototype.parsePacketTerminatedString = function() { var length = this._packetEnd - this._offset; return this.parseString(length); }; Parser.prototype.parseBuffer = function(length) { var response = new Buffer(length); this._buffer.copy(response, 0, this._offset, this._offset + length); this._offset += length; return response; }; Parser.prototype.parseString = function(length) { var offset = this._offset; var end = offset + length; var value = this._buffer.toString(this._encoding, offset, end); this._offset = end; return value; }; Parser.prototype.parseGeometryValue = function() { var buffer = this.parseLengthCodedBuffer(); var offset = 4; if (buffer === null) { return null; } function parseGeometry() { var result = null; var byteOrder = buffer.readUInt8(offset); offset += 1; var wkbType = byteOrder? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; switch(wkbType) { case 1: // WKBPoint var x = byteOrder? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; var y = byteOrder? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; result = {x: x, y: y}; break; case 2: // WKBLineString var numPoints = byteOrder? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; result = []; for(var i=numPoints;i>0;i--) { var x = byteOrder? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; var y = byteOrder? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; result.push({x: x, y: y}); } break; case 3: // WKBPolygon var numRings = byteOrder? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; result = []; for(var i=numRings;i>0;i--) { var numPoints = byteOrder? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; var line = []; for(var j=numPoints;j>0;j--) { var x = byteOrder? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; var y = byteOrder? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; line.push({x: x, y: y}); } result.push(line); } break; case 4: // WKBMultiPoint case 5: // WKBMultiLineString case 6: // WKBMultiPolygon case 7: // WKBGeometryCollection var num = byteOrder? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; var result = []; for(var i=num;i>0;i--) { result.push(parseGeometry()); } break; } return result; } return parseGeometry(); }; Parser.prototype.reachedPacketEnd = function() { return this._offset === this._packetEnd; }; Parser.prototype._bytesRemaining = function() { return this._buffer.length - this._offset; }; Parser.prototype._trackAndVerifyPacketNumber = function(number) { if (number !== this._nextPacketNumber) { var err = new Error( 'Packets out of order. Got: ' + number + ' ' + 'Expected: ' + this._nextPacketNumber ); err.code = 'PROTOCOL_PACKETS_OUT_OF_ORDER'; throw err; } this.incrementPacketNumber(); }; Parser.prototype.incrementPacketNumber = function() { var currentPacketNumber = this._nextPacketNumber; this._nextPacketNumber = (this._nextPacketNumber + 1) % 256; return currentPacketNumber; }; Parser.prototype.resetPacketNumber = function() { this._nextPacketNumber = 0; }; Parser.prototype.packetLength = function() { return this._longPacketBuffers.reduce(function(length, buffer) { return length + buffer.length; }, this._packetHeader.length); }; Parser.prototype._combineLongPacketBuffers = function() { if (!this._longPacketBuffers.length) { return; } var trailingPacketBytes = this._buffer.length - this._packetEnd; var length = this._longPacketBuffers.reduce(function(length, buffer) { return length + buffer.length; }, this._bytesRemaining()); var combinedBuffer = new Buffer(length); var offset = this._longPacketBuffers.reduce(function(offset, buffer) { buffer.copy(combinedBuffer, offset); return offset + buffer.length; }, 0); this._buffer.copy(combinedBuffer, offset, this._offset); this._buffer = combinedBuffer; this._longPacketBuffers = []; this._offset = 0; this._packetEnd = this._buffer.length - trailingPacketBytes; }; Parser.prototype._advanceToNextPacket = function() { this._offset = this._packetEnd; this._packetHeader = null; this._packetEnd = null; }; node-mysql-2.0.0~alpha8/lib/protocol/SqlString.js0000644000175000017500000000650712140003646020430 0ustar mikemikevar SqlString = exports; SqlString.escapeId = function (val, forbidQualified) { if (forbidQualified) { return '`' + val.replace(/`/g, '``') + '`'; } return '`' + val.replace(/`/g, '``').replace(/\./g, '`.`') + '`'; }; SqlString.escape = function(val, stringifyObjects, timeZone) { if (val === undefined || val === null) { return 'NULL'; } switch (typeof val) { case 'boolean': return (val) ? 'true' : 'false'; case 'number': return val+''; } if (val instanceof Date) { val = SqlString.dateToString(val, timeZone || "Z"); } if (Buffer.isBuffer(val)) { return SqlString.bufferToString(val); } if (Array.isArray(val)) { return SqlString.arrayToList(val, timeZone); } if (typeof val === 'object') { if (stringifyObjects) { val = val.toString(); } else { return SqlString.objectToValues(val, timeZone); } } val = val.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(s) { switch(s) { case "\0": return "\\0"; case "\n": return "\\n"; case "\r": return "\\r"; case "\b": return "\\b"; case "\t": return "\\t"; case "\x1a": return "\\Z"; default: return "\\"+s; } }); return "'"+val+"'"; }; SqlString.arrayToList = function(array, timeZone) { return array.map(function(v) { if (Array.isArray(v)) return '(' + SqlString.arrayToList(v) + ')'; return SqlString.escape(v, true, timeZone); }).join(', '); }; SqlString.format = function(sql, values, timeZone) { values = [].concat(values); return sql.replace(/\?\??/g, function(match) { if (!values.length) { return match; } if (match == "??") { return SqlString.escapeId(values.shift()); } return SqlString.escape(values.shift(), false, timeZone); }); }; SqlString.dateToString = function(date, timeZone) { var dt = new Date(date); if (timeZone != 'local') { var tz = convertTimezone(timeZone); dt.setTime(dt.getTime() + (dt.getTimezoneOffset() * 60000)); if (tz !== false) { dt.setTime(dt.getTime() + (tz * 60000)); } } var year = dt.getFullYear(); var month = zeroPad(dt.getMonth() + 1); var day = zeroPad(dt.getDate()); var hour = zeroPad(dt.getHours()); var minute = zeroPad(dt.getMinutes()); var second = zeroPad(dt.getSeconds()); return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second; }; SqlString.bufferToString = function(buffer) { var hex = ''; try { hex = buffer.toString('hex'); } catch (err) { // node v0.4.x does not support hex / throws unknown encoding error for (var i = 0; i < buffer.length; i++) { var byte = buffer[i]; hex += zeroPad(byte.toString(16)); } } return "X'" + hex+ "'"; }; SqlString.objectToValues = function(object, timeZone) { var values = []; for (var key in object) { var value = object[key]; if(typeof value === 'function') { continue; } values.push(this.escapeId(key) + ' = ' + SqlString.escape(value, true, timeZone)); } return values.join(', '); }; function zeroPad(number) { return (number < 10) ? '0' + number : number; } function convertTimezone(tz) { if (tz == "Z") return 0; var m = tz.match(/([\+\-\s])(\d\d):?(\d\d)?/); if (m) { return (m[1] == '-' ? -1 : 1) * (parseInt(m[2], 10) + ((m[3] ? parseInt(m[3], 10) : 0) / 60)) * 60; } return false; } node-mysql-2.0.0~alpha8/lib/protocol/sequences/0000755000175000017500000000000012140003646020127 5ustar mikemikenode-mysql-2.0.0~alpha8/lib/protocol/sequences/Handshake.js0000644000175000017500000000407212140003646022356 0ustar mikemikevar Sequence = require('./Sequence'); var Util = require('util'); var Packets = require('../packets'); var Auth = require('../Auth'); module.exports = Handshake; Util.inherits(Handshake, Sequence); function Handshake(config, callback) { Sequence.call(this, callback); this._config = config; this._handshakeInitializationPacket = null; } Handshake.prototype.determinePacket = function(firstByte) { if (firstByte === 0xff) { return Packets.ErrorPacket; } if (!this._handshakeInitializationPacket) { return Packets.HandshakeInitializationPacket; } if (firstByte === 0xfe) { return Packets.UseOldPasswordPacket; } }; Handshake.prototype['HandshakeInitializationPacket'] = function(packet) { this._handshakeInitializationPacket = packet; this._config.protocol41 = packet.protocol41; this.emit('packet', new Packets.ClientAuthenticationPacket({ clientFlags : this._config.clientFlags, maxPacketSize : this._config.maxPacketSize, charsetNumber : this._config.charsetNumber, user : this._config.user, scrambleBuff : (packet.protocol41) ? Auth.token(this._config.password, packet.scrambleBuff()) : Auth.scramble323(packet.scrambleBuff(), this._config.password), database : this._config.database, protocol41 : packet.protocol41 })); }; Handshake.prototype['UseOldPasswordPacket'] = function(packet) { if (!this._config.insecureAuth) { var err = new Error( 'MySQL server is requesting the old and insecure pre-4.1 auth mechanism.' + 'Upgrade the user password or use the {insecureAuth: true} option.' ); err.code = 'HANDSHAKE_INSECURE_AUTH'; err.fatal = true; this.end(err); return; } this.emit('packet', new Packets.OldPasswordPacket({ scrambleBuff : Auth.scramble323(this._handshakeInitializationPacket.scrambleBuff(), this._config.password), })); }; Handshake.prototype['ErrorPacket'] = function(packet) { var err = this._packetToError(packet, true); err.fatal = true; this.end(err); }; node-mysql-2.0.0~alpha8/lib/protocol/sequences/Quit.js0000644000175000017500000000047212140003646021412 0ustar mikemikevar Sequence = require('./Sequence'); var Util = require('util'); var Packets = require('../packets'); module.exports = Quit; Util.inherits(Quit, Sequence); function Quit(callback) { Sequence.call(this, callback); } Quit.prototype.start = function() { this.emit('packet', new Packets.ComQuitPacket); }; node-mysql-2.0.0~alpha8/lib/protocol/sequences/Query.js0000644000175000017500000001176612140003646021605 0ustar mikemikevar Sequence = require('./Sequence'); var Util = require('util'); var Packets = require('../packets'); var ResultSet = require('../ResultSet'); var ServerStatus = require('../constants/server_status'); var fs = require('fs'); var Readable = require('stream').Readable; module.exports = Query; Util.inherits(Query, Sequence); function Query(options, callback) { Sequence.call(this, callback); this.sql = options.sql; this.values = options.values; this.typeCast = (options.typeCast === undefined) ? true : options.typeCast; this.nestTables = options.nestTables || false; this._resultSet = null; this._results = []; this._fields = []; this._index = 0; this._loadError = null; } Query.prototype.start = function() { this.emit('packet', new Packets.ComQueryPacket(this.sql)); }; Query.prototype.determinePacket = function(firstByte, parser) { if (firstByte === 0) { // If we have a resultSet and got one eofPacket if (this._resultSet && this._resultSet.eofPackets.length === 1) { // Then this is a RowDataPacket with an empty string in the first column. // See: https://github.com/felixge/node-mysql/issues/222 } else if (this._resultSet && this._resultSet.resultSetHeaderPacket && this._resultSet.resultSetHeaderPacket.fieldCount !== null) { return Packets.FieldPacket; } else { return; } } if (firstByte === 255) { return; } // EofPacket's are 5 bytes in mysql >= 4.1 // This is the only / best way to differentiate their firstByte from a 9 // byte length coded binary. if (firstByte === 0xfe && parser.packetLength() < 9) { return Packets.EofPacket; } if (!this._resultSet) { return Packets.ResultSetHeaderPacket; } return (this._resultSet.eofPackets.length === 0) ? Packets.FieldPacket : Packets.RowDataPacket; }; Query.prototype['OkPacket'] = function(packet) { // try...finally for exception safety try { if (!this._callback) { this.emit('result', packet, this._index); } else { this._results.push(packet); this._fields.push(undefined); } } finally { this._index++; this._handleFinalResultPacket(packet); } }; Query.prototype['ErrorPacket'] = function(packet) { var err = this._packetToError(packet); var results = (this._results.length > 0) ? this._results : undefined; var fields = (this._fields.length > 0) ? this._fields : undefined; err.index = this._index; this.end(err, results, fields); }; Query.prototype['ResultSetHeaderPacket'] = function(packet) { this._resultSet = new ResultSet(packet); // used by LOAD DATA LOCAL INFILE queries if (packet.fieldCount === null) { this._sendLocalDataFile(packet.extra); } }; Query.prototype['FieldPacket'] = function(packet) { this._resultSet.fieldPackets.push(packet); }; Query.prototype['EofPacket'] = function(packet) { this._resultSet.eofPackets.push(packet); if (this._resultSet.eofPackets.length === 1 && !this._callback) { this.emit('fields', this._resultSet.fieldPackets, this._index); } if (this._resultSet.eofPackets.length !== 2) { return; } if (this._callback) { this._results.push(this._resultSet.rows); this._fields.push(this._resultSet.fieldPackets); } this._index++; this._resultSet = null; this._handleFinalResultPacket(packet); }; Query.prototype._handleFinalResultPacket = function(packet) { if (packet.serverStatus & ServerStatus.SERVER_MORE_RESULTS_EXISTS) { return; } var results = (this._results.length > 1) ? this._results : this._results[0]; var fields = (this._fields.length > 1) ? this._fields : this._fields[0]; this.end(this._loadError, results, fields); }; Query.prototype['RowDataPacket'] = function(packet, parser, connection) { packet.parse(parser, this._resultSet.fieldPackets, this.typeCast, this.nestTables, connection); if (this._callback) { this._resultSet.rows.push(packet); } else { this.emit('result', packet, this._index); } }; Query.prototype._sendLocalDataFile = function(path) { var self = this; fs.readFile(path, 'utf-8', function(err, data) { if (err) { self._loadError = err; } else { self.emit('packet', new Packets.LocalDataFilePacket(data)); } self.emit('packet', new Packets.EmptyPacket()); }); }; Query.prototype.stream = function(options) { var self = this, stream; options = options || {}; options.objectMode = true; stream = new Readable(options), stream._read = function() { self._connection.resume(); }; this.on('result',function(row,i) { if (!stream.push(row)) self._connection.pause(); stream.emit('result',row,i); // replicate old emitter }); this.on('error',function(err) { stream.emit('error',err); // Pass on any errors }); this.on('end', function() { stream.push(null); // pushing null, indicating EOF }); this.on('fields',function(fields,i) { stream.emit('fields',fields,i); // replicate old emitter }); return stream; };node-mysql-2.0.0~alpha8/lib/protocol/sequences/Statistics.js0000644000175000017500000000110312140003646022612 0ustar mikemikevar Sequence = require('./Sequence'); var Util = require('util'); var Packets = require('../packets'); module.exports = Statistics; Util.inherits(Statistics, Sequence); function Statistics(callback) { Sequence.call(this, callback); } Statistics.prototype.start = function() { this.emit('packet', new Packets.ComStatisticsPacket); }; Statistics.prototype['StatisticsPacket'] = function (packet) { this.end(null, packet); }; Statistics.prototype.determinePacket = function(firstByte, parser) { if (firstByte === 0x55) { return Packets.StatisticsPacket; } }; node-mysql-2.0.0~alpha8/lib/protocol/sequences/Sequence.js0000644000175000017500000000356212140003646022243 0ustar mikemikevar Util = require('util'); var EventEmitter = require('events').EventEmitter; var Packets = require('../packets'); var ErrorConstants = require('../constants/errors'); module.exports = Sequence; Util.inherits(Sequence, EventEmitter); function Sequence(callback) { EventEmitter.call(this); this._callback = callback; this._ended = false; // Experimental: Long stack trace support this._callSite = new Error; } Sequence.determinePacket = function(byte) { switch (byte) { case 0x00: return Packets.OkPacket; case 0xfe: return Packets.EofPacket; case 0xff: return Packets.ErrorPacket; } }; Sequence.prototype.hasErrorHandler = function() { return this._callback || this.listeners('error').length > 1; }; Sequence.prototype._packetToError = function(packet) { var code = ErrorConstants[packet.errno] || 'UNKNOWN_CODE_PLEASE_REPORT'; var err = new Error(code + ': ' + packet.message); err.code = code; return err; }; Sequence.prototype._addLongStackTrace = function(err) { var delimiter = '\n --------------------\n' ; if (err.stack.indexOf(delimiter) > -1) { return; } err.stack += delimiter + this._callSite.stack.replace(/.+\n/, ''); }; Sequence.prototype.end = function(err) { if (this._ended) { return; } this._ended = true; if (err) { this._addLongStackTrace(err); } // try...finally for exception safety try { if (err) { this.emit('error', err); } } finally { try { if (this._callback) { this._callback.apply(this, arguments); } } finally { this.emit('end'); } } }; Sequence.prototype['OkPacket'] = function(packet) { this.end(null, packet); }; Sequence.prototype['ErrorPacket'] = function(packet) { this.end(this._packetToError(packet)); }; // Implemented by child classes Sequence.prototype.start = function() {}; node-mysql-2.0.0~alpha8/lib/protocol/sequences/Ping.js0000644000175000017500000000047312140003646021366 0ustar mikemikevar Sequence = require('./Sequence'); var Util = require('util'); var Packets = require('../packets'); module.exports = Ping; Util.inherits(Ping, Sequence); function Ping(callback) { Sequence.call(this, callback); } Ping.prototype.start = function() { this.emit('packet', new Packets.ComPingPacket); }; node-mysql-2.0.0~alpha8/lib/protocol/sequences/ChangeUser.js0000644000175000017500000000242012140003646022507 0ustar mikemikevar Sequence = require('./Sequence'); var Util = require('util'); var Packets = require('../packets'); var Auth = require('../Auth'); module.exports = ChangeUser; Util.inherits(ChangeUser, Sequence); function ChangeUser(options, callback) { Sequence.call(this, callback); this._user = options.user; this._password = options.password; this._database = options.database; this._charsetNumber = options.charsetNumber; this._currentConfig = options.currentConfig; } ChangeUser.prototype.start = function(handshakeInitializationPacket) { var scrambleBuff = handshakeInitializationPacket.scrambleBuff(); scrambleBuff = Auth.token(this._password, scrambleBuff); var packet = new Packets.ComChangeUserPacket({ user : this._user, scrambleBuff : scrambleBuff, database : this._database, charsetNumber : this._charsetNumber, }); this._currentConfig.user = this._user; this._currentConfig.password = this._password; this._currentConfig.database = this._database; this._currentConfig.charsetNumber = this._charsetNumber; this.emit('packet', packet); }; ChangeUser.prototype['ErrorPacket'] = function(packet) { var err = this._packetToError(packet); err.fatal = true; this.end(err); }; node-mysql-2.0.0~alpha8/lib/protocol/sequences/index.js0000644000175000017500000000016212140003646021573 0ustar mikemikevar Elements = module.exports = require('require-all')({ dirname : __dirname, filter : /([A-Z].+)\.js$/, }); node-mysql-2.0.0~alpha8/lib/protocol/packets/0000755000175000017500000000000012140003646017566 5ustar mikemikenode-mysql-2.0.0~alpha8/lib/protocol/packets/ClientAuthenticationPacket.js0000644000175000017500000000376212140003646025402 0ustar mikemikemodule.exports = ClientAuthenticationPacket; function ClientAuthenticationPacket(options) { options = options || {}; this.clientFlags = options.clientFlags; this.maxPacketSize = options.maxPacketSize; this.charsetNumber = options.charsetNumber; this.filler = undefined; this.user = options.user; this.scrambleBuff = options.scrambleBuff; this.database = options.database; this.protocol41 = options.protocol41; } ClientAuthenticationPacket.prototype.parse = function(parser) { if (this.protocol41) { this.clientFlags = parser.parseUnsignedNumber(4); this.maxPacketSize = parser.parseUnsignedNumber(4); this.charsetNumber = parser.parseUnsignedNumber(1); this.filler = parser.parseFiller(23); this.user = parser.parseNullTerminatedString(); this.scrambleBuff = parser.parseLengthCodedBuffer(); this.database = parser.parseNullTerminatedString(); } else { this.clientFlags = parser.parseUnsignedNumber(2); this.maxPacketSize = parser.parseUnsignedNumber(3); this.user = parser.parseNullTerminatedString(); this.scrambleBuff = parser.parseBuffer(8); this.database = parser.parseLengthCodedBuffer(); } }; ClientAuthenticationPacket.prototype.write = function(writer) { if (this.protocol41) { writer.writeUnsignedNumber(4, this.clientFlags); writer.writeUnsignedNumber(4, this.maxPacketSize); writer.writeUnsignedNumber(1, this.charsetNumber); writer.writeFiller(23); writer.writeNullTerminatedString(this.user); writer.writeLengthCodedBuffer(this.scrambleBuff); writer.writeNullTerminatedString(this.database); } else { writer.writeUnsignedNumber(2, this.clientFlags); writer.writeUnsignedNumber(3, this.maxPacketSize); writer.writeNullTerminatedString(this.user); writer.writeBuffer(this.scrambleBuff); if (this.database && this.database.length) { writer.writeFiller(1); writer.writeBuffer(new Buffer(this.database)); } } }; node-mysql-2.0.0~alpha8/lib/protocol/packets/OkPacket.js0000644000175000017500000000236312140003646021631 0ustar mikemikemodule.exports = OkPacket; function OkPacket(options) { options = options || {}; this.fieldCount = undefined; this.affectedRows = undefined; this.insertId = undefined; this.serverStatus = undefined; this.warningCount = undefined; this.message = undefined; this.protocol41 = options.protocol41; } OkPacket.prototype.parse = function(parser) { this.fieldCount = parser.parseUnsignedNumber(1); this.affectedRows = parser.parseLengthCodedNumber(); this.insertId = parser.parseLengthCodedNumber(); if (this.protocol41) { this.serverStatus = parser.parseUnsignedNumber(2); this.warningCount = parser.parseUnsignedNumber(2); } this.message = parser.parsePacketTerminatedString(); this.changedRows = 0; var m = this.message.match(/\schanged:\s*(\d+)/i); if (m !== null) { this.changedRows = parseInt(m[1], 10); } }; OkPacket.prototype.write = function(writer) { writer.writeUnsignedNumber(1, 0x00); writer.writeLengthCodedNumber(this.affectedRows || 0); writer.writeLengthCodedNumber(this.insertId || 0); if (this.protocol41) { writer.writeUnsignedNumber(2, this.serverStatus || 0); writer.writeUnsignedNumber(2, this.warningCount || 0); } writer.writeString(this.message); }; node-mysql-2.0.0~alpha8/lib/protocol/packets/UseOldPasswordPacket.js0000644000175000017500000000057312140003646024177 0ustar mikemikemodule.exports = UseOldPasswordPacket; function UseOldPasswordPacket(options) { options = options || {}; this.firstByte = options.firstByte || 0xfe; } UseOldPasswordPacket.prototype.parse = function(parser) { this.firstByte = parser.parseUnsignedNumber(1); }; UseOldPasswordPacket.prototype.write = function(writer) { writer.writeUnsignedNumber(1, this.firstByte); }; node-mysql-2.0.0~alpha8/lib/protocol/packets/Field.js0000644000175000017500000000131412140003646021146 0ustar mikemikevar Types = require('../constants/types'); module.exports = Field; function Field(options) { options = options || {}; this.parser = options.parser; this.db = options.packet.db; this.table = options.packet.table; this.name = options.packet.name; this.type = typeToString(options.packet.type); this.length = options.packet.length; } Field.prototype.string = function () { return this.parser.parseLengthCodedString(); }; Field.prototype.buffer = function () { return this.parser.parseLengthCodedBuffer(); }; Field.prototype.geometry = function () { return this.parser.parseGeometryValue(); }; function typeToString(t) { for (var k in Types) { if (Types[k] == t) return k; } } node-mysql-2.0.0~alpha8/lib/protocol/packets/ResultSetHeaderPacket.js0000644000175000017500000000123512140003646024320 0ustar mikemikemodule.exports = ResultSetHeaderPacket; function ResultSetHeaderPacket(options) { options = options || {}; this.fieldCount = options.fieldCount; this.extra = options.extra; } ResultSetHeaderPacket.prototype.parse = function(parser) { this.fieldCount = parser.parseLengthCodedNumber(); if (parser.reachedPacketEnd()) return; this.extra = (this.fieldCount === null) ? parser.parsePacketTerminatedString() : parser.parseLengthCodedNumber(); }; ResultSetHeaderPacket.prototype.write = function(writer) { writer.writeLengthCodedNumber(this.fieldCount); if (this.extra !== undefined) { writer.writeLengthCodedNumber(this.extra); } }; node-mysql-2.0.0~alpha8/lib/protocol/packets/ComQuitPacket.js0000644000175000017500000000023612140003646022636 0ustar mikemikemodule.exports = ComQuitPacket; function ComQuitPacket(sql) { } ComQuitPacket.prototype.write = function(writer) { writer.writeUnsignedNumber(1, 0x01); }; node-mysql-2.0.0~alpha8/lib/protocol/packets/RowDataPacket.js0000644000175000017500000000656112140003646022625 0ustar mikemikevar Types = require('../constants/types'); var Charsets = require('../constants/charsets'); var Field = require('./Field'); var IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53); module.exports = RowDataPacket; function RowDataPacket() { } RowDataPacket.prototype.parse = function(parser, fieldPackets, typeCast, nestTables, connection) { var self = this; var next = function () { return self._typeCast(fieldPacket, parser, connection.config.timezone, connection.config.supportBigNumbers, connection.config.bigNumberStrings); }; for (var i = 0; i < fieldPackets.length; i++) { var fieldPacket = fieldPackets[i]; var value; if (typeof typeCast == "function") { value = typeCast.apply(connection, [ new Field({ packet: fieldPacket, parser: parser }), next ]); } else { value = (typeCast) ? this._typeCast(fieldPacket, parser, connection.config.timezone, connection.config.supportBigNumbers, connection.config.bigNumberStrings) : ( (fieldPacket.charsetNr === Charsets.BINARY) ? parser.parseLengthCodedBuffer() : parser.parseLengthCodedString() ); } if (typeof nestTables == "string" && nestTables.length) { this[fieldPacket.table + nestTables + fieldPacket.name] = value; } else if (nestTables) { this[fieldPacket.table] = this[fieldPacket.table] || {}; this[fieldPacket.table][fieldPacket.name] = value; } else { this[fieldPacket.name] = value; } } }; RowDataPacket.prototype._typeCast = function(field, parser, timeZone, supportBigNumbers, bigNumberStrings) { var numberString; switch (field.type) { case Types.TIMESTAMP: case Types.DATE: case Types.DATETIME: case Types.NEWDATE: var dateString = parser.parseLengthCodedString(); var dt; if (dateString === null) { return null; } if (timeZone != 'local') { if (field.type === Types.DATE) { dateString += ' 00:00:00 ' + timeZone; } else { dateString += timeZone; } } dt = new Date(dateString); if (isNaN(dt.getTime())) { return dateString; } return dt; case Types.TINY: case Types.SHORT: case Types.LONG: case Types.INT24: case Types.YEAR: case Types.FLOAT: case Types.DOUBLE: numberString = parser.parseLengthCodedString(); return (numberString === null || (field.zeroFill && numberString[0] == "0")) ? numberString : Number(numberString); case Types.NEWDECIMAL: case Types.LONGLONG: numberString = parser.parseLengthCodedString(); return (numberString === null || (field.zeroFill && numberString[0] == "0")) ? numberString : ((supportBigNumbers && (bigNumberStrings || (Number(numberString) > IEEE_754_BINARY_64_PRECISION))) ? numberString : Number(numberString)); case Types.BIT: return parser.parseLengthCodedBuffer(); case Types.STRING: case Types.VAR_STRING: case Types.TINY_BLOB: case Types.MEDIUM_BLOB: case Types.LONG_BLOB: case Types.BLOB: return (field.charsetNr === Charsets.BINARY) ? parser.parseLengthCodedBuffer() : parser.parseLengthCodedString(); case Types.GEOMETRY: return parser.parseGeometryValue(); default: return parser.parseLengthCodedString(); } }; node-mysql-2.0.0~alpha8/lib/protocol/packets/FieldPacket.js0000644000175000017500000000567112140003646022310 0ustar mikemikemodule.exports = FieldPacket; function FieldPacket(options) { options = options || {}; this.catalog = options.catalog; this.db = options.db; this.table = options.table; this.orgTable = options.orgTable; this.name = options.name; this.orgName = options.orgName; this.filler1 = undefined; this.charsetNr = options.charsetNr; this.length = options.length; this.type = options.type; this.flags = options.flags; this.decimals = options.decimals; this.filler2 = undefined; this.default = options.default; this.zeroFill = options.zeroFill; this.protocol41 = options.protocol41 } FieldPacket.prototype.parse = function(parser) { if (this.protocol41) { this.catalog = parser.parseLengthCodedString(); this.db = parser.parseLengthCodedString(); this.table = parser.parseLengthCodedString(); this.orgTable = parser.parseLengthCodedString(); this.name = parser.parseLengthCodedString(); this.orgName = parser.parseLengthCodedString(); this.filler1 = parser.parseFiller(1); this.charsetNr = parser.parseUnsignedNumber(2); this.fieldLength = parser.parseUnsignedNumber(4); this.type = parser.parseUnsignedNumber(1); this.flags = parser.parseUnsignedNumber(2); this.decimals = parser.parseUnsignedNumber(1); this.filler2 = parser.parseFiller(2); // parsed flags this.zeroFill = (this.flags & 0x0040 ? true : false); if (parser.reachedPacketEnd()) { return; } this.default = parser.parseLengthCodedNumber(); } else { this.table = parser.parseLengthCodedString(); this.name = parser.parseLengthCodedString(); this.fieldLength = parser.parseUnsignedNumber(parser.parseUnsignedNumber(1)); this.type = parser.parseUnsignedNumber(parser.parseUnsignedNumber(1)); } }; FieldPacket.prototype.write = function(writer) { if (this.protocol41) { writer.writeLengthCodedString(this.catalog); writer.writeLengthCodedString(this.db); writer.writeLengthCodedString(this.table); writer.writeLengthCodedString(this.orgTable); writer.writeLengthCodedString(this.name); writer.writeLengthCodedString(this.orgName); writer.writeFiller(1); writer.writeUnsignedNumber(2, this.charsetNr || 0); writer.writeUnsignedNumber(4, this.fieldLength || 0); writer.writeUnsignedNumber(1, this.type || 0); writer.writeUnsignedNumber(2, this.flags || 0); writer.writeUnsignedNumber(1, this.decimals || 0); writer.writeFiller(2); if (this.default !== undefined) { writer.writeLengthCodedString(this.default); } } else { writer.writeLengthCodedString(this.table); writer.writeLengthCodedString(this.name); writer.writeUnsignedNumber(1, 0x01); writer.writeUnsignedNumber(1, this.fieldLength); writer.writeUnsignedNumber(1, 0x01); writer.writeUnsignedNumber(1, this.type); } }; node-mysql-2.0.0~alpha8/lib/protocol/packets/StatisticsPacket.js0000644000175000017500000000104012140003646023401 0ustar mikemikemodule.exports = StatisticsPacket; function StatisticsPacket() { this.message = undefined; } StatisticsPacket.prototype.parse = function(parser) { this.message = parser.parsePacketTerminatedString(); var items = this.message.split(/\s\s/); for (var i = 0; i < items.length; i++) { var m = items[i].match(/^(.+)\:\s+(.+)$/); if (m !== null) { this[m[1].toLowerCase().replace(/\s/g, '_')] = Number(m[2]); } } }; StatisticsPacket.prototype.write = function(writer) { writer.writeString(this.message); }; node-mysql-2.0.0~alpha8/lib/protocol/packets/ComQueryPacket.js0000644000175000017500000000062512140003646023023 0ustar mikemikemodule.exports = ComQueryPacket; function ComQueryPacket(sql) { this.command = 0x03; this.sql = sql; } ComQueryPacket.prototype.write = function(writer) { writer.writeUnsignedNumber(1, this.command); writer.writeString(this.sql); }; ComQueryPacket.prototype.parse = function(parser) { this.command = parser.parseUnsignedNumber(1); this.sql = parser.parsePacketTerminatedString(); }; node-mysql-2.0.0~alpha8/lib/protocol/packets/ComChangeUserPacket.js0000644000175000017500000000161212140003646023737 0ustar mikemikemodule.exports = ComChangeUserPacket; function ComChangeUserPacket(options) { options = options || {}; this.command = 0x11; this.user = options.user; this.scrambleBuff = options.scrambleBuff; this.database = options.database; this.charsetNumber = options.charsetNumber; } ComChangeUserPacket.prototype.parse = function(parser) { this.user = parser.parseNullTerminatedString(); this.scrambleBuff = parser.parseLengthCodedBuffer(); this.database = parser.parseNullTerminatedString(); this.charsetNumber = parser.parseUnsignedNumber(1); }; ComChangeUserPacket.prototype.write = function(writer) { writer.writeUnsignedNumber(1, this.command); writer.writeNullTerminatedString(this.user); writer.writeLengthCodedBuffer(this.scrambleBuff); writer.writeNullTerminatedString(this.database); writer.writeUnsignedNumber(1, this.charsetNumber); }; node-mysql-2.0.0~alpha8/lib/protocol/packets/LocalDataFilePacket.js0000644000175000017500000000027712140003646023706 0ustar mikemikemodule.exports = LocalDataFilePacket; function LocalDataFilePacket(data) { this.data = data; } LocalDataFilePacket.prototype.write = function(writer) { writer.writeString(this.data); }; node-mysql-2.0.0~alpha8/lib/protocol/packets/EmptyPacket.js0000644000175000017500000000015612140003646022354 0ustar mikemikemodule.exports = EmptyPacket; function EmptyPacket() { } EmptyPacket.prototype.write = function(writer) { }; node-mysql-2.0.0~alpha8/lib/protocol/packets/EofPacket.js0000644000175000017500000000132112140003646021762 0ustar mikemikemodule.exports = EofPacket; function EofPacket(options) { options = options || {}; this.fieldCount = undefined; this.warningCount = options.warningCount; this.serverStatus = options.serverStatus; this.protocol41 = options.protocol41; } EofPacket.prototype.parse = function(parser) { this.fieldCount = parser.parseUnsignedNumber(1); if (this.protocol41) { this.warningCount = parser.parseUnsignedNumber(2); this.serverStatus = parser.parseUnsignedNumber(2); } }; EofPacket.prototype.write = function(writer) { writer.writeUnsignedNumber(1, 0xfe); if (this.protocol41) { writer.writeUnsignedNumber(2, this.warningCount); writer.writeUnsignedNumber(2, this.serverStatus); } }; node-mysql-2.0.0~alpha8/lib/protocol/packets/ComPingPacket.js0000644000175000017500000000044412140003646022612 0ustar mikemikemodule.exports = ComPingPacket; function ComPingPacket(sql) { this.command = 0x0e; } ComPingPacket.prototype.write = function(writer) { writer.writeUnsignedNumber(1, this.command); }; ComPingPacket.prototype.parse = function(parser) { this.command = parser.parseUnsignedNumber(1); }; node-mysql-2.0.0~alpha8/lib/protocol/packets/OldPasswordPacket.js0000644000175000017500000000060612140003646023517 0ustar mikemikemodule.exports = OldPasswordPacket; function OldPasswordPacket(options) { options = options || {}; this.scrambleBuff = options.scrambleBuff; } OldPasswordPacket.prototype.parse = function(parser) { this.scrambleBuff = parser.parseNullTerminatedBuffer(); }; OldPasswordPacket.prototype.write = function(writer) { writer.writeBuffer(this.scrambleBuff); writer.writeFiller(1); }; node-mysql-2.0.0~alpha8/lib/protocol/packets/ComStatisticsPacket.js0000644000175000017500000000047412140003646024052 0ustar mikemikemodule.exports = ComStatisticsPacket; function ComStatisticsPacket(sql) { this.command = 0x09; } ComStatisticsPacket.prototype.write = function(writer) { writer.writeUnsignedNumber(1, this.command); }; ComStatisticsPacket.prototype.parse = function(parser) { this.command = parser.parseUnsignedNumber(1); }; node-mysql-2.0.0~alpha8/lib/protocol/packets/ErrorPacket.js0000644000175000017500000000175712140003646022357 0ustar mikemikemodule.exports = ErrorPacket; function ErrorPacket(options) { options = options || {}; this.fieldCount = options.fieldCount; this.errno = options.errno; this.sqlStateMarker = options.sqlStateMarker; this.sqlState = options.sqlState; this.message = options.message; } ErrorPacket.prototype.parse = function(parser) { this.fieldCount = parser.parseUnsignedNumber(1); this.errno = parser.parseUnsignedNumber(2); // sqlStateMarker ('#' = 0x23) indicates error packet format if (parser.peak() === 0x23) { this.sqlStateMarker = parser.parseString(1); this.sqlState = parser.parseString(5); } this.message = parser.parsePacketTerminatedString(); }; ErrorPacket.prototype.write = function(writer) { writer.writeUnsignedNumber(1, 0xff); writer.writeUnsignedNumber(2, this.errno); if (this.sqlStateMarker) { writer.writeString(this.sqlStateMarker); writer.writeString(this.sqlState); } writer.writeString(this.message); }; node-mysql-2.0.0~alpha8/lib/protocol/packets/index.js0000644000175000017500000000016212140003646021232 0ustar mikemikevar Elements = module.exports = require('require-all')({ dirname : __dirname, filter : /([A-Z].+)\.js$/, }); node-mysql-2.0.0~alpha8/lib/protocol/packets/HandshakeInitializationPacket.js0000644000175000017500000000720412140003646026055 0ustar mikemikemodule.exports = HandshakeInitializationPacket; function HandshakeInitializationPacket(options) { options = options || {}; this.protocolVersion = options.protocolVersion; this.serverVersion = options.serverVersion; this.threadId = options.threadId; this.scrambleBuff1 = options.scrambleBuff1; this.filler1 = options.filler1; this.serverCapabilities1 = options.serverCapabilities1; this.serverLanguage = options.serverLanguage; this.serverStatus = options.serverStatus; this.serverCapabilities2 = options.serverCapabilities2; this.scrambleLength = options.scrambleLength; this.filler2 = options.filler2; this.scrambleBuff2 = options.scrambleBuff2; this.filler3 = options.filler3; this.pluginData = options.pluginData; this.protocol41 = options.protocol41; } HandshakeInitializationPacket.prototype.parse = function(parser) { this.protocolVersion = parser.parseUnsignedNumber(1); this.serverVersion = parser.parseNullTerminatedString(); this.threadId = parser.parseUnsignedNumber(4); this.scrambleBuff1 = parser.parseBuffer(8); this.filler1 = parser.parseFiller(1); this.serverCapabilities1 = parser.parseUnsignedNumber(2); this.serverLanguage = parser.parseUnsignedNumber(1); this.serverStatus = parser.parseUnsignedNumber(2); this.protocol41 = (this.serverCapabilities1 & (1 << 9)) > 0; if (this.protocol41) { this.serverCapabilities2 = parser.parseUnsignedNumber(2); this.scrambleLength = parser.parseUnsignedNumber(1); this.filler2 = parser.parseFiller(10); // scrambleBuff2 should be 0x00 terminated, but sphinx does not do this // so we assume scrambleBuff2 to be 12 byte and treat the next byte as a // filler byte. this.scrambleBuff2 = parser.parseBuffer(12); this.filler3 = parser.parseFiller(1); } else { this.filler2 = parser.parseFiller(13); } if (parser.reachedPacketEnd()) { return; } // According to the docs this should be 0x00 terminated, but MariaDB does // not do this, so we assume this string to be packet terminated. this.pluginData = parser.parsePacketTerminatedString(); // However, if there is a trailing '\0', strip it var lastChar = this.pluginData.length - 1; if (this.pluginData[lastChar] === '\0') { this.pluginData = this.pluginData.substr(0, lastChar); } }; HandshakeInitializationPacket.prototype.write = function(writer) { writer.writeUnsignedNumber(1, this.protocolVersion); writer.writeNullTerminatedString(this.serverVersion); writer.writeUnsignedNumber(4, this.threadId); writer.writeBuffer(this.scrambleBuff1); writer.writeFiller(1); writer.writeUnsignedNumber(2, this.serverCapabilities1); writer.writeUnsignedNumber(1, this.serverLanguage); writer.writeUnsignedNumber(2, this.serverStatus); if (this.protocol41) { writer.writeUnsignedNumber(2, this.serverCapabilities2); writer.writeUnsignedNumber(1, this.scrambleLength); writer.writeFiller(10); } writer.writeNullTerminatedBuffer(this.scrambleBuff2); if (this.pluginData !== undefined) { writer.writeNullTerminatedString(this.pluginData); } }; HandshakeInitializationPacket.prototype.scrambleBuff = function() { var buffer = new Buffer(this.scrambleBuff1.length + (typeof this.scrambleBuff2 != "undefined" ? this.scrambleBuff2.length : 0)); this.scrambleBuff1.copy(buffer); if (typeof this.scrambleBuff2 != "undefined") { this.scrambleBuff2.copy(buffer, this.scrambleBuff1.length); } return buffer; }; node-mysql-2.0.0~alpha8/lib/protocol/PacketHeader.js0000644000175000017500000000017112140003646021011 0ustar mikemikemodule.exports = PacketHeader; function PacketHeader(length, number) { this.length = length; this.number = number; } node-mysql-2.0.0~alpha8/lib/protocol/Auth.js0000644000175000017500000001021612140003646017373 0ustar mikemikevar Buffer = require('buffer').Buffer; var Crypto = require('crypto'); var Auth = exports; function sha1(msg) { var hash = Crypto.createHash('sha1'); hash.update(msg); // hash.digest() does not output buffers yet return hash.digest('binary'); }; Auth.sha1 = sha1; function xor(a, b) { a = new Buffer(a, 'binary'); b = new Buffer(b, 'binary'); var result = new Buffer(a.length); for (var i = 0; i < a.length; i++) { result[i] = (a[i] ^ b[i]); } return result; }; Auth.xor = xor; Auth.token = function(password, scramble) { if (!password) { return new Buffer(0); } // password must be in binary format, not utf8 var stage1 = sha1((new Buffer(password, "utf8")).toString("binary")); var stage2 = sha1(stage1); var stage3 = sha1(scramble.toString('binary') + stage2); return xor(stage3, stage1); }; // This is a port of sql/password.c:hash_password which needs to be used for // pre-4.1 passwords. Auth.hashPassword = function(password) { var nr = [0x5030, 0x5735], add = 7, nr2 = [0x1234, 0x5671], result = new Buffer(8); if (typeof password == 'string'){ password = new Buffer(password); } for (var i = 0; i < password.length; i++) { var c = password[i]; if (c == 32 || c == 9) { // skip space in password continue; } // nr^= (((nr & 63)+add)*c)+ (nr << 8); // nr = xor(nr, add(mul(add(and(nr, 63), add), c), shl(nr, 8))) nr = this.xor32(nr, this.add32(this.mul32(this.add32(this.and32(nr, [0,63]), [0,add]), [0,c]), this.shl32(nr, 8))); // nr2+=(nr2 << 8) ^ nr; // nr2 = add(nr2, xor(shl(nr2, 8), nr)) nr2 = this.add32(nr2, this.xor32(this.shl32(nr2, 8), nr)); // add+=tmp; add += c; } this.int31Write(result, nr, 0); this.int31Write(result, nr2, 4); return result; }; Auth.randomInit = function(seed1, seed2) { return { max_value: 0x3FFFFFFF, max_value_dbl: 0x3FFFFFFF, seed1: seed1 % 0x3FFFFFFF, seed2: seed2 % 0x3FFFFFFF }; }; Auth.myRnd = function(r){ r.seed1 = (r.seed1 * 3 + r.seed2) % r.max_value; r.seed2 = (r.seed1 + r.seed2 + 33) % r.max_value; return r.seed1 / r.max_value_dbl; }; Auth.scramble323 = function(message, password) { var to = new Buffer(8), hashPass = this.hashPassword(password), hashMessage = this.hashPassword(message.slice(0, 8)), seed1 = this.int32Read(hashPass, 0) ^ this.int32Read(hashMessage, 0), seed2 = this.int32Read(hashPass, 4) ^ this.int32Read(hashMessage, 4), r = this.randomInit(seed1, seed2); for (var i = 0; i < 8; i++){ to[i] = Math.floor(this.myRnd(r) * 31) + 64; } var extra = (Math.floor(this.myRnd(r) * 31)); for (var i = 0; i < 8; i++){ to[i] ^= extra; } return to; }; Auth.fmt32 = function(x){ var a = x[0].toString(16), b = x[1].toString(16); if (a.length == 1) a = '000'+a; if (a.length == 2) a = '00'+a; if (a.length == 3) a = '0'+a; if (b.length == 1) b = '000'+b; if (b.length == 2) b = '00'+b; if (b.length == 3) b = '0'+b; return '' + a + '/' + b; }; Auth.xor32 = function(a,b){ return [a[0] ^ b[0], a[1] ^ b[1]]; }; Auth.add32 = function(a,b){ var w1 = a[1] + b[1], w2 = a[0] + b[0] + ((w1 & 0xFFFF0000) >> 16); return [w2 & 0xFFFF, w1 & 0xFFFF]; }; Auth.mul32 = function(a,b){ // based on this example of multiplying 32b ints using 16b // http://www.dsprelated.com/showmessage/89790/1.php var w1 = a[1] * b[1], w2 = (((a[1] * b[1]) >> 16) & 0xFFFF) + ((a[0] * b[1]) & 0xFFFF) + (a[1] * b[0] & 0xFFFF); return [w2 & 0xFFFF, w1 & 0xFFFF]; }; Auth.and32 = function(a,b){ return [a[0] & b[0], a[1] & b[1]]; }; Auth.shl32 = function(a,b){ // assume b is 16 or less var w1 = a[1] << b, w2 = (a[0] << b) | ((w1 & 0xFFFF0000) >> 16); return [w2 & 0xFFFF, w1 & 0xFFFF]; }; Auth.int31Write = function(buffer, number, offset) { buffer[offset] = (number[0] >> 8) & 0x7F; buffer[offset + 1] = (number[0]) & 0xFF; buffer[offset + 2] = (number[1] >> 8) & 0xFF; buffer[offset + 3] = (number[1]) & 0xFF; }; Auth.int32Read = function(buffer, offset){ return (buffer[offset] << 24) + (buffer[offset+1] << 16) + (buffer[offset+2] << 8) + (buffer[offset+3]); }; node-mysql-2.0.0~alpha8/lib/protocol/Protocol.js0000644000175000017500000001660612140003646020304 0ustar mikemikevar Parser = require('./Parser'); var Sequences = require('./sequences'); var Packets = require('./packets'); var Auth = require('./Auth'); var Stream = require('stream').Stream; var Util = require('util'); var PacketWriter = require('./PacketWriter'); module.exports = Protocol; Util.inherits(Protocol, Stream); function Protocol(options) { Stream.call(this); options = options || {}; this.readable = true; this.writable = true; this._config = options.config || {}; this._connection = options.connection; this._callback = null; this._fatalError = null; this._quitSequence = null; this._handshakeSequence = null; this._handshaked = false; this._destroyed = false; this._queue = []; this._handshakeInitializationPacket = null; this._parser = new Parser({ onPacket : this._parsePacket.bind(this), config : this._config }); } Protocol.prototype.write = function(buffer) { this._parser.write(buffer); return true; }; Protocol.prototype.handshake = function(cb) { return this._handshakeSequence = this._enqueue(new Sequences.Handshake(this._config, cb)); }; Protocol.prototype.query = function(options, cb) { return this._enqueue(new Sequences.Query(options, cb)); }; Protocol.prototype.changeUser = function(options, cb) { return this._enqueue(new Sequences.ChangeUser(options, cb)); }; Protocol.prototype.ping = function(cb) { return this._enqueue(new Sequences.Ping(cb)); }; Protocol.prototype.stats = function(cb) { return this._enqueue(new Sequences.Statistics(cb)); }; Protocol.prototype.quit = function(cb) { return this._quitSequence = this._enqueue(new Sequences.Quit(cb)); }; Protocol.prototype.end = function() { var expected = (this._quitSequence && this._queue[0] === this._quitSequence); if (expected) { this._quitSequence.end(); this.emit('end'); return; } var err = new Error('Connection lost: The server closed the connection.'); err.fatal = true; err.code = 'PROTOCOL_CONNECTION_LOST'; this._delegateError(err); }; Protocol.prototype.pause = function() { this._parser.pause(); }; Protocol.prototype.resume = function() { this._parser.resume(); }; Protocol.prototype._enqueue = function(sequence) { if (!this._validateEnqueue(sequence)) { return sequence; } this._queue.push(sequence); var self = this; sequence .on('error', function(err) { self._delegateError(err, sequence); }) .on('packet', function(packet) { self._emitPacket(packet); }) .on('end', function() { self._dequeue(); }); if (this._queue.length === 1) { this._parser.resetPacketNumber(); sequence.start(); } return sequence; }; Protocol.prototype._validateEnqueue = function(sequence) { var err; var prefix = 'Cannot enqueue ' + sequence.constructor.name + ' after '; if (this._quitSequence) { err = new Error(prefix + 'invoking quit.'); err.code = 'PROTOCOL_ENQUEUE_AFTER_QUIT'; } else if (this._destroyed) { err = new Error(prefix + 'being destroyed.'); err.code = 'PROTOCOL_ENQUEUE_AFTER_DESTROY'; } else if (this._handshakeSequence && sequence.constructor === Sequences.Handshake) { err = new Error(prefix + 'already enqueuing a Handshake.'); err.code = 'PROTOCOL_ENQUEUE_HANDSHAKE_TWICE'; } else { return true; } var self = this; err.fatal = false; sequence .on('error', function(err) { self._delegateError(err, sequence); }) .end(err); return false; }; Protocol.prototype._parsePacket = function() { var sequence = this._queue[0]; var Packet = this._determinePacket(sequence); var packet = new Packet({ protocol41: this._config.protocol41 }); // Special case: Faster dispatch, and parsing done inside sequence if (Packet === Packets.RowDataPacket) { sequence.RowDataPacket(packet, this._parser, this._connection); if (this._config.debug) { this._debugPacket(true, packet); } return; } packet.parse(this._parser); if (this._config.debug) { this._debugPacket(true, packet); } if (Packet === Packets.HandshakeInitializationPacket) { this._handshakeInitializationPacket = packet; } sequence[Packet.name](packet); }; Protocol.prototype._emitPacket = function(packet) { var packetWriter = new PacketWriter(); packet.write(packetWriter); this.emit('data', packetWriter.toBuffer(this._parser)); if (this._config.debug) { this._debugPacket(false, packet); } }; Protocol.prototype._determinePacket = function(sequence) { var firstByte = this._parser.peak(); if (sequence.determinePacket) { var Packet = sequence.determinePacket(firstByte, this._parser); if (Packet) { return Packet; } } switch (firstByte) { case 0x00: if (!this._handshaked) { this._handshaked = true; this.emit('handshake'); } return Packets.OkPacket; case 0xfe: return Packets.EofPacket; case 0xff: return Packets.ErrorPacket; } throw new Error('Could not determine packet, firstByte = ' + firstByte); }; Protocol.prototype._dequeue = function() { // No point in advancing the queue, we are dead if (this._fatalError) { return; } this._queue.shift(); var sequence = this._queue[0]; if (!sequence) { this.emit('drain'); return; } this._parser.resetPacketNumber(); if (sequence.constructor == Sequences.ChangeUser) { sequence.start(this._handshakeInitializationPacket); return; } sequence.start(); }; Protocol.prototype.handleNetworkError = function(err) { err.fatal = true; var sequence = this._queue[0]; if (sequence) { sequence.end(err); } else { this._delegateError(err); } }; Protocol.prototype._delegateError = function(err, sequence) { // Stop delegating errors after the first fatal error if (this._fatalError) { return; } if (err.fatal) { this._fatalError = err; } if (this._shouldErrorBubbleUp(err, sequence)) { // Can't use regular 'error' event here as that always destroys the pipe // between socket and protocol which is not what we want (unless the // exception was fatal). this.emit('unhandledError', err); } else if (err.fatal) { this._queue.forEach(function(sequence) { sequence.end(err); }); } // Make sure the stream we are piping to is getting closed if (err.fatal) { this.emit('end', err); } }; Protocol.prototype._shouldErrorBubbleUp = function(err, sequence) { if (sequence) { if (sequence.hasErrorHandler()) { return false; } else if (!err.fatal) { return true; } } return (err.fatal && !this._hasPendingErrorHandlers()); }; Protocol.prototype._hasPendingErrorHandlers = function() { return this._queue.some(function(sequence) { return sequence.hasErrorHandler(); }); }; Protocol.prototype.destroy = function() { this._destroyed = true; this._parser.pause(); }; Protocol.prototype._debugPacket = function(incoming, packet) { var headline = (incoming) ? '<-- ' : '--> '; headline = headline + packet.constructor.name; // check for debug packet restriction if (Array.isArray(this._config.debug) && this._config.debug.indexOf(packet.constructor.name) === -1) { return; } console.log(headline); console.log(packet); console.log(''); }; node-mysql-2.0.0~alpha8/lib/ConnectionConfig.js0000644000175000017500000000715012140003646020061 0ustar mikemikevar urlParse = require('url').parse; var ClientConstants = require('./protocol/constants/client'); var Charsets = require('./protocol/constants/charsets'); module.exports = ConnectionConfig; function ConnectionConfig(options) { if (typeof options === 'string') { options = ConnectionConfig.parseUrl(options); } this.host = options.host || 'localhost'; this.port = options.port || 3306; this.socketPath = options.socketPath; this.user = options.user || undefined; this.password = options.password || undefined; this.database = options.database; this.insecureAuth = options.insecureAuth || false; this.supportBigNumbers = options.supportBigNumbers || false; this.bigNumberStrings = options.bigNumberStrings || false; this.debug = options.debug; this.timezone = options.timezone || 'local'; this.flags = options.flags || ''; this.queryFormat = options.queryFormat; this.pool = options.pool || undefined; this.multipleStatements = options.multipleStatements || false; this.typeCast = (options.typeCast === undefined) ? true : options.typeCast; if (this.timezone[0] == " ") { // "+" is a url encoded char for space so it // gets translated to space when giving a // connection string.. this.timezone = "+" + this.timezone.substr(1); } this.maxPacketSize = 0; this.charsetNumber = (options.charset) ? ConnectionConfig.getCharsetNumber(options.charset) : options.charsetNumber||Charsets.UTF8_GENERAL_CI; this.clientFlags = ConnectionConfig.mergeFlags(ConnectionConfig.getDefaultFlags(options), options.flags || ''); } ConnectionConfig.mergeFlags = function(default_flags, user_flags) { var flags = 0x0, i; user_flags = (user_flags || '').toUpperCase().split(/\s*,+\s*/); // add default flags unless "blacklisted" for (i in default_flags) { if (user_flags.indexOf("-" + default_flags[i]) >= 0) continue; flags |= ClientConstants["CLIENT_" + default_flags[i]] || 0x0; } // add user flags unless already already added for (i in user_flags) { if (user_flags[i][0] == "-") continue; if (default_flags.indexOf(user_flags[i]) >= 0) continue; flags |= ClientConstants["CLIENT_" + user_flags[i]] || 0x0; } return flags; }; ConnectionConfig.getDefaultFlags = function(options) { var defaultFlags = [ "LONG_PASSWORD", "FOUND_ROWS", "LONG_FLAG", "CONNECT_WITH_DB", "ODBC", "LOCAL_FILES", "IGNORE_SPACE", "PROTOCOL_41", "IGNORE_SIGPIPE", "TRANSACTIONS", "RESERVED", "SECURE_CONNECTION", "MULTI_RESULTS" ]; if (options && options.multipleStatements) { defaultFlags.push("MULTI_STATEMENTS"); } return defaultFlags; }; ConnectionConfig.getCharsetNumber = function(charset) { return Charsets[charset]; }; ConnectionConfig.parseUrl = function(url) { url = urlParse(url, true); var options = { host : url.hostname, port : url.port, database : url.pathname.substr(1), }; if (url.auth) { var auth = url.auth.split(':'); options.user = auth[0]; options.password = auth[1]; } if (url.query) { for (var key in url.query) { var value = url.query[key]; try { // Try to parse this as a JSON expression first options[key] = JSON.parse(value); } catch (err) { // Otherwise assume it is a plain string options[key] = value; } } } return options; }; node-mysql-2.0.0~alpha8/lib/Pool.js0000644000175000017500000001051512140003646015544 0ustar mikemike var Mysql = require('../'); var Connection = require('./Connection'); module.exports = Pool; function Pool(options) { this.config = options.config; this.config.connectionConfig.pool = this; this._allConnections = []; this._freeConnections = []; this._connectionQueue = []; this._closed = false; } Pool.prototype.getConnection = function(cb) { if (this._closed) { cb(new Error('Pool is closed.')); return; } if (this._freeConnections.length > 0) { var connection = this._freeConnections[0]; this._freeConnections.shift(); cb(null, connection); } else if (this.config.connectionLimit == 0 || this._allConnections.length < this.config.connectionLimit) { var self = this; var connection = this._createConnection(); this._allConnections.push(connection); connection.connect(function(err) { if (self._closed) { cb(new Error('Pool is closed.')); } else if (err) { cb(err); } else { cb(null, connection); } }); } else if (this.config.waitForConnections) { this._connectionQueue.push(cb); } else { cb(new Error('No connections available.')); } }; Pool.prototype.releaseConnection = function(connection) { if (connection._poolRemoved) { // The connection has been removed from the pool and is no longer good. if (this._connectionQueue.length) { var cb = this._connectionQueue[0]; this._connectionQueue.shift(); process.nextTick(this.getConnection.bind(this, cb)); } } else if (this._connectionQueue.length) { var cb = this._connectionQueue[0]; this._connectionQueue.shift(); process.nextTick(cb.bind(null, null, connection)); } else { this._freeConnections.push(connection); } }; Pool.prototype.end = function(cb) { this._closed = true; cb = cb || function(err) { if( err ) throw err; }; var self = this; var closedConnections = 0; var calledBack = false; var endCB = function(err) { if (calledBack) { return; } else if (err) { calledBack = true; delete endCB; cb(err); } else if (++closedConnections >= self._allConnections.length) { calledBack = true; delete endCB; cb(); } }; if (this._allConnections.length == 0) { endCB(); return; } for (var i = 0; i < this._allConnections.length; ++i) { var connection = this._allConnections[i]; connection.destroy = connection._realDestroy; connection.end = connection._realEnd; connection.end(endCB); } }; Pool.prototype._createConnection = function() { var self = this; var connection = (this.config.createConnection) ? this.config.createConnection(this.config.connectionConfig) : Mysql.createConnection(this.config.connectionConfig); connection._realEnd = connection.end; connection.end = function(cb) { self.releaseConnection(connection); if (cb) cb(); }; connection._realDestroy = connection.destroy; connection.destroy = function() { self._removeConnection(connection); connection.destroy(); }; // When a fatal error occurs the connection's protocol ends, which will cause // the connection to end as well, thus we only need to watch for the end event // and we will be notified of disconnects. connection.on('end', this._handleConnectionEnd.bind(this, connection)); connection.on('error', this._handleConnectionError.bind(this, connection)); return connection; }; Pool.prototype._handleConnectionEnd = function(connection) { if (this._closed || connection._poolRemoved) { return; } this._removeConnection(connection); }; Pool.prototype._handleConnectionError = function(connection) { if (this._closed || connection._poolRemoved) { return; } this._removeConnection(connection); }; Pool.prototype._removeConnection = function(connection) { connection._poolRemoved = true; for (var i = 0; i < this._allConnections.length; ++i) { if (this._allConnections[i] === connection) { this._allConnections.splice(i, 1); break; } } for (var i = 0; i < this._freeConnections.length; ++i) { if (this._freeConnections[i] === connection) { this._freeConnections.splice(i, 1); break; } } connection.end = connection._realEnd; connection.destroy = connection._realDestroy; this.releaseConnection(connection); }; node-mysql-2.0.0~alpha8/lib/Connection.js0000644000175000017500000001164012140003646016732 0ustar mikemikevar Net = require('net'); var ConnectionConfig = require('./ConnectionConfig'); var Pool = require('./Pool'); var Protocol = require('./protocol/Protocol'); var SqlString = require('./protocol/SqlString'); var Query = require('./protocol/sequences/Query'); var EventEmitter = require('events').EventEmitter; var Util = require('util'); module.exports = Connection; Util.inherits(Connection, EventEmitter); function Connection(options) { EventEmitter.call(this); this.config = options.config; this._socket = options.socket; this._protocol = new Protocol({config: this.config, connection: this}); this._connectCalled = false; this.state = "disconnected"; } Connection.createQuery = function(sql, values, cb) { if (sql instanceof Query) { return sql; } var options = {}; if (typeof sql === 'object') { // query(options, cb) options = sql; if (typeof values === 'function') { cb = values; } else { options.values = values; } } else if (typeof values === 'function') { // query(sql, cb) cb = values; options.sql = sql; options.values = undefined; } else { // query(sql, values, cb) options.sql = sql; options.values = values; } return new Query(options, cb); }; Connection.prototype.connect = function(cb) { if (!this._connectCalled) { this._connectCalled = true; this._socket = (this.config.socketPath) ? Net.createConnection(this.config.socketPath) : Net.createConnection(this.config.port, this.config.host); // Node v0.10+ Switch socket into "old mode" (Streams2) this._socket.on("data",function() {}); this._socket.pipe(this._protocol); this._protocol.pipe(this._socket); this._socket.on('error', this._handleNetworkError.bind(this)); this._socket.on('connect', this._handleProtocolConnect.bind(this)); this._protocol.on('handshake', this._handleProtocolHandshake.bind(this)); this._protocol.on('unhandledError', this._handleProtocolError.bind(this)); this._protocol.on('drain', this._handleProtocolDrain.bind(this)); this._protocol.on('end', this._handleProtocolEnd.bind(this)); } this._protocol.handshake(cb); }; Connection.prototype.changeUser = function(options, cb){ this._implyConnect(); if (typeof options === 'function') { cb = options; options = {}; } var charsetNumber = (options.charset) ? Config.getCharsetNumber(options.charset) : this.config.charsetNumber; return this._protocol.changeUser({ user : options.user || this.config.user, password : options.password || this.config.password, database : options.database || this.config.database, charsetNumber : charsetNumber, currentConfig : this.config }, cb); }; Connection.prototype.query = function(sql, values, cb) { this._implyConnect(); var query = Connection.createQuery(sql, values, cb); query._connection = this; if (!(typeof sql == 'object' && 'typeCast' in sql)) { query.typeCast = this.config.typeCast; } query.sql = this.format(query.sql, query.values || []); delete query.values; return this._protocol._enqueue(query); }; Connection.prototype.ping = function(cb) { this._implyConnect(); this._protocol.ping(cb); }; Connection.prototype.statistics = function(cb) { this._implyConnect(); this._protocol.stats(cb); }; Connection.prototype.end = function(cb) { this._implyConnect(); this._protocol.quit(cb); }; Connection.prototype.destroy = function() { this.state = "disconnected"; this._implyConnect(); this._socket.destroy(); this._protocol.destroy(); }; Connection.prototype.pause = function() { this._socket.pause(); this._protocol.pause(); }; Connection.prototype.resume = function() { this._socket.resume(); this._protocol.resume(); }; Connection.prototype.escape = function(value) { return SqlString.escape(value, false, this.config.timezone); }; Connection.prototype.format = function(sql, values) { if (typeof this.config.queryFormat == "function") { return this.config.queryFormat.call(this, sql, values, this.config.timezone); } return SqlString.format(sql, values, this.config.timezone); }; Connection.prototype._handleNetworkError = function(err) { this._protocol.handleNetworkError(err); }; Connection.prototype._handleProtocolError = function(err) { this.state = "protocol_error"; this.emit('error', err); }; Connection.prototype._handleProtocolDrain = function() { this.emit('drain'); }; Connection.prototype._handleProtocolConnect = function() { this.state = "connected"; }; Connection.prototype._handleProtocolHandshake = function() { this.state = "authenticated"; }; Connection.prototype._handleProtocolEnd = function(err) { this.state = "disconnected"; this.emit('end', err); }; Connection.prototype._implyConnect = function() { if (!this._connectCalled) { this.connect(); } }; node-mysql-2.0.0~alpha8/lib/PoolConfig.js0000644000175000017500000000074512140003646016676 0ustar mikemike var ConnectionConfig = require('./ConnectionConfig'); module.exports = PoolConfig; function PoolConfig(options) { this.connectionConfig = new ConnectionConfig(options); this.createConnection = options.createConnection || undefined; this.waitForConnections = (options.waitForConnections === undefined) ? true : Boolean(options.waitForConnections); this.connectionLimit = (options.connectionLimit === undefined) ? 10 : Number(options.connectionLimit); } node-mysql-2.0.0~alpha8/Changes.md0000644000175000017500000002114312140003646015420 0ustar mikemike# Changes This file is a manually maintained list of changes for each release. Feel free to add your changes here when sending pull requests. Also send corrections if you spot any mistakes. ## v2.0.0-alpha8 (2013-04-30) * Switch to old mode for Streams 2 (Node.js v 0.10.x) * Add stream method to Query Wraps events from the query object into a node v0.10.x Readable stream * DECIMAL should also be treated as big number * Removed slow unnecessary stack access * Added charsets * Added bigNumberStrings option for forcing BIGINT columns as strings * Changes date parsing to return String if not a valid JS Date * Adds support for ?? escape sequence to escape identifiers * Changes Auth.token() to force password to be in binary, not utf8 (#378) * Restrict debugging by packet types * Add 'multipleStatements' option tracking to ConnectionConfig. Fixes GH-408 * Changes Pool to handle 'error' events and dispose connection * Allows db.query({ sql: "..." }, [ val1, ... ], cb); (#390) * Improved documentation * Bug fixes ## v2.0.0-alpha7 (2013-02-03) * Add connection pooling (#351) ## v2.0.0-alpha6 (2013-01-31) * Add supportBigNumbers option (#381, #382) * Accept prebuilt Query object in connection.query * Bug fixes ## v2.0.0-alpha5 (2012-12-03) * Add mysql.escapeId to escape identifiers (closes #342) * Allow custom escaping mode (config.queryFormat) * Convert DATE columns to configured timezone instead of UTC (#332) * Convert LONGLONG and NEWDECIMAL to numbers (#333) * Fix Connection.escape() (fixes #330) * Changed Readme ambiguity about custom type cast fallback * Change typeCast to receive Connection instead of Connection.config.timezone * Fix drain event having useless err parameter * Add Connection.statistics() back from v0.9 * Add Connection.ping() back from v0.9 ## v2.0.0-alpha4 (2012-10-03) * Fix some OOB errors on resume() * Fix quick pause() / resume() usage * Properly parse host denied / similar errors * Add Connection.ChangeUser functionality * Make sure changeUser errors are fatal * Enable formatting nested arrays for bulk inserts * Add Connection.escape functionality * Renamed 'close' to 'end' event * Return parsed object instead of Buffer for GEOMETRY types * Allow nestTables inline (using a string instead of a boolean) * Check for ZEROFILL_FLAG and format number accordingly * Add timezone support (default: local) * Add custom typeCast functionality * Export mysql column types * Add connection flags functionality (#237) * Exports drain event when queue finishes processing (#272, #271, #306) ## v2.0.0-alpha3 (2012-06-12) * Implement support for `LOAD DATA LOCAL INFILE` queries (#182). * Support OLD\_PASSWORD() accounts like 0.9.x did. You should still upgrade any user accounts in your your MySQL user table that has short (16 byte) Password values. Connecting to those accounts is not secure. (#204) * Ignore function values when escaping objects, allows to use RowDataPacket objects as query arguments. (Alex Gorbatchev, #213) * Handle initial error packets from server such as `ER_HOST_NOT_PRIVILEGED`. * Treat `utf8\_bin` as a String, not Buffer. (#214) * Handle empty strings in first row column value. (#222) * Honor Connection#nestTables setting for queries. (#221) * Remove `CLIENT_INTERACTIVE` flag from config. Improves #225. * Improve docs for connections settings. * Implement url string support for Connection configs. ## v2.0.0-alpha2 (2012-05-31) * Specify escaping before for NaN / Infinity (they are as unquoted constants). * Support for unix domain socket connections (use: {socketPath: '...'}). * Fix type casting for NULL values for Date/Number fields * Add `fields` argument to `query()` as well as `'fields'` event. This is similar to what was available in 0.9.x. * Support connecting to the sphinx searchd daemon as well as MariaDB (#199). * Implement long stack trace support, will be removed / disabled if the node core ever supports it natively. * Implement `nestTables` option for queries, allows fetching JOIN result sets with overlapping column names. * Fix ? placeholder mechanism for values containing '?' characters (#205). * Detect when `connect()` is called more than once on a connection and provide the user with a good error message for it (#204). * Switch to `UTF8_GENERAL_CI` (previously `UTF8_UNICODE_CI`) as the default charset for all connections to avoid strange MySQL performance issues (#200), and also make the charset user configurable. * Fix BLOB type casting for `TINY_BLOG`, `MEDIUM_BLOB` and `LONG_BLOB`. * Add support for sending and receiving large (> 16 MB) packets. ## v2.0.0-alpha (2012-05-15) This release is a rewrite. You should carefully test your application after upgrading to avoid problems. This release features many improvements, most importantly: * ~5x faster than v0.9.x for parsing query results * Support for pause() / resume() (for streaming rows) * Support for multiple statement queries * Support for stored procedures * Support for transactions * Support for binary columns (as blobs) * Consistent & well documented error handling * A new Connection class that has well defined semantics (unlike the old Client class). * Convenient escaping of objects / arrays that allows for simpler query construction * A significantly simpler code base * Many bug fixes & other small improvements (Closed 62 out of 66 GitHub issues) Below are a few notes on the upgrade process itself: The first thing you will run into is that the old `Client` class is gone and has been replaced with a less ambitious `Connection` class. So instead of `mysql.createClient()`, you now have to: ```js var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', }); connection.query('SELECT 1', function(err, rows) { if (err) throw err; console.log('Query result: ', rows); }); connection.end(); ``` The new `Connection` class does not try to handle re-connects, please study the `Server disconnects` section in the new Readme. Other than that, the interface has stayed very similar. Here are a few things to check out so: * BIGINT's are now cast into strings * Binary data is now cast to buffers * The `'row'` event on the `Query` object is now called `'result'` and will also be emitted for queries that produce an OK/Error response. * Error handling is consistently defined now, check the Readme * Escaping has become more powerful which may break your code if you are currently using objects to fill query placeholders. * Connections can now be established explicitly again, so you may wish to do so if you want to handle connection errors specifically. That should be most of it, if you run into anything else, please send a patch or open an issue to improve this document. ## v0.9.6 (2012-03-12) * Escape array values so they produce sql arrays (Roger Castells, Colin Smith) * docs: mention mysql transaction stop gap solution (Blake Miner) * docs: Mention affectedRows in FAQ (Michael Baldwin) ## v0.9.5 (2011-11-26) * Fix #142 Driver stalls upon reconnect attempt that's immediately closed * Add travis build * Switch to urun as a test runner * Switch to utest for unit tests * Remove fast-or-slow dependency for tests * Split integration tests into individual files again ## v0.9.4 (2011-08-31) * Expose package.json as `mysql.PACKAGE` (#104) ## v0.9.3 (2011-08-22) * Set default `client.user` to root * Fix #91: Client#format should not mutate params array * Fix #94: TypeError in client.js * Parse decimals as string (vadimg) ## v0.9.2 (2011-08-07) * The underlaying socket connection is now managed implicitly rather than explicitly. * Check the [upgrading guide][] for a full list of changes. ## v0.9.1 (2011-02-20) * Fix issue #49 / `client.escape()` throwing exceptions on objects. (Nick Payne) * Drop < v0.4.x compatibility. From now on you need node v0.4.x to use this module. ## Older releases These releases were done before maintaining this file: * [v0.9.0](https://github.com/felixge/node-mysql/compare/v0.8.0...v0.9.0) (2011-01-04) * [v0.8.0](https://github.com/felixge/node-mysql/compare/v0.7.0...v0.8.0) (2010-10-30) * [v0.7.0](https://github.com/felixge/node-mysql/compare/v0.6.0...v0.7.0) (2010-10-14) * [v0.6.0](https://github.com/felixge/node-mysql/compare/v0.5.0...v0.6.0) (2010-09-28) * [v0.5.0](https://github.com/felixge/node-mysql/compare/v0.4.0...v0.5.0) (2010-09-17) * [v0.4.0](https://github.com/felixge/node-mysql/compare/v0.3.0...v0.4.0) (2010-09-02) * [v0.3.0](https://github.com/felixge/node-mysql/compare/v0.2.0...v0.3.0) (2010-08-25) * [v0.2.0](https://github.com/felixge/node-mysql/compare/v0.1.0...v0.2.0) (2010-08-22) * [v0.1.0](https://github.com/felixge/node-mysql/commits/v0.1.0) (2010-08-22) node-mysql-2.0.0~alpha8/tool/0000755000175000017500000000000012140003646014502 5ustar mikemikenode-mysql-2.0.0~alpha8/tool/generate-error-constants.js0000755000175000017500000000143112140003646021775 0ustar mikemike#!/usr/bin/env node var path = require('path'); var script = path.basename(__filename); var errorFile = process.argv[2]; if (!errorFile) { console.error('Usage: ./' + script + ' path/to/errmsg-utf8.txt'); process.exit(1); } var fs = require('fs'); var errors = fs.readFileSync(errorFile, 'utf-8'); var number = Number(errors.match(/start-error-number (\d+)/)[1]); var codes = errors.match(/^([A-Z_]+)/mg) var source = '// Generated by ' + script + ', do not modify by hand\n' + codes .map(function(code) { return 'exports[' + (number++) + '] = \'' + code + '\';'; }) .join('\n'); var targetFile = path.join(__dirname, '../lib/protocol/constants/errors.js'); fs.writeFileSync(targetFile, source, 'utf-8'); console.log('Wrote constants to ' + targetFile); node-mysql-2.0.0~alpha8/License0000644000175000017500000000213612140003646015034 0ustar mikemikeCopyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node-mysql-2.0.0~alpha8/test/0000755000175000017500000000000012140003646014504 5ustar mikemikenode-mysql-2.0.0~alpha8/test/integration/0000755000175000017500000000000012140003646017027 5ustar mikemikenode-mysql-2.0.0~alpha8/test/integration/pool/0000755000175000017500000000000012140003646020000 5ustar mikemikenode-mysql-2.0.0~alpha8/test/integration/pool/test-connection-limit.js0000644000175000017500000000117412140003646024571 0ustar mikemikevar common = require('../../common'); var assert = require('assert'); var pool = common.createPool({ connectionLimit : 1, waitForConnections : false }); pool.getConnection(function(err, connection) { if (err) throw err; pool.getConnection(function(err) { assert.ok(err); var shouldGetConnection = false; pool.config.waitForConnections = true; pool.getConnection(function(err, connection2) { if (err) throw err; assert.ok(shouldGetConnection); assert.strictEqual(connection, connection2); pool.end(); }); shouldGetConnection = true; connection.end(); }); }); node-mysql-2.0.0~alpha8/test/integration/pool/test-get-connection.js0000644000175000017500000000046112140003646024230 0ustar mikemikevar common = require('../../common'); var assert = require('assert'); var Connection = require(common.lib + '/Connection'); var pool = common.createPool(); pool.getConnection(function(err, connection) { if (err) throw err; assert.ok(connection instanceof Connection); pool.end(); }); node-mysql-2.0.0~alpha8/test/integration/pool/test-end-empty.js0000644000175000017500000000041212140003646023212 0ustar mikemikevar common = require('../../common'); var assert = require('assert'); var pool = common.createPool(); var poolEnded = false; pool.end(function(err) { poolEnded = true; if (err) throw err; }); process.on('exit', function() { assert(poolEnded); }); node-mysql-2.0.0~alpha8/test/integration/pool/test-destroy-connection.js0000644000175000017500000000107012140003646025137 0ustar mikemikevar common = require('../../common'); var assert = require('assert'); var Connection = require(common.lib + '/Connection'); var pool = common.createPool(); pool.getConnection(function(err, connection) { if (err) throw err; assert.strictEqual(connection, pool._allConnections[0]); connection.destroy(); assert.ok(pool._allConnections.length == 0); assert.ok(connection._poolRemoved); assert.strictEqual(connection.end, Connection.prototype.end); assert.strictEqual(connection.destroy, Connection.prototype.destroy); pool.end(); }); node-mysql-2.0.0~alpha8/test/integration/connection/0000755000175000017500000000000012140003646021166 5ustar mikemikenode-mysql-2.0.0~alpha8/test/integration/connection/test-procedure-with-single-select.js0000644000175000017500000000143012140003646030174 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var procedureName = 'singleSelectProcedure'; var input = 1; var fieldName = 'param'; var result = undefined; connection.query([ 'CREATE DEFINER=root@localhost PROCEDURE '+procedureName+'(IN '+fieldName+' INT)', 'BEGIN', 'SELECT '+fieldName+';', 'END' ].join('\n')); connection.query('CALL '+procedureName+'(?)', [input], function(err, _result) { if (err) throw err; _result.pop(); // drop metadata result = _result; }); connection.query('DROP PROCEDURE '+procedureName); connection.end(); process.on('exit', function() { var expected = {}; expected[fieldName] = input; assert.deepEqual(result, [[expected]]); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-change-user-fatal-error.js0000644000175000017500000000142312140003646027116 0ustar mikemike// This test verifies that changeUser errors are treated as fatal errors. The // rationale for that is that a failure to execute a changeUser sequence may // cause unexpected behavior for queries that were enqueued under the // assumption of changeUser to succeed. var common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); if (common.isTravis()) { return console.log('skipping - travis mysql does not support this test'); } var err; connection.changeUser({user: 'does-not-exist'}, function(_err) { err = _err; connection.end(); }); process.on('exit', function() { if (process.env.NO_GRANT == '1' && err === null) return; assert.equal(err.code, 'ER_ACCESS_DENIED_ERROR'); assert.equal(err.fatal, true); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-multiple-statements-streaming.js0000644000175000017500000000244412140003646030514 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({multipleStatements: true}); var assert = require('assert'); var sql = [ 'SELECT 1', 'USE ' + common.testDatabase, 'SELECT 2', 'invalid sql', 'SELECT 3', ].join('; '); var results = []; var fields = []; var hadErr = false; var query = connection.query(sql); query .on('error', function(err) { assert.equal(hadErr, false); hadErr = true; assert.equal(err.code, 'ER_PARSE_ERROR'); assert.equal(err.index, 3); }) .on('fields', function(_fields, index) { fields.push({fields: _fields, index: index}); }) .on('result', function(result, index) { results.push({result: result, index: index}); }); connection.end(); process.on('exit', function() { assert.ok(hadErr); assert.equal(results.length, 3); assert.deepEqual(results[0].result, {1: 1}); assert.equal(results[0].index, 0); assert.equal(results[1].result.constructor.name, 'OkPacket'); assert.equal(results[1].index, 1); assert.deepEqual(results[2].result, {2: 2}); assert.equal(results[2].index, 2); assert.equal(fields.length, 2); assert.equal(fields[0].fields[0].name, '1'); assert.equal(fields[1].fields[0].name, '2'); assert.equal(fields[0].index, 0); assert.equal(fields[1].index, 2); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-custom-typecast.js0000644000175000017500000000206212140003646025645 0ustar mikemikevar Mysql = require('../../../'); var common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var table = 'custom_typecast_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '`(', '`id` int(5),', '`val` tinyint(1)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); var results; connection.query("INSERT INTO " + table + " VALUES (1, 0), (2, 1), (3, NULL)"); connection.query({ sql: "SELECT * FROM " + table, typeCast: function (field, next) { if (field.type != 'TINY') { return next(); } var val = field.string(); if (val === null) { return null; } return (Number(val) > 0); } }, function (err, _results) { if (err) throw err; results = _results; }); connection.end(); process.on('exit', function() { assert.equal(results.length, 3); assert.deepEqual(results[0], {id: 1, val: false}); assert.deepEqual(results[1], {id: 2, val: true}); assert.deepEqual(results[2], {id: 3, val: null}); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-old-password.js0000644000175000017500000000142512140003646025121 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({ port : common.fakeServerPort, password : 'oldpw', insecureAuth : true, }); var assert = require('assert'); var server = common.createFakeServer(); var connected; server.listen(common.fakeServerPort, function(err) { if (err) throw err; connection.connect(function(err, result) { if (err) throw err; connected = result; connection.destroy(); server.destroy(); }); }); server.on('connection', function(incomingConnection) { incomingConnection.handshake({ user : connection.config.user, password : connection.config.password, oldPassword : true, }); }); process.on('exit', function() { assert.equal(connected.fieldCount, 0); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-fatal-auth-error-going-to-all-callbacks.js0000644000175000017500000000117012140003646032061 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({password: common.bogusPassword}); var assert = require('assert'); var errors = {}; connection.connect(function(err) { assert.equal(errors.a, undefined); errors.a = err; }); connection.query('SELECT 1', function(err) { assert.equal(errors.b, undefined); errors.b = err; connection.end(); }); process.on('exit', function() { if (process.env.NO_GRANT == '1' && errors.a === null) return; assert.equal(errors.a.code, 'ER_ACCESS_DENIED_ERROR'); assert.equal(errors.a.fatal, true); assert.strictEqual(errors.a, errors.b); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-procedure-with-multiple-selects.js0000644000175000017500000000177212140003646030742 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var procedureName = 'multipleSelectProcedure'; var input0 = 1; var input1 = 1000; var fieldName0 = 'param0'; var fieldName1 = 'param1'; var result = undefined; connection.query([ 'CREATE DEFINER=root@localhost PROCEDURE '+procedureName+'(IN '+fieldName0+' INT, IN '+fieldName1+' INT)', 'BEGIN', 'SELECT '+fieldName0+';', 'SELECT '+fieldName1+';', 'END' ].join('\n')); connection.query('CALL '+procedureName+'(?,?)', [input0,input1], function(err, _result) { if (err) throw err; _result.pop(); // drop metadata result = _result; }); connection.query('DROP PROCEDURE '+procedureName); connection.end(); process.on('exit', function() { var result0Expected = {}; result0Expected[fieldName0] = input0; var result1Expected = {}; result1Expected[fieldName1] = input1; assert.deepEqual(result, [[result0Expected], [result1Expected]]); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-long-stack-traces-for-connection-errors.js0000644000175000017500000000044712140003646032262 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({port: common.bogusPort}); var assert = require('assert'); var err; connection.connect(function(_err) { err = _err; }); process.on('exit', function() { assert.ok(err.stack.indexOf(__filename) > 0); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-insert-results.js0000644000175000017500000000122012140003646025477 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var table = 'insert_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`title` varchar(255),', 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); var result; connection.query('INSERT INTO ' + table + ' SET ?', {title: 'test'}, function(err, _result) { if (err) throw err; result = _result; }); connection.end(); process.on('exit', function() { assert.strictEqual(result.insertId, 1); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-timezones.js0000644000175000017500000000312712140003646024521 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var table = 'timezone_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '`(', '`offset` varchar(10),', '`dt` datetime', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); var tests = [ 0, 1, 5, 12, 26, -1, -5, -20, 'Z', 'local' ]; connection.query('DELETE FROM ' + table); testNextDate(); function testNextDate() { if (tests.length === 0) { return connection.end(); } var test = tests.pop(); testDate(test, function () { testNextDate(); }); } function testDate(offset, cb) { var dt = new Date(); if (offset == 'Z' || offset == 'local') { connection.config.timezone = offset; } else { connection.config.timezone = (offset < 0 ? "-" : "+") + pad2(Math.abs(offset)) + ":00"; } connection.query('INSERT INTO ' + table + ' SET ?', { offset: offset, dt: dt }); if (offset == 'Z') { dt.setTime(dt.getTime() + (dt.getTimezoneOffset() * 60000)); } else if (offset != 'local') { dt.setTime(dt.getTime() + (dt.getTimezoneOffset() * 60000) + (offset * 3600000)); } connection.query({ sql: 'SELECT * FROM ' + table + ' WHERE offset = \'' + offset + '\'', typeCast: function (field, next) { if (field.type != 'DATETIME') return next(); return new Date(field.string()); } }, function (err, result) { if (err) throw err; assert.strictEqual(dt.toString(), result[0].dt.toString()); return cb(); }); } function pad2(v) { return (v < 10 ? "0" : "") + v; } node-mysql-2.0.0~alpha8/test/integration/connection/test-select-1.js0000644000175000017500000000067512140003646024126 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); connection.connect(); var rows = undefined; var fields = undefined; connection.query('SELECT 1', function(err, _rows, _fields) { if (err) throw err; rows = _rows; fields = _fields; }); connection.end(); process.on('exit', function() { assert.deepEqual(rows, [{1: 1}]); assert.equal(fields[0].name, '1'); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-statistics.js0000644000175000017500000000173212140003646024676 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); var statsErr, statsData; connection.statistics(function(err, data) { statsErr = err; statsData = data; }); connection.end(); process.on('exit', function() { assert.equal(statsErr, null); assert.strictEqual(typeof statsData, "object"); assert.strictEqual(statsData.hasOwnProperty("message"), true); assert.strictEqual(statsData.hasOwnProperty("uptime"), true); assert.strictEqual(statsData.hasOwnProperty("threads"), true); assert.strictEqual(statsData.hasOwnProperty("questions"), true); assert.strictEqual(statsData.hasOwnProperty("slow_queries"), true); assert.strictEqual(statsData.hasOwnProperty("opens"), true); assert.strictEqual(statsData.hasOwnProperty("flush_tables"), true); assert.strictEqual(statsData.hasOwnProperty("open_tables"), true); assert.strictEqual(statsData.hasOwnProperty("queries_per_second_avg"), true); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-exception-safety.js0000644000175000017500000000347712140003646026003 0ustar mikemike// This test covers all event / callback interfaces offered by node-mysql and // throws an exception in them. Exception safety means that each of those // exceptions can be caught by an 'uncaughtException' / Domain handler without // the connection instance ending up in a bad state where it doesn't work // properly or doesn't execute the next sequence anymore. var common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); var errors = []; process.on('uncaughtException', function(err) { console.log(err.stack); errors.push(err); }); // Normal callback connection.connect(function(err) { throw err || new Error('1'); }); // Normal callback (same code path as connect, but in here should that // implementation detail change at some point). connection.query('SELECT 1', function(err) { throw err || new Error('2'); }); // Row streaming events connection.query('SELECT 1') .on('fields', function() { throw new Error('3'); }) .on('result', function() { throw new Error('4'); }); // Normal callback with error connection.query('INVALID SQL', function(err) { assert.equal(err.code, 'ER_PARSE_ERROR'); throw new Error('5'); }); // Row streaming 'result' event triggered by Ok Packet (special code path) connection.query('USE ' + common.testDatabase) .on('result', function() { throw new Error('6'); }); // Normal callback (same code path as connect, but in here should that // implementation detail change at some point). connection.end(function(err) { throw err || new Error('7'); }); process.on('exit', function() { process.removeAllListeners(); var expectedErrors = 7; for (var i = 0; i < expectedErrors - 1; i++) { var error = errors[i]; assert.equal(error.message, String(i + 1)); assert.equal(error.code, undefined); } }); node-mysql-2.0.0~alpha8/test/integration/connection/test-send-and-receive-large-packets.js0000644000175000017500000000424012140003646030332 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); connection.connect(function(err) { if (err) throw err; getMaxAllowedPacket(); }); var oldMaxAllowedPacket; function getMaxAllowedPacket() { connection.query('SHOW VARIABLES WHERE Variable_name = ?', ['max_allowed_packet'], function(err, rows) { if (err) throw err; oldMaxAllowedPacket = Number(rows[0].Value); increaseMaxAllowedPacketIfNeeded(); }); } function increaseMaxAllowedPacketIfNeeded() { // Our test generates a SQL query a few bytes larger than 16 MB, but lets // leave a little margin: var minMaxAllowedPacket = 20 * 1024 * 1024; var newMaxAllowedPacket = (oldMaxAllowedPacket < minMaxAllowedPacket) ? minMaxAllowedPacket : oldMaxAllowedPacket; connection.query('SET GLOBAL max_allowed_packet = ?', [newMaxAllowedPacket], function(err, rows) { if (err) throw err; // We need to re-connect for this change to take effect, bah connection.end(); connection = common.createConnection(); // We need to wait for the re-connect to happen before starting the actual // test. That's because our buffer to hex shim in 0.4.x takes ~12 sec on // TravisCI, causing a MySQL connection timeout otherwise. connection.connect(function(err) { if (err) throw err; triggerLargeQueryAndResponsePackets(); }); }); } var rows = []; var length = Math.pow(256, 3) / 2; // Half, because of hex encoding var buffer = new Buffer(length); var sql = 'SELECT ? as bigField'; function triggerLargeQueryAndResponsePackets() { connection.query(sql, [buffer], function(err, _rows) { if (err) throw err; rows = _rows; resetMaxAllowedPacket(); }); } function resetMaxAllowedPacket() { connection.query('SET GLOBAL max_allowed_packet = ?', [oldMaxAllowedPacket], function(err, rows) { if (err) { err.message = 'Could not reset max_allowed_packet size, please check your server settings: ' + err.message; throw err; } }); connection.end(); } process.on('exit', function() { assert.equal(rows.length, 1); assert.equal(rows[0].bigField.length, length); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-fatal-auth-error-without-handlers.js0000644000175000017500000000101012140003646031145 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({password: common.bogusPassword}); var assert = require('assert'); connection.connect(); connection.query('SELECT 1'); var err; connection.on('error', function(_err) { assert.equal(err, undefined); err = _err; }); connection.end(); process.on('exit', function() { if (process.env.NO_GRANT == '1' && typeof err == 'undefined') return; assert.equal(err.code, 'ER_ACCESS_DENIED_ERROR'); assert.equal(err.fatal, true); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-implicit-connect.js0000644000175000017500000000051412140003646025742 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); var rows = undefined; connection.query('SELECT 1', function(err, _rows) { if (err) throw err; rows = _rows; }); connection.end(); process.on('exit', function() { assert.deepEqual(rows, [{1: 1}]); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-query-after-destroy.js0000644000175000017500000000061212140003646026433 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); var err; connection.connect(function() { connection.destroy(); connection.query('SELECT 1', function(_err) { err = _err; }); }); process.on('exit', function() { assert.equal(err.fatal, false); assert.equal(err.code, 'PROTOCOL_ENQUEUE_AFTER_DESTROY'); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-end-callback.js0000644000175000017500000000101012140003646024771 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); connection.connect(); var gotEnd = false; connection.on('end', function(err) { assert.equal(gotEnd, false); assert.ok(!err); gotEnd = true; }); var gotCallback = false; connection.end(function(err) { if (err) throw err; assert.equal(gotCallback, false); gotCallback = true; }); process.on('exit', function() { assert.equal(gotCallback, true); assert.equal(gotEnd, true); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-fatal-query-error-without-callback.js0000644000175000017500000000066512140003646031324 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({port: common.bogusPort}); var assert = require('assert'); connection.connect(); var query = connection.query('SELECT 1'); var err; query.on('error', function(_err) { assert.equal(err, undefined); err = _err; }); connection.end(); process.on('exit', function() { assert.equal(err.code, 'ECONNREFUSED'); assert.equal(err.fatal, true); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-type-cast-null-fields.js0000644000175000017500000000144212140003646026627 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var table = 'insert_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`date` DATETIME NULL,', '`number` INT NULL,', 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); connection.query('INSERT INTO ' + table + ' SET ?', { date : null, number : null, }); var results; connection.query('SELECT * FROM ' + table, function(err, _results) { if (err) throw err; results = _results; }); connection.end(); process.on('exit', function() { assert.strictEqual(results[0].date, null); assert.strictEqual(results[0].number, null); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-query-after-end.js0000644000175000017500000000076712140003646025523 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); var didEnd = false; connection.connect(); connection.end(function(err) { if (err) throw err; didEnd = true; }); var err; connection.query('SELECT 1', function(_err) { assert.equal(didEnd, false); err = _err; }); process.on('exit', function() { assert.equal(didEnd, true); assert.equal(err.code, 'PROTOCOL_ENQUEUE_AFTER_QUIT'); assert.equal(err.fatal, false); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-nested-tables-query.js0000644000175000017500000000216512140003646026402 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var table = 'nested_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`title` varchar(255),', 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); connection.query('INSERT INTO ' + table + ' SET ?', {title: 'test'}); var options1 = { nestTables: true, sql: 'SELECT * FROM ' + table }; var options2 = { nestTables: '_', sql: 'SELECT * FROM ' + table }; var rows1, rows2; connection.query(options1, function(err, _rows) { if (err) throw err; rows1 = _rows; }); connection.query(options2, function(err, _rows) { if (err) throw err; rows2 = _rows; }); connection.end(); process.on('exit', function() { assert.equal(rows1.length, 1); assert.equal(rows1[0].nested_test.id, 1); assert.equal(rows1[0].nested_test.title, 'test'); assert.equal(rows2.length, 1); assert.equal(rows2[0].nested_test_id, 1); assert.equal(rows2[0].nested_test_title, 'test'); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-double-connect.js0000644000175000017500000000100312140003646025374 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); var didConnect = false; connection.connect(function(err) { if (err) throw err; assert.equal(didConnect, false); didConnect = true; }); var err; connection.connect(function(_err) { err = _err; }); connection.end(); process.on('exit', function() { assert.equal(didConnect, true); assert.equal(err.fatal, false); assert.equal(err.code, 'PROTOCOL_ENQUEUE_HANDSHAKE_TWICE'); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-connection-destroy.js0000644000175000017500000000032112140003646026323 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); connection.connect(function(err) { if (err) throw err; connection.destroy(); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-query-escaping.js0000644000175000017500000000164512140003646025443 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var table = 'escape_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`example` varchar(255),', 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); connection.query('INSERT INTO ' + table + ' SET id = ?, example = ?', [1, 'array escape']); connection.query('INSERT INTO ' + table + ' SET ?', { id: 2, example: 'object escape' }); var rows; connection.query('SELECT * FROM escape_test', function(err, _rows) { if (err) throw err; rows = _rows; }); connection.end(); process.on('exit', function() { assert.equal(rows.length, 2); assert.deepEqual(rows[0], {id: 1, example: 'array escape'}); assert.deepEqual(rows[1], {id: 2, example: 'object escape'}); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-unix-domain-socket.js0000644000175000017500000000136712140003646026226 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({socketPath: common.fakeServerSocket}); var assert = require('assert'); var server = common.createFakeServer(); var didConnect = false; server.listen(common.fakeServerSocket, function(err) { if (err) throw err; connection.connect(function(err) { if (err) throw err; assert.equal(didConnect, false); didConnect = true; connection.destroy(); server.destroy(); }); }); var hadConnection = false; server.on('connection', function(connection) { connection.handshake(); assert.equal(hadConnection, false); hadConnection = true; }); process.on('exit', function() { assert.equal(didConnect, true); assert.equal(hadConnection, true); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-long-stack-traces.js0000644000175000017500000000056212140003646026025 0ustar mikemike// Experimental: https://github.com/felixge/node-mysql/issues/198 var common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); var err; connection.query('invalid sql', function(_err) { err = _err; }); connection.end(); process.on('exit', function() { assert.ok(err.stack.indexOf(__filename) > 0); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-multiple-statements-with-error.js0000644000175000017500000000155012140003646030622 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({multipleStatements: true}); var assert = require('assert'); var sql = [ 'SELECT 1', 'invalid sql', 'SELECT 2', ].join('; '); var finishedQueryOne = false; connection.query(sql, function(err, results, fields) { assert.equal(finishedQueryOne, false); finishedQueryOne = true; assert.equal(err.code, 'ER_PARSE_ERROR'); assert.deepEqual(results, [[{1: 1}]]); assert.equal(fields.length, 1); assert.equal(fields[0][0].name, '1'); }); var finishedQueryTwo = false; connection.query('SELECT 3', function(err, results) { assert.equal(finishedQueryTwo, false); finishedQueryTwo = true; assert.deepEqual(results, [{3: 3}]); }); connection.end(); process.on('exit', function() { assert.equal(finishedQueryOne, true); assert.equal(finishedQueryTwo, true); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-streaming-rows-quick-pause-resume.js0000644000175000017500000000171412140003646031210 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var table = 'stream_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`title` varchar(255),', 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); var rowCount = 10; for (var i = 1; i <= rowCount; i++) { var row = { id: i, title: 'Row #' + i, }; connection.query('INSERT INTO ' + table + ' SET ?', row); } var query = connection.query('SELECT * FROM ' + table); var hadEnd = false; var rows = []; var fields = undefined; query.on('result', function(row) { connection.pause(); connection.resume(); rows.push(row); }) .on('end', function() { hadEnd = true; }); connection.end(); process.on('exit', function() { assert.equal(rows.length, rowCount); assert.equal(hadEnd, true); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-load-data-infile.js0000644000175000017500000000247312140003646025601 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var table = 'load_data_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`title` varchar(255),', 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); var path = common.fixtures + '/data.csv'; var sql = 'LOAD DATA LOCAL INFILE ? INTO TABLE ' + table + ' ' + 'FIELDS TERMINATED BY ? (id, title)'; var ok; connection.query(sql, [path, ','], function(err, _ok) { if (err) throw err; ok = _ok; }); var rows; connection.query('SELECT * FROM ' + table, function(err, _rows) { if (err) throw err; rows = _rows; }); // Try to load a file that does not exist to see if we handle this properly var loadErr; var loadResult; var badPath = common.fixtures + '/does_not_exist.csv'; connection.query(sql, [badPath, ','], function(err, result) { loadErr = err; loadResult = result; }); connection.end(); process.on('exit', function() { assert.equal(ok.affectedRows, 3); assert.equal(rows.length, 3); assert.equal(rows[0].id, 1); assert.equal(rows[0].title, 'Hello World'); assert.equal(loadErr.code, 'ENOENT'); assert.equal(loadResult.affectedRows, 0); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-server-timeout-disconnect.js0000644000175000017500000000104512140003646027622 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); connection.query('SET wait_timeout = 1'); var errorErr; var endErr; connection .on('end', function(err) { assert.ok(!endErr); endErr = err; }) .on('error', function(err) { assert.ok(!errorErr); errorErr = err; }); process.on('exit', function() { assert.strictEqual(errorErr.code, 'PROTOCOL_CONNECTION_LOST'); assert.strictEqual(errorErr.fatal, true); assert.strictEqual(endErr, errorErr); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-callback-errors-are-not-caught.js0000644000175000017500000000061612140003646030366 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); var err = new Error('uncaught exception'); connection.connect(function() { throw err; }); var caughtErr; process.on('uncaughtException', function(err) { caughtErr = err; process.exit(0); }); process.on('exit', function() { assert.strictEqual(caughtErr, err); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-normal-query-error-without-callback.js0000644000175000017500000000065412140003646031523 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); connection.connect(); var query = connection.query('INVALID SQL'); var err; query.on('error', function(_err) { assert.equal(err, undefined); err = _err; }); connection.end(); process.on('exit', function() { assert.equal(err.code, 'ER_PARSE_ERROR'); assert.equal(Boolean(err.fatal), false); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-host-denied-error.js0000644000175000017500000000131312140003646026031 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({port: common.fakeServerPort}); var assert = require('assert'); var server = common.createFakeServer(); var connectErr; server.listen(common.fakeServerPort, function(err) { if (err) throw err; connection.connect(function(err) { connectErr = err; server.destroy(); }); }); server.on('connection', function(incomingConnection) { var errno = 1130; // ER_HOST_NOT_PRIVILEGED incomingConnection.deny('You suck.', errno); }); process.on('exit', function() { assert.equal(connectErr.code, 'ER_HOST_NOT_PRIVILEGED'); assert.ok(/You suck/.test(connectErr.message)); assert.equal(connectErr.fatal, true); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-bulk-insert.js0000644000175000017500000000171512140003646024744 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); var _ = require('underscore'); common.useTestDb(connection); var table = 'insert_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`title` varchar(255),', 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); var result; var items = []; var itemsFoundInTable = []; for(var i = 0; i < 100; i++) items[i] = ['test '+i]; connection.query('INSERT INTO ' + table + ' (title) VALUES ? ', [items], function(err, _result) { if (err) throw err; result = _result; connection.query('SELECT title FROM '+table+';', [], function(err, _items) { itemsFoundInTable = _.map(_items, function(row) { return [row.title]; }); connection.end(); }); }); process.on('exit', function() { assert.deepEqual(items, itemsFoundInTable); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-query-after-end-without-callback.js0000644000175000017500000000076012140003646030747 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); var didEnd = false; connection.connect(); connection.end(function(err) { if (err) throw err; didEnd = true; }); var err; connection.on('error', function(_err) { err = _err; }); connection.query('SELECT 1'); process.on('exit', function() { assert.equal(didEnd, true); assert.equal(err.code, 'PROTOCOL_ENQUEUE_AFTER_QUIT'); assert.equal(err.fatal, false); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-multiple-statements.js0000644000175000017500000000135012140003646026520 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({multipleStatements: true}); var assert = require('assert'); var sql = [ 'SELECT 1', 'USE ' + common.testDatabase, 'SELECT 2', ].join('; '); var results; var fields; connection.query(sql, function(err, _results, _fields) { if (err) throw err; results = _results; fields = _fields; }); connection.end(); process.on('exit', function() { assert.equal(results.length, 3); assert.deepEqual(results[0], [{1: 1}]); assert.strictEqual(results[1].constructor.name, 'OkPacket'); assert.deepEqual(results[2], [{2: 2}]); assert.equal(fields[0][0].name, '1'); assert.equal(fields[1], undefined); assert.equal(fields[2][0].name, '2'); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-destroy-while-streaming-rows.js0000644000175000017500000000170012140003646030255 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var table = 'stream_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`title` varchar(255),', 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); var rowCount = 10; for (var i = 1; i <= rowCount; i++) { var row = { id: i, title: 'Row #' + i, }; connection.query('INSERT INTO ' + table + ' SET ?', row); } var destroyed = false; var hadEnd = false; var query = connection.query('SELECT * FROM ' + table); query .on('result', function(row) { assert.equal(destroyed, false); destroyed = true; connection.destroy(); }) .on('end', function() { hadEnd = true; }); connection.end(); process.on('exit', function() { assert.strictEqual(hadEnd, false); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-connection-config-flags-affected-rows.js0000644000175000017500000000333212140003646031725 0ustar mikemike// Based on: // https://github.com/ichernev/node-mysql/blob/on-duplicate-key-update/test/integration/connection/test-on-duplicate-key-update.js // (but with CLIENT_FOUND_ROWS connection flag blacklisted) var common = require('../../common'); var connection = common.createConnection({ flags: "-FOUND_ROWS" }); var assert = require('assert'); common.useTestDb(connection); var table = 'on_duplicate_key_test'; connection.query('DROP TABLE IF EXISTS `' + table + '`'); connection.query([ 'CREATE TABLE `' + table + '` (', '`a` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`b` int(11),', '`c` int(11),', 'PRIMARY KEY (`a`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); connection.query('INSERT INTO `' + table + '` SET ?', {a: 1, b: 1, c: 1}); connection.query('INSERT INTO `' + table + '` (a, b, c) VALUES (1, 2, 3) ON DUPLICATE KEY UPDATE c = 1', function(err, info) { assert.strictEqual(null, err); assert.strictEqual(0, info.affectedRows, 'both primary key and updated key are the same so nothing is affected (expected 0, got ' + info.affectedRows + ' affectedRows)'); }); connection.query('INSERT INTO `' + table + '` (a, b, c) VALUES (2, 3, 4) ON DUPLICATE KEY UPDATE c = 1', function(err, info) { assert.strictEqual(null, err); assert.strictEqual(1, info.affectedRows, 'primary key differs, so new row is inserted (expected 1, got ' + info.affectedRows + ' affectedRows)'); }); connection.query('INSERT INTO `' + table + '` (a, b, c) VALUES (1, 2, 3) ON DUPLICATE KEY UPDATE c = 2', function(err, info) { assert.strictEqual(null, err); assert.strictEqual(2, info.affectedRows, 'primary key is the same, row is updated (expected 2, got ' + info.affectedRows + ' affectedRows)'); }); connection.end(); node-mysql-2.0.0~alpha8/test/integration/connection/test-type-casting.js0000644000175000017500000001173712140003646025121 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var tests = [ {type: 'decimal(3,3)', insert: '0.330', expect: 0.33 }, {type: 'decimal(3,3)', insert: 0.33}, {type: 'tinyint', insert: 1}, {type: 'smallint', insert: 2}, {type: 'int', insert: 3}, {type: 'float', insert: 4.5}, {type: 'double', insert: 5.5}, {type: 'bigint', insert: '6', expect: 6}, {type: 'bigint', insert: 6}, {type: 'mediumint', insert: 7}, {type: 'year', insert: 2012}, {type: 'timestamp', insert: new Date('2012-05-12 11:00:23')}, {type: 'datetime', insert: new Date('2012-05-12 12:00:23')}, {type: 'date', insert: new Date('2012-05-12 00:00:00 Z')}, {type: 'time', insert: '13:13:23'}, {type: 'binary(4)', insert: new Buffer([0, 1, 254, 255])}, {type: 'varbinary(4)', insert: new Buffer([0, 1, 254, 255])}, {type: 'tinyblob', insert: new Buffer([0, 1, 254, 255])}, {type: 'mediumblob', insert: new Buffer([0, 1, 254, 255])}, {type: 'longblob', insert: new Buffer([0, 1, 254, 255])}, {type: 'blob', insert: new Buffer([0, 1, 254, 255])}, {type: 'bit(32)', insert: new Buffer([0, 1, 254, 255])}, {type: 'char(5)', insert: 'Hello'}, {type: 'varchar(5)', insert: 'Hello'}, {type: 'varchar(3) character set utf8 collate utf8_bin', insert: 'bin'}, {type: 'tinytext', insert: 'Hello World'}, {type: 'mediumtext', insert: 'Hello World'}, {type: 'longtext', insert: 'Hello World'}, {type: 'text', insert: 'Hello World'}, {type: 'point', insertRaw: 'POINT(1.2,-3.4)', expect: {x:1.2, y:-3.4}, deep: true}, {type: 'point', insertRaw: (function() { var buffer = new Buffer(21); buffer.writeUInt8(1, 0); buffer.writeUInt32LE(1, 1); buffer.writeDoubleLE(-5.6, 5); buffer.writeDoubleLE(10.23, 13); return 'GeomFromWKB(' + connection.escape(buffer) + ')'; })(), expect: {x:-5.6, y:10.23}, deep: true}, {type: 'linestring', insertRaw: 'LINESTRING(POINT(1.2,-3.4),POINT(-5.6,10.23),POINT(0.2,0.7))', expect: [{x:1.2, y:-3.4}, {x:-5.6, y:10.23}, {x:0.2, y:0.7}], deep: true}, {type: 'polygon', insertRaw: "GeomFromText('POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))')", expect: [[{x:0,y:0},{x:10,y:0},{x:10,y:10},{x:0,y:10},{x:0,y:0}],[{x:5,y:5},{x:7,y:5},{x:7,y:7},{x:5,y:7},{x:5,y:5}]], deep: true}, {type: 'geometry', insertRaw: 'POINT(1.2,-3.4)', expect: {x:1.2, y:-3.4}, deep: true}, {type: 'multipoint', insertRaw: "GeomFromText('MULTIPOINT(0 0, 20 20, 60 60)')", expect: [{x:0, y:0}, {x:20, y:20}, {x:60, y:60}], deep: true}, {type: 'multilinestring', insertRaw: "GeomFromText('MULTILINESTRING((10 10, 20 20), (15 15, 30 15))')", expect: [[{x:10,y:10},{x:20,y:20}],[{x:15,y:15},{x:30,y:15}]], deep: true}, {type: 'multipolygon', insertRaw: "GeomFromText('MULTIPOLYGON(((0 0,10 0,10 10,0 10,0 0)),((5 5,7 5,7 7,5 7, 5 5)))')", expect: [[[{x:0,y:0},{x:10,y:0},{x:10,y:10},{x:0,y:10},{x:0,y:0}]],[[{x:5,y:5},{x:7,y:5},{x:7,y:7},{x:5,y:7},{x:5,y:5}]]], deep: true}, {type: 'geometrycollection', insertRaw: "GeomFromText('GEOMETRYCOLLECTION(POINT(10 10), POINT(30 30), LINESTRING(15 15, 20 20))')", expect: [{x:10,y:10},{x:30,y:30},[{x:15,y:15},{x:20,y:20}]], deep: true} ]; var table = 'type_casting'; var schema = []; var inserts = []; tests.forEach(function(test, index) { var escaped = test.insertRaw || connection.escape(test.insert); test.columnName = test.type + '_' + index; schema.push('`' + test.columnName + '` ' + test.type + ','); inserts.push('`' + test.columnName + '` = ' + escaped); }); var createTable = [ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,' ].concat(schema).concat([ 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ]).join('\n'); connection.query(createTable); connection.query('INSERT INTO ' + table + ' SET' + inserts.join(',\n')); var row; connection.query('SELECT * FROM type_casting', function(err, rows) { if (err) throw err; row = rows[0]; }); connection.end(); process.on('exit', function() { tests.forEach(function(test) { var expected = test.expect || test.insert; var got = row[test.columnName]; var message; if (expected instanceof Date) { assert.equal(got instanceof Date, true, test.type); expected = String(expected); got = String(got); } else if (Buffer.isBuffer(expected)) { assert.equal(Buffer.isBuffer(got), true, test.type); expected = String(Array.prototype.slice.call(expected)); got = String(Array.prototype.slice.call(got)); } if (test.deep) { message = 'got: "' + JSON.stringify(got) + '" expected: "' + JSON.stringify(expected) + '" test: ' + test.type + ''; assert.deepEqual(expected, got, message); } else { message = 'got: "' + got + '" (' + (typeof got) + ') expected: "' + expected + '" (' + (typeof expected) + ') test: ' + test.type + ''; assert.strictEqual(expected, got, message); } }); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-transaction-rollback.js0000644000175000017500000000155412140003646026622 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var table = 'transaction_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`title` varchar(255),', 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); connection.query('START TRANSACTION'); var rowCount = 10; for (var i = 1; i <= rowCount; i++) { var row = { id: i, title: 'Row #' + i, }; connection.query('INSERT INTO ' + table + ' SET ?', row); } connection.query('ROLLBACK'); var rows; var query = connection.query('SELECT * FROM ' + table, function(err, _rows) { if (err) throw err; rows = _rows; }); connection.end(); process.on('exit', function() { assert.equal(rows.length, 0); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-streaming-rows.js0000644000175000017500000000254512140003646025470 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var table = 'stream_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`title` varchar(255),', 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); var rowCount = 10; for (var i = 1; i <= rowCount; i++) { var row = { id: i, title: 'Row #' + i, }; connection.query('INSERT INTO ' + table + ' SET ?', row); } var paused = false; var query = connection.query('SELECT * FROM ' + table); var hadEnd = 0; var rows = []; var fields = undefined; query .on('fields', function(_fields, index) { assert.equal(index, 0); assert.ok(!fields); fields = _fields; }) .on('result', function(row) { // Make sure we never receive a row while being paused assert.equal(paused, false); paused = true; connection.pause(); setTimeout(function() { paused = false; connection.resume(); rows.push(row); }, 10); }) .on('end', function() { hadEnd = true; }); connection.end(); process.on('exit', function() { assert.equal(rows.length, 10); assert.equal(hadEnd, true); assert.equal(fields[0].name, 'id'); assert.equal(fields[1].name, 'title'); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-query-escape-id.js0000644000175000017500000000141712140003646025501 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var table = 'escape_id_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`example` varchar(255),', 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); connection.query('INSERT INTO ?? SET ?? = ?, ?? = ?', [ table, 'id', 1, 'example', 'id escape']); var rows; connection.query('SELECT * FROM ??', [ table ], function(err, _rows) { if (err) throw err; rows = _rows; }); connection.end(); process.on('exit', function() { assert.equal(rows.length, 1); assert.deepEqual(rows[0], {id: 1, example: 'id escape'}); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-change-user.js0000644000175000017500000000165212140003646024706 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); if (common.isTravis()) { return console.log('skipping - travis mysql does not support this test'); } connection.query('CREATE DATABASE ' + common.testDatabase, function(err) { if (err && err.code !== 'ER_DB_CREATE_EXISTS') throw err; }); var initialDb; connection.query('select database() as db', function(err, results) { if (err) throw err; initialDb = results[0].db; assert.equal(connection.config.database, null); }); connection.changeUser({database: common.testDatabase}); var finalDb; connection.query('select database() as db', function(err, results){ if (err) throw err; finalDb = results[0].db; assert.equal(connection.config.database, finalDb); }); connection.end(); process.on('exit', function() { assert.equal(initialDb, null); assert.equal(finalDb, common.testDatabase); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-custom-query-format.js0000644000175000017500000000121212140003646026440 0ustar mikemikevar Mysql = require('../../../'); var common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); connection.config.queryFormat = function (query, values, tz) { if (!values) return query; return query.replace(/\:(\w+)/g, function (txt, key) { if (values.hasOwnProperty(key)) { return this.escape(values[key]); } return txt; }.bind(this)); }; assert.equal(connection.format("SELECT :a1, :a2", { a1: 1, a2: 'two' }), "SELECT 1, 'two'"); assert.equal(connection.format("SELECT :a1", []), "SELECT :a1"); assert.equal(connection.format("SELECT :a1"), "SELECT :a1"); ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootnode-mysql-2.0.0~alpha8/test/integration/connection/test-fatal-network-error-going-to-all-callbacks.jsnode-mysql-2.0.0~alpha8/test/integration/connection/test-fatal-network-error-going-to-all-callbacks.0000644000175000017500000000102012140003646032246 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({port: common.bogusPort}); var assert = require('assert'); var errors = {}; connection.connect(function(err) { assert.equal(errors.a, undefined); errors.a = err; }); connection.query('SELECT 1', function(err) { assert.equal(errors.b, undefined); errors.b = err; }); process.on('exit', function() { assert.equal(errors.a.code, 'ECONNREFUSED'); assert.equal(errors.a.fatal, true); assert.strictEqual(errors.a, errors.b); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-drain-event.js0000644000175000017500000000065412140003646024722 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); connection.connect(); var got_drain = false; connection.on('drain', function() { got_drain = true; }); connection.query("SELECT 1", function(err) { assert.equal(got_drain, false); assert.ok(!err); process.nextTick(function() { assert.equal(got_drain, true); connection.end(); }); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-select-empty-string.js0000644000175000017500000000050312140003646026416 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); var rows; connection.query('SELECT ""', function(err, _rows) { if (err) throw err; rows = _rows; }); connection.end(); process.on('exit', function() { assert.deepEqual(rows, [{'': ''}]); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-bad-credentials.js0000644000175000017500000000122112140003646025516 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({password: 'INVALID PASSWORD'}); var assert = require('assert'); var endErr; connection.on('end', function(err) { assert.equal(endErr, undefined); endErr = err; }); var connectErr; connection.connect(function(err) { assert.equal(connectErr, undefined); connectErr = err; connection.end(); }); process.on('exit', function() { if (process.env.NO_GRANT == '1' && typeof endErr == 'undefined') return; assert.equal(endErr.code, 'ER_ACCESS_DENIED_ERROR'); assert.ok(/access denied/i.test(endErr.message)); assert.strictEqual(endErr, connectErr); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-normal-error-without-handler.js0000644000175000017500000000064512140003646030241 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); connection.connect(); connection.query('INVALID SQL'); var err; connection.on('error', function(_err) { assert.equal(err, undefined); err = _err; }); connection.end(); process.on('exit', function() { assert.equal(err.code, 'ER_PARSE_ERROR'); assert.equal(Boolean(err.fatal), false); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-zerofill-results.js0000644000175000017500000000223612140003646026031 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var table = 'zerofill_results_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`num` int(5) UNSIGNED ZEROFILL,', 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); var test_numbers = [ "00000", "00001", "00012", "00123", "01234", "12345", null ]; var results = {}; for (var i = 0; i < test_numbers.length; i++) { connection.query('INSERT INTO ' + table + ' SET ?', { id: (i + 1), num: (test_numbers[i] !== null ? parseInt(test_numbers[i], 10) : null) }, function (err, _result) { if (err) throw err; }); } connection.query('SELECT * FROM ' + table, function (err, _results) { if (err) throw err; results = _results; }); connection.end(); process.on('exit', function() { assert.strictEqual(results.length, test_numbers.length); for (var i = 0; i < results.length; i++) { assert.strictEqual(test_numbers[results[i].id - 1], (results[i].num !== null ? "" + results[i].num : null)); } }); node-mysql-2.0.0~alpha8/test/integration/connection/test-connection-config-flags.js0000644000175000017500000000365212140003646027203 0ustar mikemikevar ConnectionConfig = require('../../../lib/ConnectionConfig'); var ClientConstants = require('../../../lib/protocol/constants/client'); var assert = require('assert'); var testFlags = [{ 'default' : [ '' ], 'user' : 'LONG_PASSWORD', 'expected': ClientConstants.CLIENT_LONG_PASSWORD }, { 'default' : [ '' ], 'user' : '-LONG_PASSWORD', 'expected': 0x0 }, { 'default' : [ 'LONG_PASSWORD', 'FOUND_ROWS' ], 'user' : '-LONG_PASSWORD', 'expected': ClientConstants.CLIENT_FOUND_ROWS }, { 'default' : [ 'LONG_PASSWORD', 'FOUND_ROWS' ], 'user' : '-FOUND_ROWS', 'expected': ClientConstants.CLIENT_LONG_PASSWORD }, { 'default' : [ 'LONG_PASSWORD', 'FOUND_ROWS' ], 'user' : '-LONG_FLAG', 'expected': ClientConstants.CLIENT_LONG_PASSWORD | ClientConstants.CLIENT_FOUND_ROWS }, { 'default' : [ 'LONG_PASSWORD', 'FOUND_ROWS' ], 'user' : 'LONG_FLAG', 'expected': ClientConstants.CLIENT_LONG_PASSWORD | ClientConstants.CLIENT_FOUND_ROWS | ClientConstants.CLIENT_LONG_FLAG }, { 'default' : [ 'LONG_PASSWORD', 'FOUND_ROWS' ], 'user' : 'UNDEFINED_CONSTANT', 'expected': ClientConstants.CLIENT_LONG_PASSWORD | ClientConstants.CLIENT_FOUND_ROWS }, { 'default' : [ 'LONG_PASSWORD', 'FOUND_ROWS' ], 'user' : '-UNDEFINED_CONSTANT', 'expected': ClientConstants.CLIENT_LONG_PASSWORD | ClientConstants.CLIENT_FOUND_ROWS }, { 'default' : [ 'LONG_PASSWORD', 'FOUND_ROWS' ], 'user' : '-UNDEFINED_CONSTANT,, -found_ROWS', 'expected': ClientConstants.CLIENT_LONG_PASSWORD }]; for (var i = 0; i < testFlags.length; i++) { // console.log("expected: %s got: %s", testFlags[i]['expected'], // ConnectionConfig.mergeFlags(testFlags[i]['default'], testFlags[i]['user'])); assert.strictEqual(testFlags[i]['expected'], ConnectionConfig.mergeFlags(testFlags[i]['default'], testFlags[i]['user'])); } node-mysql-2.0.0~alpha8/test/integration/connection/test-ping.js0000644000175000017500000000042512140003646023437 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); var pingErr; connection.ping(function(err) { pingErr = err; }); connection.end(); process.on('exit', function() { assert.equal(pingErr, null); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-type-cast-query.js0000644000175000017500000000210012140003646025546 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({typeCast: true}); var assert = require('assert'); var util = require('util'); connection.connect(); var options = { sql : "SELECT NOW() as date, POINT(1.2,-3.4) as point", typeCast : false }; var rows; var query = connection.query(options, function(err, _rows) { if (err) throw err; rows = _rows; }); connection.end(); process.on('exit', function() { var point = rows[0].point; var byteOrder = point.readUInt8(4); var wkbType = byteOrder? point.readUInt32LE(5) : point.readUInt32BE(5); var x = byteOrder? point.readDoubleLE(9) : point.readDoubleBE(9); var y = byteOrder? point.readDoubleLE(17) : point.readDoubleBE(17); assert.strictEqual(typeof rows[0].date, 'object'); assert.equal(Buffer.isBuffer(rows[0].date), true); assert.strictEqual(typeof point, 'object'); assert.equal(Buffer.isBuffer(point), true); assert.equal(point.readUInt32LE(0), 0); // unknown assert.equal(wkbType, 1); // WKBPoint assert.equal(x, 1.2); assert.equal(y, -3.4); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-transaction-commit.js0000644000175000017500000000156612140003646026324 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); common.useTestDb(connection); var table = 'transaction_test'; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`title` varchar(255),', 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); connection.query('START TRANSACTION'); var rowCount = 10; for (var i = 1; i <= rowCount; i++) { var row = { id: i, title: 'Row #' + i, }; connection.query('INSERT INTO ' + table + ' SET ?', row); } connection.query('COMMIT'); var rows = []; var query = connection.query('SELECT * FROM ' + table, function(err, _rows) { if (err) throw err; rows = _rows; }); connection.end(); process.on('exit', function() { assert.equal(rows.length, rowCount); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-server-unexpected-disconnect.js0000644000175000017500000000146012140003646030301 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({port: common.fakeServerPort}); var assert = require('assert'); var endErr; connection.on('end', function(err) { assert.ok(!endErr); endErr = err; }); var queryErr; var server = common.createFakeServer(); server.listen(common.fakeServerPort, function(err) { if (err) throw err; connection.query('SELECT 1', function(err) { assert.ok(!queryErr); queryErr = err; }); }); server.on('connection', function(connection) { connection.handshake(); connection.on('query', function(packet) { server.destroy(); }); }); process.on('exit', function() { assert.strictEqual(queryErr.code, 'PROTOCOL_CONNECTION_LOST'); assert.strictEqual(queryErr.fatal, true); assert.strictEqual(endErr, queryErr); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-fatal-network-error-without-handlers.js0000644000175000017500000000063312140003646031707 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection({port: common.bogusPort}); var assert = require('assert'); connection.connect(); connection.query('SELECT 1'); var err; connection.on('error', function(_err) { assert.equal(err, undefined); err = _err; }); process.on('exit', function() { assert.equal(err.code, 'ECONNREFUSED'); assert.equal(err.fatal, true); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-query-dates-as-strings.js0000644000175000017500000000230412140003646027033 0ustar mikemikevar common = require('../../common'); var connection = common.createConnection(); var assert = require('assert'); var util = require('util'); common.useTestDb(connection); var table = 'dates_as_strings'; var rows; connection.query([ 'CREATE TEMPORARY TABLE `' + table + '` (', '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,', '`dt` DATE,', 'PRIMARY KEY (`id`)', ') ENGINE=InnoDB DEFAULT CHARSET=utf8' ].join('\n')); connection.query('INSERT INTO ' + table + ' SET ?', {dt: '0000-00-00'}); connection.query('INSERT INTO ' + table + ' SET ?', {dt: '2013-00-00'}); connection.query('INSERT INTO ' + table + ' SET ?', {dt: '2013-03-00'}); connection.query('INSERT INTO ' + table + ' SET ?', {dt: '2013-03-01'}); connection.query('SELECT * FROM ' + table, function(err, _rows) { if (err) throw err; rows = _rows; }); connection.end(); process.on('exit', function() { assert.equal(rows.length, 4); assert.equal(rows[0].id, 1); assert.equal(rows[0].dt, '0000-00-00'); assert.equal(rows[1].id, 2); assert.equal(rows[1].dt, '2013-00-00'); assert.equal(rows[2].id, 3); assert.equal(rows[2].dt, '2013-03-00'); assert.equal(rows[3].id, 4); assert(util.isDate(rows[3].dt)); }); node-mysql-2.0.0~alpha8/test/integration/connection/test-escape-id.js0000644000175000017500000000050112140003646024327 0ustar mikemikevar SqlString = require('../../../lib/protocol/SqlString'); var assert = require('assert'); assert.equal('`id`', SqlString.escapeId('id')); assert.equal('`i``d`', SqlString.escapeId('i`d')); assert.equal('`id1`.`id2`', SqlString.escapeId('id1.id2')); assert.equal('`id``1`.`i``d2`', SqlString.escapeId('id`1.i`d2')); node-mysql-2.0.0~alpha8/test/common.js0000644000175000017500000000346312140003646016340 0ustar mikemikevar common = exports; var path = require('path'); var _ = require('underscore'); var FakeServer = require('./FakeServer'); common.lib = path.join(__dirname, '../lib'); common.fixtures = path.join(__dirname, 'fixtures'); // Useful for triggering ECONNREFUSED errors on connect() common.bogusPort = 47378; // Useful for triggering ER_ACCESS_DENIED_ERROR errors on connect() common.bogusPassword = 'INVALID PASSWORD'; // Used for simulating a fake mysql server common.fakeServerPort = 32893; // Used for simulating a fake mysql server common.fakeServerSocket = __dirname + '/fake_server.sock'; common.testDatabase = process.env.MYSQL_DATABASE; var Mysql = require('../'); common.isTravis = function() { return Boolean(process.env.CI); }; common.createConnection = function(config) { config = mergeTestConfig(config); return Mysql.createConnection(config); }; common.createPool = function(config) { config = mergeTestConfig(config); config.createConnection = common.createConnection; return Mysql.createPool(config); }; common.createFakeServer = function(options) { return new FakeServer(_.extend({}, options)); }; common.useTestDb = function(connection) { var query = connection.query('CREATE DATABASE ' + common.testDatabase, function(err) { if (err && err.code !== 'ER_DB_CREATE_EXISTS') throw err; }); connection.query('USE ' + common.testDatabase); } function mergeTestConfig(config) { if (common.isTravis()) { // see: http://about.travis-ci.org/docs/user/database-setup/ config = _.extend({ user: 'root' }, config); } else { config = _.extend({ host : process.env.MYSQL_HOST, port : process.env.MYSQL_PORT, user : process.env.MYSQL_USER, password : process.env.MYSQL_PASSWORD }, config); } return config; } node-mysql-2.0.0~alpha8/test/unit/0000755000175000017500000000000012140003646015463 5ustar mikemikenode-mysql-2.0.0~alpha8/test/unit/protocol/0000755000175000017500000000000012140003646017324 5ustar mikemikenode-mysql-2.0.0~alpha8/test/unit/protocol/test-Parser.js0000644000175000017500000000666212140003646022105 0ustar mikemikevar common = require('../../common'); var test = require('utest'); var assert = require('assert'); var Parser = require(common.lib + '/protocol/Parser'); function packet(bytes) { var buffer = new Buffer(bytes); var parser = new Parser(); parser.append(buffer); return parser; } test('Parser', { "parseBuffer: buffer won\'t change after appending another one": function() { var startBuffer = new Buffer(5); startBuffer.fill('a'); var parser = new Parser(); parser.append(startBuffer); var value = parser.parseBuffer(4); assert.equal(value.toString(), 'aaaa'); parser.append(new Buffer('b')); assert.equal(value.toString(), 'aaaa'); }, 'parseUnsignedNumber: 1 byte': function() { var value = packet([5]).parseUnsignedNumber(1); assert.equal(value, 5); }, 'parseUnsignedNumber: 2 bytes': function() { var value = packet([1, 1]).parseUnsignedNumber(2); assert.equal(value, 256 + 1); }, 'parseUnsignedNumber: honors offsets': function() { var parser = packet([1, 2]); assert.equal(parser.parseUnsignedNumber(1), 1); assert.equal(parser.parseUnsignedNumber(1), 2); }, 'parseLengthCodedNumber: 1 byte': function() { var parser = packet([250]); assert.strictEqual(parser.parseLengthCodedNumber(), 250); }, 'parseLengthCodedNumber: 251 = null': function() { var parser = packet([251]); assert.strictEqual(parser.parseLengthCodedNumber(), null); }, 'parseLengthCodedNumber: 252 = 16 bit': function() { var parser = packet([252, 2, 1]); var expected = 2 * Math.pow(256, 0) + 1 * Math.pow(256, 1); assert.strictEqual(parser.parseLengthCodedNumber(), expected); }, 'parseLengthCodedNumber: 253 = 24 bit': function() { var parser = packet([253, 3, 2, 1]); var expected = 3 * Math.pow(256, 0) + 2 * Math.pow(256, 1) + 1 * Math.pow(256, 2); assert.strictEqual(parser.parseLengthCodedNumber(), expected); }, 'parseLengthCodedNumber: 254 = 64 bit': function() { var parser = packet([254, 8, 7, 6, 5, 4, 3, 2, 0]); var expected = 8 * Math.pow(256, 0) + 7 * Math.pow(256, 1) + 6 * Math.pow(256, 2) + 5 * Math.pow(256, 3) + 4 * Math.pow(256, 4) + 3 * Math.pow(256, 5) + 2 * Math.pow(256, 6) + 0 * Math.pow(256, 7); assert.strictEqual(parser.parseLengthCodedNumber(), expected); }, 'parseLengthCodedNumber: < 53 bit = no problemo': function() { var parser = packet([254, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00]); assert.strictEqual(parser.parseLengthCodedNumber(), Math.pow(2, 53) - 1); }, 'parseLengthCodedNumber: 53 bit = Error': function() { var parser = packet([254, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00]); assert.throws(function() { parser.parseLengthCodedNumber(); }, /precision/i); }, 'parseLengthCodedNumber: 255 = Error': function() { var parser = packet([255]); assert.throws(function() { parser.parseLengthCodedNumber(); }, /unexpected/i); }, 'parsePacketTerminatedString: regular case': function() { var parser = packet([0x48, 0x69]); parser._packetEnd = 2; var str = parser.parsePacketTerminatedString(); assert.equal(str, 'Hi'); }, 'parsePacketTerminatedString: 0x00 terminated': function() { var parser = packet([0x48, 0x69, 0x00]); parser._packetEnd = 2; var str = parser.parsePacketTerminatedString(); assert.equal(str, 'Hi'); }, }); node-mysql-2.0.0~alpha8/test/unit/protocol/test-SqlString.js0000644000175000017500000000752512140003646022576 0ustar mikemikevar common = require('../../common'); var test = require('utest'); var assert = require('assert'); var SqlString = require(common.lib + '/protocol/SqlString'); test('SqlString.escape', { 'undefined -> NULL': function() { assert.equal(SqlString.escape(undefined), 'NULL'); }, 'null -> NULL': function() { assert.equal(SqlString.escape(null), 'NULL'); }, 'booleans convert to strings': function() { assert.equal(SqlString.escape(false), 'false'); assert.equal(SqlString.escape(true), 'true'); }, 'numbers convert to strings': function() { assert.equal(SqlString.escape(5), '5'); }, 'objects are turned into key value pairs': function() { assert.equal(SqlString.escape({a: 'b', c: 'd'}), "`a` = 'b', `c` = 'd'"); }, 'objects function properties are ignored': function() { assert.equal(SqlString.escape({a: 'b', c: function() {}}), "`a` = 'b'"); }, 'nested objects are cast to strings': function() { assert.equal(SqlString.escape({a: {nested: true}}), "`a` = '[object Object]'"); }, 'arrays are turned into lists': function() { assert.equal(SqlString.escape([1, 2, 'c']), "1, 2, 'c'"); }, 'nested arrays are turned into grouped lists': function() { assert.equal(SqlString.escape([[1,2,3], [4,5,6], ['a', 'b', {nested: true}]]), "(1, 2, 3), (4, 5, 6), ('a', 'b', '[object Object]')"); }, 'nested objects inside arrays are cast to strings': function() { assert.equal(SqlString.escape([1, {nested: true}, 2]), "1, '[object Object]', 2"); }, 'strings are quoted': function() { assert.equal(SqlString.escape('Super'), "'Super'"); }, '\0 gets escaped': function() { assert.equal(SqlString.escape('Sup\0er'), "'Sup\\0er'"); }, '\b gets escaped': function() { assert.equal(SqlString.escape('Sup\ber'), "'Sup\\ber'"); }, '\n gets escaped': function() { assert.equal(SqlString.escape('Sup\ner'), "'Sup\\ner'"); }, '\r gets escaped': function() { assert.equal(SqlString.escape('Sup\rer'), "'Sup\\rer'"); }, '\t gets escaped': function() { assert.equal(SqlString.escape('Sup\ter'), "'Sup\\ter'"); }, '\\ gets escaped': function() { assert.equal(SqlString.escape('Sup\\er'), "'Sup\\\\er'"); }, '\u001a (ascii 26) gets replaced with \\Z': function() { assert.equal(SqlString.escape('Sup\u001aer'), "'Sup\\Zer'"); }, 'single quotes get escaped': function() { assert.equal(SqlString.escape('Sup\'er'), "'Sup\\'er'"); }, 'double quotes get escaped': function() { assert.equal(SqlString.escape('Sup"er'), "'Sup\\\"er'"); }, 'dates are converted to YYYY-MM-DD HH:II:SS': function() { var expected = '2012-05-07 11:42:03'; var date = new Date(Date.UTC(2012, 4, 7, 11, 42, 3)); var string = SqlString.escape(date); assert.strictEqual(string, "'" + expected + "'"); }, 'buffers are converted to hex': function() { var buffer = new Buffer([0, 1, 254, 255]); var string = SqlString.escape(buffer); assert.strictEqual(string, "X'0001feff'"); }, 'NaN -> NaN': function() { assert.equal(SqlString.escape(NaN), 'NaN'); }, 'Infinity -> Infinity': function() { assert.equal(SqlString.escape(Infinity), 'Infinity'); } }); test('SqlString.format', { 'question marks are replaced with escaped array values': function() { var sql = SqlString.format('? and ?', ['a', 'b']); assert.equal(sql, "'a' and 'b'"); }, 'extra question marks are left untouched': function() { var sql = SqlString.format('? and ?', ['a']); assert.equal(sql, "'a' and ?"); }, 'extra arguments are not used': function() { var sql = SqlString.format('? and ?', ['a', 'b', 'c']); assert.equal(sql, "'a' and 'b'"); }, 'question marks within values do not cause issues': function() { var sql = SqlString.format('? and ?', ['hello?', 'b']); assert.equal(sql, "'hello?' and 'b'"); }, }); node-mysql-2.0.0~alpha8/test/unit/test-ConnectionConfig.js0000644000175000017500000000211512140003646022222 0ustar mikemikevar common = require('../common'); var test = require('utest'); var assert = require('assert'); var Charsets = require(common.lib + '/protocol/constants/charsets'); var ConnectionConfig = require(common.lib + '/ConnectionConfig'); test('ConnectionConfig#Constructor', { 'takes user,pw,host,port,db from url string': function() { var url = 'mysql://myuser:mypass@myhost:3333/mydb'; var config = new ConnectionConfig(url); assert.equal(config.host, 'myhost'); assert.equal(config.port, 3333); assert.equal(config.user, 'myuser'); assert.equal(config.password, 'mypass'); assert.equal(config.database, 'mydb'); }, 'allows additional options via url query': function() { var url = 'mysql://myhost/mydb?debug=true&charset=BIG5_CHINESE_CI'; var config = new ConnectionConfig(url); assert.equal(config.host, 'myhost'); assert.equal(config.port, 3306); assert.equal(config.database, 'mydb'); assert.equal(config.debug, true); assert.equal(config.charsetNumber, Charsets.BIG5_CHINESE_CI); }, }); node-mysql-2.0.0~alpha8/test/fixtures/0000755000175000017500000000000012140003646016355 5ustar mikemikenode-mysql-2.0.0~alpha8/test/fixtures/data.csv0000644000175000017500000000007612140003646020006 0ustar mikemike1,Hello World 2,This is a test 3,For loading data from a file node-mysql-2.0.0~alpha8/test/FakeServer.js0000644000175000017500000001041612140003646017101 0ustar mikemike// An experimental fake MySQL server for tricky integration tests. Expanded // as needed. var Net = require('net'); var Packets = require('../lib/protocol/packets'); var PacketWriter = require('../lib/protocol/PacketWriter'); var Parser = require('../lib/protocol/Parser'); var Auth = require('../lib/protocol/Auth'); var EventEmitter = require('events').EventEmitter; var Util = require('util'); module.exports = FakeServer; Util.inherits(FakeServer, EventEmitter); function FakeServer(options) { EventEmitter.call(this); this._server = null; this._connections = []; } FakeServer.prototype.listen = function(port, cb) { this._server = Net.createServer(this._handleConnection.bind(this)); this._server.listen(port, cb); }; FakeServer.prototype._handleConnection = function(socket) { var connection = new FakeConnection(socket); this.emit('connection', connection); this._connections.push(connection); }; FakeServer.prototype.destroy = function() { this._server.close(); this._connections.forEach(function(connection) { connection.destroy(); }); }; Util.inherits(FakeConnection, EventEmitter); function FakeConnection(socket) { EventEmitter.call(this); this._socket = socket; this._parser = new Parser({onPacket: this._parsePacket.bind(this)}); this._handshakeInitializationPacket = null; this._clientAuthenticationPacket = null; this._oldPasswordPacket = null; this._handshakeOptions = {}; socket.on('data', this._handleData.bind(this)); } FakeConnection.prototype.handshake = function(options) { this._handshakeOptions = options || {}; this._handshakeInitializationPacket = new Packets.HandshakeInitializationPacket({ scrambleBuff1 : new Buffer(8), scrambleBuff2 : new Buffer(12), serverCapabilities1 : 512, // only 1 flag, PROTOCOL_41 protocol41 : true }); this._sendPacket(this._handshakeInitializationPacket); }; FakeConnection.prototype.deny = function(message, errno) { this._sendPacket(new Packets.ErrorPacket({ message: message, errno: errno, })); }; FakeConnection.prototype._sendPacket = function(packet) { var writer = new PacketWriter(); packet.write(writer); this._socket.write(writer.toBuffer(this._parser)); }; FakeConnection.prototype._handleData = function(buffer) { this._parser.write(buffer); }; FakeConnection.prototype._parsePacket = function(header) { var Packet = this._determinePacket(header); var packet = new Packet(); packet.parse(this._parser); switch (Packet) { case Packets.ClientAuthenticationPacket: this._clientAuthenticationPacket = packet; if (this._handshakeOptions.oldPassword) { this._sendPacket(new Packets.UseOldPasswordPacket()); } else { if (this._handshakeOptions.user || this._handshakeOptions.password) { throw new Error('not implemented'); } this._sendPacket(new Packets.OkPacket()); this._parser.resetPacketNumber(); } break; case Packets.OldPasswordPacket: this._oldPasswordPacket = packet; var expected = Auth.scramble323(this._handshakeInitializationPacket.scrambleBuff(), this._handshakeOptions.password); var got = packet.scrambleBuff; var toString = function(buffer) { return Array.prototype.slice.call(buffer).join(','); }; if (toString(expected) === toString(got)) { this._sendPacket(new Packets.OkPacket()); } else { this._sendPacket(new Packets.ErrorPacket()); } this._parser.resetPacketNumber(); break; case Packets.ComQueryPacket: this.emit('query', packet); break; default: throw new Error('Unexpected packet: ' + Packet.name) } }; FakeConnection.prototype._determinePacket = function() { if (!this._clientAuthenticationPacket) { return Packets.ClientAuthenticationPacket; } else if (this._handshakeOptions.oldPassword && !this._oldPasswordPacket) { return Packets.OldPasswordPacket; } var firstByte = this._parser.peak(); switch (firstByte) { case 0x03: return Packets.ComQueryPacket; default: throw new Error('Unknown packet, first byte: ' + firstByte); break; } }; FakeConnection.prototype.destroy = function() { this._socket.destroy(); }; node-mysql-2.0.0~alpha8/test/run.js0000644000175000017500000000022612140003646015646 0ustar mikemikevar options = {}; if (process.env.FILTER) { options.include = new RegExp(process.env.FILTER + '.*\\.js$'); } require('urun')(__dirname, options); node-mysql-2.0.0~alpha8/benchmark/0000755000175000017500000000000012140003646015457 5ustar mikemikenode-mysql-2.0.0~alpha8/benchmark/analyze.js0000644000175000017500000000346712140003646017472 0ustar mikemikevar script = process.cwd() + '/' + process.argv[2]; var spawn = require('child_process').spawn; var numbers = []; var boringResults = 0; var scriptRuns = 0; function runScript() { scriptRuns++; var child = spawn(process.execPath, [script]); var buffer = ''; child.stdout.on('data', function(chunk) { buffer += chunk; var offset; while ((offset = buffer.indexOf('\n')) > -1) { var number = parseInt(buffer.substr(0, offset), 10); buffer = buffer.substr(offset + 1); var maxBefore = max(); var minBefore = min(); numbers.push(number); if (maxBefore === max() && minBefore === min()) { boringResults++; } if (boringResults > 10) { boringResults = 0; child.kill(); runScript(); } } }); } function report() { console.log( 'max: %s | median: %s | sdev: %s | last: %s | min: %s | runs: %s | results: %s', max(), median(), sdev(), numbers[numbers.length - 1], min(), scriptRuns, numbers.length ); } function min() { if (!numbers.length) return undefined; return numbers.reduce(function(min, number) { return (number < min) ? number : min; }); } function max() { if (!numbers.length) return undefined; return numbers.reduce(function(max, number) { return (number > max) ? number : max; }); } function median() { return numbers[Math.floor(numbers.length / 2)]; } function sdev() { if (!numbers.length) return undefined; return Math.round(Math.sqrt(variance())); } function variance() { var t = 0, squares = 0, len = numbers.length; for (var i=0; i 0) { mergeBuffers.push(mergeBuffer.slice(0, offset)); } return mergeBuffers; } function benchmark(buffers) { var protocol = new Protocol(); protocol._handshakeInitializationPacket = true; protocol.query({typeCast: false, sql: 'SELECT ...'}); var start = +new Date; for (var i = 0; i < buffers.length; i++) { protocol.write(buffers[i]); } var duration = Date.now() - start; var hz = Math.round(options.rows / (duration / 1000)); console.log(hz); } var buffers = createBuffers(); while (true) { benchmark(buffers); } node-mysql-2.0.0~alpha8/benchmark/select-100k-blog-rows.js0000644000175000017500000000151512140003646021660 0ustar mikemikevar common = require('../test/common'); var client = common.createConnection({typeCast: false}); var rowsPerRun = 100000; client.connect(function(err) { if (err) throw err; client.query('USE node_mysql_test', function(err, results) { if (err) throw err; selectRows(); }); }); var firstSelect; var rowCount = 0; console.error('Benchmarking rows per second in hz:'); function selectRows() { firstSelect = firstSelect || Date.now(); client.query('SELECT * FROM posts', function(err, rows) { if (err) throw err; rowCount += rows.length; if (rowCount < rowsPerRun) { selectRows(); return; } var duration = (Date.now() - firstSelect) / 1000; var hz = Math.round(rowCount / duration); console.log(hz); rowCount = 0; firstSelect = null; selectRows(); }); }; node-mysql-2.0.0~alpha8/Makefile0000644000175000017500000000004612140003646015165 0ustar mikemiketest: node test/run.js .PHONY: test node-mysql-2.0.0~alpha8/package.json0000644000175000017500000000123312140003646016012 0ustar mikemike{ "author": "Felix Geisendörfer (http://debuggable.com/)", "name": "mysql", "description": "A node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed.", "version": "2.0.0-alpha8", "repository": { "type": "git", "url": "https://github.com/felixge/node-mysql" }, "main": "./index", "scripts": { "test": "make test" }, "engines": { "node": "*" }, "dependencies": { "require-all": "0.0.3", "bignumber.js": "1.0.1" }, "devDependencies": { "utest": "0.0.6", "urun": "0.0.6", "underscore": "1.3.1" }, "optionalDependencies": {} } node-mysql-2.0.0~alpha8/Readme.md0000644000175000017500000006603612140003646015257 0ustar mikemike# node-mysql [![Build Status](https://secure.travis-ci.org/felixge/node-mysql.png)](http://travis-ci.org/felixge/node-mysql) ## Install ```bash npm install mysql@2.0.0-alpha8 ``` Despite the alpha tag, this is the recommended version for new applications. For information about the previous 0.9.x releases, visit the [v0.9 branch][]. Sometimes I may also ask you to install the latest version from Github to check if a bugfix is working. In this case, please do: ``` npm install felixge/node-mysql ``` [v0.9 branch]: https://github.com/felixge/node-mysql/tree/v0.9 ## Introduction This is a node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed. Here is an example on how to use it: ```js var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', }); connection.connect(); connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution); }); connection.end(); ``` From this example, you can learn the following: * Every method you invoke on a connection is queued and executed in sequence. * Closing the connection is done using `end()` which makes sure all remaining queries are executed before sending a quit packet to the mysql server. ## Contributors Thanks goes to the people who have contributed code to this module, see the [GitHub Contributors page][]. [GitHub Contributors page]: https://github.com/felixge/node-mysql/graphs/contributors Additionally I'd like to thank the following people: * [Andrey Hristov][] (Oracle) - for helping me with protocol questions. * [Ulf Wendel][] (Oracle) - for helping me with protocol questions. [Ulf Wendel]: http://blog.ulf-wendel.de/ [Andrey Hristov]: http://andrey.hristov.com/ ## Sponsors The following companies have supported this project financially, allowing me to spend more time on it (ordered by time of contribution): * [Transloadit](http://transloadit.com) (my startup, we do file uploading & video encoding as a service, check it out) * [Joyent](http://www.joyent.com/) * [pinkbike.com](http://pinkbike.com/) * [Holiday Extras](http://www.holidayextras.co.uk/) (they are [hiring](http://join.holidayextras.co.uk/vacancy/software-engineer/)) * [Newscope](http://newscope.com/) (they are [hiring](http://www.newscope.com/stellenangebote)) If you are interested in sponsoring a day or more of my time, please [get in touch][]. [get in touch]: http://felixge.de/#consulting ## Community If you'd like to discuss this module, or ask questions about it, please use one of the following: * **Mailing list**: https://groups.google.com/forum/#!forum/node-mysql * **IRC Channel**: #node.js (on freenode.net, I pay attention to any message including the term `mysql`) ## Establishing connections The recommended way to establish a connection is this: ```js var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'example.org', user : 'bob', password : 'secret', }); connection.connect(function(err) { // connected! (unless `err` is set) }); ``` However, a connection can also be implicitly established by invoking a query: ```js var mysql = require('mysql'); var connection = mysql.createConnection(...); connection.query('SELECT 1', function(err, rows) { // connected! (unless `err` is set) }); ``` Depending on how you like to handle your errors, either method may be appropriate. Any type of connection error (handshake or network) is considered a fatal error, see the [Error Handling](#error-handling) section for more information. ## Connection options When establishing a connection, you can set the following options: * `host`: The hostname of the database you are connecting to. (Default: `localhost`) * `port`: The port number to connect to. (Default: `3306`) * `socketPath`: The path to a unix domain socket to connect to. When used `host` and `port` are ignored. * `user`: The MySQL user to authenticate as. * `password`: The password of that MySQL user. * `database`: Name of the database to use for this connection (Optional). * `charset`: The charset for the connection. (Default: `'UTF8_GENERAL_CI'`) * `timezone`: The timezone used to store local dates. (Default: `'local'`) * `insecureAuth`: Allow connecting to MySQL instances that ask for the old (insecure) authentication method. (Default: `false`) * `typeCast`: Determines if column values should be converted to native JavaScript types. (Default: `true`) * `queryFormat`: A custom query format function. See [Custom format](#custom-format). * `supportBigNumbers`: When dealing with big numbers (BIGINT and DECIMAL columns) in the database, you should enable this option (Default: `false`). * `bigNumberStrings`: Enabling both `supportBigNumbers` and `bigNumberStrings` forces big numbers (BIGINT and DECIMAL columns) to be always returned as JavaScript String objects (Default: `false`). Enabling `supportBigNumbers` but leaving `bigNumberStrings` disabled will return big numbers as String objects only when they cannot be accurately represented with [JavaScript Number objects] (http://ecma262-5.com/ELS5_HTML.htm#Section_8.5) (which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as Number objects. This option is ignored if `supportBigNumbers` is disabled. * `debug`: Prints protocol details to stdout. (Default: `false`) * `multipleStatements`: Allow multiple mysql statements per query. Be careful with this, it exposes you to SQL injection attacks. (Default: `false`) * `flags`: List of connection flags to use other than the default ones. It is also possible to blacklist default ones. For more information, check [Connection Flags](#connection-flags). In addition to passing these options as an object, you can also use a url string. For example: ```js var connection = mysql.createConnection('mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700'); ``` Note: The query values are first attempted to be parsed as JSON, and if that fails assumed to be plaintext strings. ## Terminating connections There are two ways to end a connection. Terminating a connection gracefully is done by calling the `end()` method: ```js connection.end(function(err) { // The connection is terminated now }); ``` This will make sure all previously enqueued queries are still before sending a `COM_QUIT` packet to the MySQL server. If a fatal error occurs before the `COM_QUIT` packet can be sent, an `err` argument will be provided to the callback, but the connection will be terminated regardless of that. An alternative way to end the connection is to call the `destroy()` method. This will cause an immediate termination of the underlying socket. Additionally `destroy()` guarantees that no more events or callbacks will be triggered for the connection. ```js connection.destroy(); ``` Unlike `end()` the `destroy()` method does not take a callback argument. ## Pooling connections Connections can be pooled to ease sharing a single connection, or managing multiple connections. ```js var mysql = require('mysql'); var pool = mysql.createPool({ host : 'example.org', user : 'bob', password : 'secret' }); pool.getConnection(function(err, connection) { // connected! (unless `err` is set) }); ``` When you are done with a connection, just call `connection.end()` and the connection will return to the pool, ready to be used again by someone else. ```js var mysql = require('mysql'); var pool = mysql.createPool(...); pool.getConnection(function(err, connection) { // Use the connection connection.query( 'SELECT something FROM sometable', function(err, rows) { // And done with the connection. connection.end(); // Don't use the connection here, it has been returned to the pool. }); }); ``` If you would like to close the connection and remove it from the pool, use `connection.destroy()` instead. The pool will create a new connection the next time one is needed. Connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. Connections are also cycled round-robin style, with connections being taken from the top of the pool and returning to the bottom. ## Pool options Pools accept all the same options as a connection. When creating a new connection, the options are simply passed to the connection constructor. In addition to those options pools accept a few extras: * `createConnection`: The function to use to create the connection. (Default: `mysql.createConnection`) * `waitForConnections`: Determines the pool's action when no connections are available and the limit has been reached. If `true`, the pool will queue the connection request and call it when one becomes available. If `false`, the pool will immediately call back with an error. (Default: `true`) * `connectionLimit`: The maximum number of connections to create at once. (Default: `10`) ## Switching users / altering connection state MySQL offers a changeUser command that allows you to alter the current user and other aspects of the connection without shutting down the underlying socket: ```js connection.changeUser({user : 'john'}, function(err) { if (err) throw err; }); ``` The available options for this feature are: * `user`: The name of the new user (defaults to the previous one). * `password`: The password of the new user (defaults to the previous one). * `charset`: The new charset (defaults to the previous one). * `database`: The new database (defaults to the previous one). A sometimes useful side effect of this functionality is that this function also resets any connection state (variables, transactions, etc.). Errors encountered during this operation are treated as fatal connection errors by this module. ## Server disconnects You may lose the connection to a MySQL server due to network problems, the server timing you out, or the server crashing. All of these events are considered fatal errors, and will have the `err.code = 'PROTOCOL_CONNECTION_LOST'`. See the [Error Handling](#error-handling) section for more information. The best way to handle such unexpected disconnects is shown below: ```js function handleDisconnect(connection) { connection.on('error', function(err) { if (!err.fatal) { return; } if (err.code !== 'PROTOCOL_CONNECTION_LOST') { throw err; } console.log('Re-connecting lost connection: ' + err.stack); connection = mysql.createConnection(connection.config); handleDisconnect(connection); connection.connect(); }); } handleDisconnect(connection); ``` As you can see in the example above, re-connecting a connection is done by establishing a new connection. Once terminated, an existing connection object cannot be re-connected by design. With Pool, disconnected connections will be removed from the pool freeing up space for a new connection to be created on the next getConnection call. ## Escaping query values In order to avoid SQL Injection attacks, you should always escape any user provided data before using it inside a SQL query. You can do so using the `connection.escape()` method: ```js var userId = 'some user provided value'; var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId); connection.query(sql, function(err, results) { // ... }); ``` Alternatively, you can use `?` characters as placeholders for values you would like to have escaped like this: ```js connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) { // ... }); ``` This looks similar to prepared statements in MySQL, however it really just uses the same `connection.escape()` method internally. Different value types are escaped differently, here is how: * Numbers are left untouched * Booleans are converted to `true` / `false` strings * Date objects are converted to `'YYYY-mm-dd HH:ii:ss'` strings * Buffers are converted to hex strings, e.g. `X'0fa5'` * Strings are safely escaped * Arrays are turned into list, e.g. `['a', 'b']` turns into `'a', 'b'` * Nested arrays are turned into grouped lists (for bulk inserts), e.g. `[['a', 'b'], ['c', 'd']]` turns into `('a', 'b'), ('c', 'd')` * Objects are turned into `key = 'val'` pairs. Nested objects are cast to strings. * `undefined` / `null` are converted to `NULL` * `NaN` / `Infinity` are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support. If you paid attention, you may have noticed that this escaping allows you to do neat things like this: ```js var post = {id: 1, title: 'Hello MySQL'}; var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) { // Neat! }); console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL' ``` If you feel the need to escape queries by yourself, you can also use the escaping function directly: ```js var query = "SELECT * FROM posts WHERE title=" + mysql.escape("Hello MySQL"); console.log(query); // SELECT * FROM posts WHERE title='Hello MySQL' ``` ## Escaping query identifiers If you can't trust an SQL identifier (database / table / column name) because it is provided by a user, you should escape it with `mysql.escapeId(identifier)` like this: ```js var sorter = 'date'; var query = 'SELECT * FROM posts ORDER BY ' + mysql.escapeId(sorter); console.log(query); // SELECT * FROM posts ORDER BY `date` ``` It also supports adding qualified identifiers. It will escape both parts. ```js var sorter = 'date'; var query = 'SELECT * FROM posts ORDER BY ' + mysql.escapeId('posts.' + sorter); console.log(query); // SELECT * FROM posts ORDER BY `posts`.`date` ``` Alternatively, you can use `??` characters as placeholders for identifiers you would like to have escaped like this: ```js connection.query('SELECT * FROM ?? WHERE id = ?', ['users', userId], function(err, results) { // ... }); ``` **Please note that this last character sequence is experimental and syntax might change** When you pass an Object to `.escape()` or `.query()`, `.escapeId()` is used to avoid SQL injection in object keys. ### Custom format If you prefer to have another type of query escape format, there's a connection configuration option you can use to define a custom format function. You can access the connection object if you want to use the built-in `.escape()` or any other connection function. Here's an example of how to implement another format: ```js connection.config.queryFormat = function (query, values) { if (!values) return query; return query.replace(/\:(\w+)/g, function (txt, key) { if (values.hasOwnProperty(key)) { return this.escape(values[key]); } return txt; }.bind(this)); }; connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" }); ``` ## Getting the id of an inserted row If you are inserting a row into a table with an auto increment primary key, you can retrieve the insert id like this: ```js connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result) { if (err) throw err; console.log(result.insertId); }); ``` When dealing with big numbers (above JavaScript Number precision limit), you should consider enabling `supportBigNumbers` option to be able to read the insert id as a string, otherwise it will throw. This option is also required when fetching big numbers from the database, otherwise you will get values rounded to hundreds or thousands due to the precision limit. ## Executing queries in parallel The MySQL protocol is sequential, this means that you need multiple connections to execute queries in parallel. You can use a Pool to manage connections, one simple approach is to create one connection per incoming http request. ## Streaming query rows Sometimes you may want to select large quantities of rows and process each of them as they are received. This can be done like this: ```js var query = connection.query('SELECT * FROM posts'); query .on('error', function(err) { // Handle error, an 'end' event will be emitted after this as well }) .on('fields', function(fields) { // the field packets for the rows to follow }) .on('result', function(row) { // Pausing the connnection is useful if your processing involves I/O connection.pause(); processRow(row, function() { connection.resume(); }); }) .on('end', function() { // all rows have been received }); ``` Please note a few things about the example above: * Usually you will want to receive a certain amount of rows before starting to throttle the connection using `pause()`. This number will depend on the amount and size of your rows. * `pause()` / `resume()` operate on the underlying socket and parser. You are guaranteed that no more `'result'` events will fire after calling `pause()`. * You MUST NOT provide a callback to the `query()` method when streaming rows. * The `'result'` event will fire for both rows as well as OK packets confirming the success of a INSERT/UPDATE query. Additionally you may be interested to know that it is currently not possible to stream individual row columns, they will always be buffered up entirely. If you have a good use case for streaming large fields to and from MySQL, I'd love to get your thoughts and contributions on this. ### Piping results with [Streams2](http://blog.nodejs.org/2012/12/20/streams2/) (Node v0.10+) The query object provides a convenience method `.stream([options])` that wraps query events into a [Readable](http://nodejs.org/api/stream.html#stream_class_stream_readable) Streams2 object. This stream can easily be piped downstream and provides automatic pause/resume, based on downstream congestion and the optional `highWaterMark`. The `objectMode` parameter of the stream is set to `true` by default. For example, piping query results into another stream (with a max buffer of 5 objects) is simply: ```js connection.query('SELECT * FROM posts') .stream({highWaterMark: 5}) .pipe(...); ``` ## Multiple statement queries Support for multiple statements is disabled for security reasons (it allows for SQL injection attacks if values are not properly escaped). To use this feature you have to enable it for your connection: ```js var connection = mysql.createConnection({multipleStatements: true}); ``` Once enabled, you can execute multiple statement queries like any other query: ```js connection.query('SELECT 1; SELECT 2', function(err, results) { if (err) throw err; // `results` is an array with one element for every statement in the query: console.log(results[0]); // [{1: 1}] console.log(results[1]); // [{2: 2}] }); ``` Additionally you can also stream the results of multiple statement queries: ```js var query = connection.query('SELECT 1; SELECT 2'); query .on('fields', function(fields, index) { // the fields for the result rows that follow }) .on('result', function(row, index) { // index refers to the statement this result belongs to (starts at 0) }); ``` If one of the statements in your query causes an error, the resulting Error object contains a `err.index` property which tells you which statement caused it. MySQL will also stop executing any remaining statements when an error occurs. Please note that the interface for streaming multiple statement queries is experimental and I am looking forward to feedback on it. ## Stored procedures You can call stored procedures from your queries as with any other mysql driver. If the stored procedure produces several result sets, they are exposed to you the same way as the results for multiple statement queries. ## Joins with overlapping column names When executing joins, you are likely to get result sets with overlapping column names. By default, node-mysql will overwrite colliding column names in the order the columns are received from MySQL, causing some of the received values to be unavailable. However, you can also specify that you want your columns to be nested below the table name like this: ```js var options = {sql: '...', nestTables: true}; connection.query(options, function(err, results) { /* results will be an array like this now: [{ table1: { fieldA: '...', fieldB: '...', }, table2: { fieldA: '...', fieldB: '...', }, }, ...] */ }); ``` Or use a string separator to have your results merged. ```js var options = {sql: '...', nestTables: '_'}; connection.query(options, function(err, results) { /* results will be an array like this now: [{ table1_fieldA: '...', table1_fieldB: '...', table2_fieldA: '...', table2_fieldB: '...' }, ...] */ }); ``` ## Error handling This module comes with a consistent approach to error handling that you should review carefully in order to write solid applications. All errors created by this module are instances of the JavaScript [Error][] object. Additionally they come with two properties: * `err.code`: Either a [MySQL server error][] (e.g. `'ER_ACCESS_DENIED_ERROR'`), a node.js error (e.g. `'ECONNREFUSED'`) or an internal error (e.g. `'PROTOCOL_CONNECTION_LOST'`). * `err.fatal`: Boolean, indicating if this error is terminal to the connection object. [Error]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error [MySQL server error]: http://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html Fatal errors are propagated to *all* pending callbacks. In the example below, a fatal error is triggered by trying to connect to an invalid port. Therefore the error object is propagated to both pending callbacks: ```js var connection = require('mysql').createConnection({ port: 84943, // WRONG PORT }); connection.connect(function(err) { console.log(err.code); // 'ECONNREFUSED' console.log(err.fatal); // true }); connection.query('SELECT 1', function(err) { console.log(err.code); // 'ECONNREFUSED' console.log(err.fatal); // true }); ``` Normal errors however are only delegated to the callback they belong to. So in the example below, only the first callback receives an error, the second query works as expected: ```js connection.query('USE name_of_db_that_does_not_exist', function(err, rows) { console.log(err.code); // 'ER_BAD_DB_ERROR' }); connection.query('SELECT 1', function(err, rows) { console.log(err); // null console.log(rows.length); // 1 }); ``` Last but not least: If a fatal errors occurs and there are no pending callbacks, or a normal error occurs which has no callback belonging to it, the error is emitted as an `'error'` event on the connection object. This is demonstrated in the example below: ```js connection.on('error', function(err) { console.log(err.code); // 'ER_BAD_DB_ERROR' }); connection.query('USE name_of_db_that_does_not_exist'); ``` Note: `'error'` are special in node. If they occur without an attached listener, a stack trace is printed and your process is killed. **tl;dr:** This module does not want you to deal with silent failures. You should always provide callbacks to your method calls. If you want to ignore this advice and suppress unhandled errors, you can do this: ```js // I am Chuck Norris: connection.on('error', function() {}); ``` ## Exception Safety This module is exception safe. That means you can continue to use it, even if one of your callback functions throws an error which you're catching using 'uncaughtException' or a domain. ## Type casting For your convenience, this driver will cast mysql types into native JavaScript types by default. The following mappings exist: ### Number * TINYINT * SMALLINT * INT * MEDIUMINT * YEAR * FLOAT * DOUBLE ### Date * TIMESTAMP * DATE * DATETIME ### Buffer * TINYBLOB * MEDIUMBLOB * LONGBLOB * BLOB * BINARY * VARBINARY * BIT (last byte will be filled with 0 bits as necessary) ### String * CHAR * VARCHAR * TINYTEXT * MEDIUMTEXT * LONGTEXT * TEXT * ENUM * SET * DECIMAL (may exceed float precision) * BIGINT (may exceed float precision) * TIME (could be mapped to Date, but what date would be set?) * GEOMETRY (never used those, get in touch if you do) It is not recommended (and may go away / change in the future) to disable type casting, but you can currently do so on either the connection: ```js var connection = require('mysql').createConnection({typeCast: false}); ``` Or on the query level: ```js var options = {sql: '...', typeCast: false}; var query = connection.query(options, function(err, results) { }): ``` You can also pass a function and handle type casting yourself. You're given some column information like database, table and name and also type and length. If you just want to apply a custom type casting to a specific type you can do it and then fallback to the default. Here's an example of converting `TINYINT(1)` to boolean: ```js connection.query({ sql: '...', typeCast: function (field, next) { if (field.type == 'TINY' && field.length == 1) { return (field.string() == '1'); // 1 = true, 0 = false } return next(); } }) ``` If you need a buffer there's also a `.buffer()` function and also a `.geometry()` one both used by the default type cast that you can use. ## Connection Flags If, for any reason, you would like to change the default connection flags, you can use the connection option `flags`. Pass a string with a comma separated list of items to add to the default flags. If you don't want a default flag to be used prepend the flag with a minus sign. To add a flag that is not in the default list, don't prepend it with a plus sign, just write the flag name (case insensitive). **Please note that some available flags that are not default are still not supported (e.g.: SSL, Compression). Use at your own risk.** ### Example The next example blacklists FOUND_ROWS flag from default connection flags. ```js var connection = mysql.createConnection("mysql://localhost/test?flags=-FOUND_ROWS") ``` ### Default Flags - LONG_PASSWORD - FOUND_ROWS - LONG_FLAG - CONNECT_WITH_DB - ODBC - LOCAL_FILES - IGNORE_SPACE - PROTOCOL_41 - IGNORE_SIGPIPE - TRANSACTIONS - RESERVED - SECURE_CONNECTION - MULTI_RESULTS - MULTI_STATEMENTS (used if `multipleStatements` option is activated) ### Other Available Flags - NO_SCHEMA - COMPRESS - INTERACTIVE - SSL - PS_MULTI_RESULTS - PLUGIN_AUTH - SSL_VERIFY_SERVER_CERT - REMEMBER_OPTIONS ## Debugging and reporting problems If you are running into problems, one thing that may help is enabling the `debug` mode for the connection: ```js var connection = mysql.createConnection({debug: true}); ``` This will print all incoming and outgoing packets on stdout. You can also restrict debugging to packet types by passing an array of types to debug: ```js var connection = mysql.createConnection({debug: ['ComQueryPacket', 'RowDataPacket']}); ``` to restrict debugging to the query and data packets. If that does not help, feel free to open a GitHub issue. A good GitHub issue will have: * The minimal amount of code required to reproduce the problem (if possible) * As much debugging output and information about your environment (mysql version, node version, os, etc.) as you can gather. ## Todo * Prepared statements * setTimeout() for Connection / Query * Support for encodings other than UTF-8 / ASCII * API support for transactions, similar to [php](http://www.php.net/manual/en/mysqli.quickstart.transactions.php) node-mysql-2.0.0~alpha8/.travis.yml0000644000175000017500000000006312140003646015635 0ustar mikemikelanguage: node_js node_js: - 0.4 - 0.6 - 0.8 node-mysql-2.0.0~alpha8/index.js0000644000175000017500000000127012140003646015172 0ustar mikemikevar Connection = require('./lib/Connection'); var ConnectionConfig = require('./lib/ConnectionConfig'); var Types = require('./lib/protocol/constants/types'); var SqlString = require('./lib/protocol/SqlString'); var Pool = require('./lib/Pool'); var PoolConfig = require('./lib/PoolConfig'); exports.createConnection = function(config) { return new Connection({config: new ConnectionConfig(config)}); }; exports.createPool = function(config) { return new Pool({config: new PoolConfig(config)}); }; exports.createQuery = Connection.createQuery; exports.Types = Types; exports.escape = SqlString.escape; exports.escapeId = SqlString.escapeId; node-mysql-2.0.0~alpha8/.gitignore0000644000175000017500000000005512140003646015515 0ustar mikemike*.un~ /node_modules *.sublime-* .DS_Store