1 /++ 2 Functions to escape special characters in mysql strings 3 +/ 4 module mysql.escape; 5 6 7 /++ 8 Simple escape function for dangerous SQL characters 9 10 Params: 11 input = string to escape 12 buffer = buffer to use for the output 13 +/ 14 void mysql_escape ( Buffer, Input ) ( Input input, Buffer buffer ) 15 { 16 import std.string : translate; 17 18 immutable string[dchar] transTable = [ 19 '\\' : "\\\\", 20 '\'' : "\\'", 21 '\0' : "\\0", 22 '\n' : "\\n", 23 '\r' : "\\r", 24 '"' : "\\\"", 25 '\032' : "\\Z" 26 ]; 27 28 translate(input, transTable, null, buffer); 29 } 30 31 32 /++ 33 Struct to wrap around a string so it can be passed to formattedWrite and be 34 properly escaped all using the buffer that formattedWrite provides. 35 36 Template Params: 37 Input = Type of the input 38 +/ 39 struct MysqlEscape ( Input ) 40 { 41 Input input; 42 43 const void toString ( scope void delegate(const(char)[]) sink ) 44 { 45 struct SinkOutputRange 46 { 47 void put ( const(char)[] t ) { sink(t); } 48 } 49 50 SinkOutputRange r; 51 mysql_escape(input, r); 52 } 53 } 54 55 /++ 56 Helper function to easily construct a escape wrapper struct 57 58 Template Params: 59 T = type of the input 60 61 Params: 62 input = input to escape 63 +/ 64 MysqlEscape!(T) mysqlEscape ( T ) ( T input ) 65 { 66 return MysqlEscape!(T)(input); 67 } 68 69 unittest 70 { 71 import std.array : appender; 72 73 auto buf = appender!string(); 74 75 import std.format : formattedWrite; 76 77 formattedWrite(buf, "%s, %s, %s, mkay?", 1, 2, 78 mysqlEscape("\0, \r, \n, \", \\")); 79 80 assert(buf.data() == `1, 2, \0, \r, \n, \", \\, mkay?`); 81 }