SqlSharpCli.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678
  1. //
  2. // SqlSharpCli.cs - main driver for Mono SQL Query Command Line Interface
  3. // found in mcs/tools/SqlSharp
  4. //
  5. // This program is included in Mono and is licenced under the GPL.
  6. // http://www.fsf.org/licenses/gpl.html
  7. //
  8. // For more information about Mono,
  9. // visit http://www.mono-project.com/
  10. //
  11. // To build SqlSharpCli.cs
  12. // $ mcs /out:sqlsharp.exe SqlSharpCli.cs /r:System.Data.dll
  13. //
  14. // To run with mono:
  15. // $ mono sqlsharp.exe
  16. //
  17. // To run with mint:
  18. // $ mint sqlsharp.exe
  19. //
  20. // To run batch commands and get the output, do something like:
  21. // $ cat commands_example.txt | mono sqlsharp.exe -s > results.txt
  22. //
  23. // Author:
  24. // Daniel Morgan <[email protected]>
  25. //
  26. // (C)Copyright 2002-2004 Daniel Morgan
  27. //
  28. using System;
  29. using System.Collections;
  30. using System.Data;
  31. using System.Data.Common;
  32. using System.Data.OleDb;
  33. using System.Data.SqlClient;
  34. using System.IO;
  35. using System.Reflection;
  36. using System.Runtime.Remoting;
  37. using System.Text;
  38. namespace Mono.Data.SqlSharp {
  39. public enum FileFormat {
  40. Html,
  41. Xml,
  42. CommaSeparatedValues,
  43. TabSeparated,
  44. Normal
  45. }
  46. // SQL Sharp - Command Line Interface
  47. public class SqlSharpCli
  48. {
  49. // provider supports
  50. private bool UseParameters = true;
  51. private bool UseSimpleReader = false;
  52. private IDbConnection conn = null;
  53. private string provider = ""; // name of internal provider
  54. // {OleDb,SqlClient,MySql,Odbc,Oracle,
  55. // PostgreSql,SqlLite,Sybase,Tds} however, it
  56. // can be set to LOADEXTPROVIDER to load an external provider
  57. private string providerAssembly = "";
  58. // filename of assembly
  59. // for example: "Mono.Data.MySql"
  60. private string providerConnectionClass = "";
  61. // Connection class
  62. // in the provider assembly that implements the IDbConnection
  63. // interface. for example: "Mono.Data.MySql.MySqlConnection"
  64. Type conType;
  65. private StringBuilder build = null; // SQL string to build
  66. private string buff = ""; // SQL string buffer
  67. private string connectionString = "";
  68. private string inputFilename = "";
  69. private string outputFilename = "";
  70. private StreamReader inputFilestream = null;
  71. private StreamWriter outputFilestream = null;
  72. private FileFormat outputFileFormat = FileFormat.Html;
  73. private bool silent = false;
  74. private bool showHeader = true;
  75. private Hashtable internalVariables = new Hashtable();
  76. // DisplayResult - used to Read() display a result set
  77. // called by DisplayData()
  78. public bool DisplayResult (IDataReader reader, DataTable schemaTable)
  79. {
  80. StringBuilder column = null;
  81. StringBuilder line = null;
  82. StringBuilder hdrUnderline = null;
  83. string outData = "";
  84. int hdrLen = 0;
  85. int spacing = 0;
  86. int columnSize = 0;
  87. int c;
  88. char spacingChar = ' '; // a space
  89. char underlineChar = '='; // an equal sign
  90. string dataType; // .NET Type
  91. Type theType;
  92. DataRow row; // schema row
  93. line = new StringBuilder ();
  94. hdrUnderline = new StringBuilder ();
  95. OutputLine ("");
  96. for (c = 0; c < reader.FieldCount; c++) {
  97. try {
  98. DataRow schemaRow = schemaTable.Rows [c];
  99. string columnHeader = reader.GetName (c);
  100. if (columnHeader.Equals (""))
  101. columnHeader = "column";
  102. if (columnHeader.Length > 32)
  103. columnHeader = columnHeader.Substring (0,32);
  104. // spacing
  105. columnSize = (int) schemaRow ["ColumnSize"];
  106. theType = reader.GetFieldType (c);
  107. dataType = theType.ToString ();
  108. switch (dataType) {
  109. case "System.DateTime":
  110. columnSize = 25;
  111. break;
  112. case "System.Boolean":
  113. columnSize = 5;
  114. break;
  115. case "System.Byte":
  116. columnSize = 1;
  117. break;
  118. case "System.Single":
  119. columnSize = 12;
  120. break;
  121. case "System.Double":
  122. columnSize = 21;
  123. break;
  124. case "System.Int16":
  125. case "System.Unt16":
  126. columnSize = 5;
  127. break;
  128. case "System.Int32":
  129. case "System.UInt32":
  130. columnSize = 10;
  131. break;
  132. case "System.Int64":
  133. columnSize = 19;
  134. break;
  135. case "System.UInt64":
  136. columnSize = 20;
  137. break;
  138. case "System.Decimal":
  139. columnSize = 29;
  140. break;
  141. }
  142. if (columnSize < 0)
  143. columnSize = 32;
  144. if (columnSize > 32)
  145. columnSize = 32;
  146. hdrLen = columnHeader.Length;
  147. if (hdrLen < 0)
  148. hdrLen = 0;
  149. if (hdrLen > 32)
  150. hdrLen = 32;
  151. hdrLen = System.Math.Max (hdrLen, columnSize);
  152. line.Append (columnHeader);
  153. if (columnHeader.Length < hdrLen) {
  154. spacing = hdrLen - columnHeader.Length;
  155. line.Append (spacingChar, spacing);
  156. }
  157. hdrUnderline.Append (underlineChar, hdrLen);
  158. line.Append (" ");
  159. hdrUnderline.Append (" ");
  160. }
  161. catch (Exception e) {
  162. OutputLine ("Error: Unable to display header: " + e.Message);
  163. return false;
  164. }
  165. }
  166. OutputHeader (line.ToString ());
  167. line = null;
  168. OutputHeader (hdrUnderline.ToString ());
  169. OutputHeader ("");
  170. hdrUnderline = null;
  171. int numRows = 0;
  172. // column data
  173. try {
  174. while (reader.Read ()) {
  175. numRows++;
  176. line = new StringBuilder ();
  177. for(c = 0; c < reader.FieldCount; c++) {
  178. int dataLen = 0;
  179. string dataValue = "";
  180. column = new StringBuilder ();
  181. outData = "";
  182. row = schemaTable.Rows [c];
  183. string colhdr = (string) reader.GetName (c);
  184. if (colhdr.Equals (""))
  185. colhdr = "column";
  186. if (colhdr.Length > 32)
  187. colhdr = colhdr.Substring (0, 32);
  188. columnSize = (int) row ["ColumnSize"];
  189. theType = reader.GetFieldType (c);
  190. dataType = theType.ToString ();
  191. switch (dataType) {
  192. case "System.DateTime":
  193. columnSize = 25;
  194. break;
  195. case "System.Boolean":
  196. columnSize = 5;
  197. break;
  198. case "System.Byte":
  199. columnSize = 1;
  200. break;
  201. case "System.Single":
  202. columnSize = 12;
  203. break;
  204. case "System.Double":
  205. columnSize = 21;
  206. break;
  207. case "System.Int16":
  208. case "System.Unt16":
  209. columnSize = 5;
  210. break;
  211. case "System.Int32":
  212. case "System.UInt32":
  213. columnSize = 10;
  214. break;
  215. case "System.Int64":
  216. columnSize = 19;
  217. break;
  218. case "System.UInt64":
  219. columnSize = 20;
  220. break;
  221. case "System.Decimal":
  222. columnSize = 29;
  223. break;
  224. }
  225. if (columnSize < 0)
  226. columnSize = 32;
  227. if (columnSize > 32)
  228. columnSize = 32;
  229. hdrLen = colhdr.Length;
  230. if (hdrLen < 0)
  231. hdrLen = 0;
  232. if (hdrLen > 32)
  233. hdrLen = 32;
  234. columnSize = System.Math.Max (colhdr.Length, columnSize);
  235. dataValue = "";
  236. dataLen = 0;
  237. if (!reader.IsDBNull (c)) {
  238. object o = reader.GetValue (c);
  239. if (o.GetType ().ToString ().Equals ("System.Byte[]"))
  240. dataValue = GetHexString ( (byte[]) o);
  241. else
  242. dataValue = o.ToString ();
  243. dataLen = dataValue.Length;
  244. if (dataLen <= 0) {
  245. dataValue = "";
  246. dataLen = 0;
  247. }
  248. if (dataLen > 32) {
  249. dataValue = dataValue.Substring (0, 32);
  250. dataLen = 32;
  251. }
  252. if (dataValue.Equals(""))
  253. dataLen = 0;
  254. }
  255. columnSize = System.Math.Max (columnSize, dataLen);
  256. if (dataLen < columnSize) {
  257. switch (dataType) {
  258. case "System.Byte":
  259. case "System.SByte":
  260. case "System.Int16":
  261. case "System.UInt16":
  262. case "System.Int32":
  263. case "System.UInt32":
  264. case "System.Int64":
  265. case "System.UInt64":
  266. case "System.Single":
  267. case "System.Double":
  268. case "System.Decimal":
  269. outData = dataValue.PadLeft (columnSize);
  270. break;
  271. default:
  272. outData = dataValue.PadRight (columnSize);
  273. break;
  274. }
  275. }
  276. else
  277. outData = dataValue;
  278. line.Append (outData);
  279. line.Append (" ");
  280. }
  281. OutputData (line.ToString ());
  282. }
  283. }
  284. catch (Exception rr) {
  285. OutputLine ("Error: Unable to read next row: " + rr.Message);
  286. return false;
  287. }
  288. OutputLine ("\nRows retrieved: " + numRows.ToString ());
  289. return true; // return true - success
  290. }
  291. public static string GetHexString (byte[] bytes)
  292. {
  293. string bvalue = "";
  294. if (bytes.Length > 0) {
  295. StringBuilder sb = new StringBuilder ();
  296. for (int z = 0; z < bytes.Length; z++)
  297. sb.Append (bytes [z].ToString ("x"));
  298. bvalue = "0x" + sb.ToString ();
  299. }
  300. return bvalue;
  301. }
  302. public void OutputDataToHtmlFile (IDataReader rdr, DataTable dt)
  303. {
  304. StringBuilder strHtml = new StringBuilder ();
  305. strHtml.Append ("<html> \n <head> <title>");
  306. strHtml.Append ("Results");
  307. strHtml.Append ("</title> </head>");
  308. strHtml.Append ("<body>");
  309. strHtml.Append ("<h1> Results </h1>");
  310. strHtml.Append ("<table border=1>");
  311. outputFilestream.WriteLine (strHtml.ToString ());
  312. strHtml = new StringBuilder ();
  313. strHtml.Append ("<tr>");
  314. foreach (DataRow schemaRow in dt.Rows) {
  315. strHtml.Append ("<td> <b>");
  316. object dataObj = schemaRow ["ColumnName"];
  317. string sColumnName = dataObj.ToString ();
  318. strHtml.Append (sColumnName);
  319. strHtml.Append ("</b> </td>");
  320. }
  321. strHtml.Append ("</tr>");
  322. outputFilestream.WriteLine (strHtml.ToString ());
  323. strHtml = null;
  324. int col = 0;
  325. string dataValue = "";
  326. while (rdr.Read ()) {
  327. strHtml = new StringBuilder ();
  328. strHtml.Append ("<tr>");
  329. for (col = 0; col < rdr.FieldCount; col++) {
  330. // column data
  331. if (rdr.IsDBNull (col) == true)
  332. dataValue = "NULL";
  333. else {
  334. object obj = rdr.GetValue (col);
  335. dataValue = obj.ToString ();
  336. }
  337. strHtml.Append ("<td>");
  338. strHtml.Append (dataValue);
  339. strHtml.Append ("</td>");
  340. }
  341. strHtml.Append ("\t\t</tr>");
  342. outputFilestream.WriteLine (strHtml.ToString ());
  343. strHtml = null;
  344. }
  345. outputFilestream.WriteLine (" </table> </body> \n </html>");
  346. strHtml = null;
  347. }
  348. // DisplayData - used to display any Result Sets
  349. // from execution of SQL SELECT Query or Queries
  350. // called by DisplayData.
  351. // ExecuteSql() only calls this function
  352. // for a Query, it does not get
  353. // for a Command.
  354. public void DisplayData (IDataReader reader)
  355. {
  356. DataTable schemaTable = null;
  357. int ResultSet = 0;
  358. do {
  359. // by Default, SqlDataReader has the
  360. // first Result set if any
  361. ResultSet++;
  362. OutputLine ("Display the result set " + ResultSet);
  363. schemaTable = reader.GetSchemaTable ();
  364. if (reader.FieldCount > 0) {
  365. // SQL Query (SELECT)
  366. // RecordsAffected -1 and DataTable has a reference
  367. OutputQueryResult (reader, schemaTable);
  368. }
  369. else if (reader.RecordsAffected >= 0) {
  370. // SQL Command (INSERT, UPDATE, or DELETE)
  371. // RecordsAffected >= 0
  372. Console.WriteLine ("SQL Command Records Affected: " + reader.RecordsAffected);
  373. }
  374. else {
  375. // SQL Command (not INSERT, UPDATE, nor DELETE)
  376. // RecordsAffected -1 and DataTable has a null reference
  377. Console.WriteLine ("SQL Command Executed.");
  378. }
  379. // get next result set (if anymore is left)
  380. } while (reader.NextResult ());
  381. }
  382. // display the result in a simple way
  383. // new ADO.NET providers may have not certain
  384. // things implemented yet, such as, TableSchema
  385. // support
  386. public void DisplayDataSimple (IDataReader reader)
  387. {
  388. int row = 0;
  389. Console.WriteLine ("Reading Data using simple reader...");
  390. while (reader.Read ()){
  391. row++;
  392. Console.WriteLine ("Row: " + row);
  393. for (int col = 0; col < reader.FieldCount; col++) {
  394. int co = col + 1;
  395. Console.WriteLine (" Field: " + co);
  396. string dname = (string) reader.GetName (col);
  397. if (dname == null)
  398. dname = "?column?";
  399. if (dname.Equals (String.Empty))
  400. dname = "?column?";
  401. Console.WriteLine (" Name: " + dname);
  402. string dvalue = "";
  403. if (reader.IsDBNull (col))
  404. dvalue = "(null)";
  405. else
  406. dvalue = reader.GetValue (col).ToString ();
  407. Console.WriteLine (" Value: " + dvalue);
  408. }
  409. }
  410. Console.WriteLine ("\n" + row + " ROWS RETRIEVED\n");
  411. }
  412. public void OutputQueryResult (IDataReader dreader, DataTable dtable)
  413. {
  414. if (outputFilestream == null) {
  415. DisplayResult (dreader, dtable);
  416. }
  417. else {
  418. switch (outputFileFormat) {
  419. case FileFormat.Normal:
  420. DisplayResult (dreader, dtable);
  421. break;
  422. case FileFormat.Html:
  423. OutputDataToHtmlFile (dreader, dtable);
  424. break;
  425. default:
  426. Console.WriteLine ("Error: Output data file format not supported.");
  427. break;
  428. }
  429. }
  430. }
  431. public void BuildParameters (IDbCommand cmd)
  432. {
  433. if (UseParameters == true) {
  434. ParametersBuilder parmsBuilder = new ParametersBuilder (cmd, BindVariableCharacter.Colon);
  435. Console.WriteLine ("Get Parameters (if any)...");
  436. parmsBuilder.ParseParameters ();
  437. IList parms = (IList) cmd.Parameters;
  438. Console.WriteLine ("Print each parm...");
  439. for (int p = 0; p < parms.Count; p++) {
  440. string theParmName;
  441. IDataParameter prm = (IDataParameter) parms[p];
  442. theParmName = prm.ParameterName;
  443. string inValue = "";
  444. bool found;
  445. if (parmsBuilder.ParameterMarkerCharacter == '?') {
  446. Console.Write ("Enter Parameter " +
  447. (p + 1).ToString() +
  448. ": ");
  449. inValue = Console.ReadLine();
  450. prm.Value = inValue;
  451. }
  452. else {
  453. found = GetInternalVariable (theParmName, out inValue);
  454. if (found == true) {
  455. prm.Value = inValue;
  456. }
  457. else {
  458. Console.Write ("Enter Parameter " + (p + 1).ToString () +
  459. ": " + theParmName + ": ");
  460. inValue = Console.ReadLine ();
  461. prm.Value = inValue;
  462. }
  463. }
  464. }
  465. parmsBuilder = null;
  466. }
  467. }
  468. // ExecuteSql - Execute the SQL Command(s) and/or Query(ies)
  469. public void ExecuteSql (string sql)
  470. {
  471. string msg = "";
  472. IDbCommand cmd = null;
  473. IDataReader reader = null;
  474. cmd = conn.CreateCommand();
  475. // set command properties
  476. cmd.CommandType = CommandType.Text;
  477. cmd.CommandText = sql;
  478. cmd.Connection = conn;
  479. BuildParameters (cmd);
  480. try {
  481. reader = cmd.ExecuteReader ();
  482. if (UseSimpleReader == false)
  483. DisplayData (reader);
  484. else
  485. DisplayDataSimple (reader);
  486. reader.Close ();
  487. reader = null;
  488. }
  489. catch (Exception e) {
  490. msg = "Error: " + e.Message;
  491. Console.WriteLine (msg);
  492. reader = null;
  493. }
  494. finally {
  495. cmd = null;
  496. }
  497. }
  498. // ExecuteSql - Execute the SQL Commands (no SELECTs)
  499. public void ExecuteSqlNonQuery (string sql)
  500. {
  501. string msg = "";
  502. IDbCommand cmd = null;
  503. int rowsAffected = -1;
  504. cmd = conn.CreateCommand();
  505. // set command properties
  506. cmd.CommandType = CommandType.Text;
  507. cmd.CommandText = sql;
  508. cmd.Connection = conn;
  509. BuildParameters(cmd);
  510. try {
  511. rowsAffected = cmd.ExecuteNonQuery ();
  512. cmd = null;
  513. Console.WriteLine ("Rows affected: " + rowsAffected);
  514. }
  515. catch(Exception e) {
  516. msg = "Error: " + e.Message;
  517. Console.WriteLine (msg);
  518. }
  519. finally {
  520. cmd = null;
  521. }
  522. }
  523. public void ExecuteSqlScalar(string sql)
  524. {
  525. string msg = "";
  526. IDbCommand cmd = null;
  527. string retrievedValue = "";
  528. cmd = conn.CreateCommand ();
  529. // set command properties
  530. cmd.CommandType = CommandType.Text;
  531. cmd.CommandText = sql;
  532. cmd.Connection = conn;
  533. BuildParameters(cmd);
  534. try {
  535. retrievedValue = (string) cmd.ExecuteScalar ().ToString ();
  536. Console.WriteLine ("Retrieved value: " + retrievedValue);
  537. }
  538. catch(Exception e) {
  539. msg = "Error: " + e.Message;
  540. Console.WriteLine (msg);
  541. }
  542. finally {
  543. cmd = null;
  544. }
  545. }
  546. public void ExecuteSqlXml(string sql, string[] parms)
  547. {
  548. string filename = "";
  549. if (parms.Length != 2) {
  550. Console.WriteLine ("Error: wrong number of parameters");
  551. return;
  552. }
  553. try {
  554. filename = parms [1];
  555. }
  556. catch (Exception e) {
  557. Console.WriteLine ("Error: Unable to setup output results file. " + e.Message);
  558. return;
  559. }
  560. try {
  561. IDbCommand cmd = null;
  562. cmd = conn.CreateCommand ();
  563. // set command properties
  564. cmd.CommandType = CommandType.Text;
  565. cmd.CommandText = sql;
  566. cmd.Connection = conn;
  567. BuildParameters (cmd);
  568. DataSet dataSet = new DataSet ();
  569. DbDataAdapter adapter = CreateNewDataAdapter (cmd, conn);
  570. adapter.Fill (dataSet);
  571. dataSet.WriteXml (filename);
  572. OutputLine ("Data written to xml file: " + filename);
  573. }
  574. catch (Exception exexml) {
  575. Console.WriteLine ("Error: Execute SQL XML Failure: " + exexml);
  576. }
  577. }
  578. public DbDataAdapter CreateNewDataAdapter (IDbCommand command, IDbConnection connection)
  579. {
  580. DbDataAdapter adapter = null;
  581. switch(provider) {
  582. case "OLEDB":
  583. adapter = (DbDataAdapter) new OleDbDataAdapter ();
  584. break;
  585. case "SQLCLIENT":
  586. adapter = (DbDataAdapter) new SqlDataAdapter ();
  587. break;
  588. case "LOADEXTPROVIDER":
  589. adapter = CreateExternalDataAdapter (command, connection);
  590. if (adapter == null)
  591. return null;
  592. break;
  593. default:
  594. Console.WriteLine("Error: Data Adapter not found in provider.");
  595. return null;
  596. }
  597. IDbDataAdapter dbAdapter = (IDbDataAdapter) adapter;
  598. dbAdapter.SelectCommand = command;
  599. return adapter;
  600. }
  601. public DbDataAdapter CreateExternalDataAdapter (IDbCommand command, IDbConnection connection)
  602. {
  603. DbDataAdapter adapter = null;
  604. Assembly ass = Assembly.Load (providerAssembly);
  605. Type [] types = ass.GetTypes ();
  606. foreach (Type t in types) {
  607. if (t.IsSubclassOf (typeof (System.Data.Common.DbDataAdapter))) {
  608. if (t.Namespace.Equals (conType.Namespace))
  609. adapter = (DbDataAdapter) Activator.CreateInstance (t);
  610. }
  611. }
  612. return adapter;
  613. }
  614. // like ShowHelp - but only show at the beginning
  615. // only the most important commands are shown
  616. // like help and quit
  617. public void StartupHelp ()
  618. {
  619. OutputLine (@"Type: \Q to quit");
  620. OutputLine (@" \ConnectionString to set the ConnectionString");
  621. OutputLine (@" \Provider to set the Provider:");
  622. OutputLine (@" {OleDb,SqlClient,MySql,Odbc,DB2,");
  623. OutputLine (@" Oracle,PostgreSql,Sqlite,Sybase,Tds)");
  624. OutputLine (@" \Open to open the connection");
  625. OutputLine (@" \Close to close the connection");
  626. OutputLine (@" \e to execute SQL query (SELECT)");
  627. OutputLine (@" \h to show help (all commands).");
  628. OutputLine (@" \defaults to show default variables.");
  629. OutputLine ("");
  630. }
  631. // ShowHelp - show the help - command a user can enter
  632. public void ShowHelp ()
  633. {
  634. Console.WriteLine ("");
  635. Console.WriteLine (@"Type: \Q to quit");
  636. Console.WriteLine (@" \ConnectionString to set the ConnectionString");
  637. Console.WriteLine (@" \Provider to set the Provider:");
  638. Console.WriteLine (@" {OleDb,SqlClient,MySql,Odbc,MSODBC,");
  639. Console.WriteLine (@" Oracle,PostgreSql,Sqlite,Sybase,Tds}");
  640. Console.WriteLine (@" \Open to open the connection");
  641. Console.WriteLine (@" \Close to close the connection");
  642. Console.WriteLine (@" \e to execute SQL query (SELECT)");
  643. Console.WriteLine (@" \exenonquery to execute an SQL non query (not a SELECT).");
  644. Console.WriteLine (@" \exescalar to execute SQL to get a single row and single column.");
  645. Console.WriteLine (@" \exexml FILENAME to execute SQL and save output to XML file.");
  646. Console.WriteLine (@" \f FILENAME to read a batch of SQL# commands from file.");
  647. Console.WriteLine (@" \o FILENAME to write result of commands executed to file.");
  648. Console.WriteLine (@" \load FILENAME to load from file SQL commands into SQL buffer.");
  649. Console.WriteLine (@" \save FILENAME to save SQL commands from SQL buffer to file.");
  650. Console.WriteLine (@" \h to show help (all commands).");
  651. Console.WriteLine (@" \defaults to show default variables, such as,");
  652. Console.WriteLine (@" Provider and ConnectionString.");
  653. Console.WriteLine (@" \s {TRUE, FALSE} to silent messages.");
  654. Console.WriteLine (@" \r to reset or clear the query buffer.");
  655. WaitForEnterKey ();
  656. Console.WriteLine (@" \set NAME VALUE to set an internal variable.");
  657. Console.WriteLine (@" \unset NAME to remove an internal variable.");
  658. Console.WriteLine (@" \variable NAME to display the value of an internal variable.");
  659. Console.WriteLine (@" \loadextprovider ASSEMBLY CLASS to load the provider");
  660. Console.WriteLine (@" use the complete name of its assembly and");
  661. Console.WriteLine (@" its Connection class.");
  662. Console.WriteLine (@" \print - show what's in the SQL buffer now.");
  663. Console.WriteLine (@" \UseParameters (TRUE,FALSE) to use parameters when executing SQL.");
  664. Console.WriteLine (@" \UseSimpleReader (TRUE,FALSE) to use simple reader when displaying results.");
  665. Console.WriteLine ();
  666. }
  667. public bool WaitForEnterKey ()
  668. {
  669. Console.Write("Waiting... Press Enter key to continue. ");
  670. string entry = Console.ReadLine();
  671. if (entry.ToUpper() == "Q")
  672. return false;
  673. return true;
  674. }
  675. // ShowDefaults - show defaults for connection variables
  676. public void ShowDefaults()
  677. {
  678. Console.WriteLine ();
  679. if (provider.Equals (""))
  680. Console.WriteLine ("Provider is not set.");
  681. else {
  682. Console.WriteLine ("The default Provider is " + provider);
  683. if (provider.Equals ("LOADEXTPROVIDER")) {
  684. Console.WriteLine (" Assembly: " + providerAssembly);
  685. Console.WriteLine (" Connection Class: " + providerConnectionClass);
  686. }
  687. }
  688. Console.WriteLine ();
  689. if (connectionString.Equals (""))
  690. Console.WriteLine ("ConnectionString is not set.");
  691. else {
  692. Console.WriteLine ("The default ConnectionString is: ");
  693. Console.WriteLine (" \"" + connectionString + "\"");
  694. Console.WriteLine ();
  695. }
  696. }
  697. // OpenDataSource - open connection to the data source
  698. public void OpenDataSource ()
  699. {
  700. string msg = "";
  701. OutputLine ("Opening connection...");
  702. try {
  703. switch (provider) {
  704. case "OLEDB":
  705. conn = new OleDbConnection ();
  706. break;
  707. case "SQLCLIENT":
  708. conn = new SqlConnection ();
  709. break;
  710. case "LOADEXTPROVIDER":
  711. if (LoadExternalProvider () == false)
  712. return;
  713. break;
  714. default:
  715. Console.WriteLine ("Error: Bad argument or provider not supported.");
  716. return;
  717. }
  718. } catch (Exception e) {
  719. msg = "Error: Unable to create Connection object because: " + e.Message;
  720. Console.WriteLine (msg);
  721. return;
  722. }
  723. conn.ConnectionString = connectionString;
  724. try {
  725. conn.Open ();
  726. if (conn.State == ConnectionState.Open)
  727. OutputLine ("Open was successfull.");
  728. } catch (Exception e) {
  729. msg = "Exception Caught Opening. " + e.Message;
  730. Console.WriteLine (msg);
  731. conn = null;
  732. }
  733. }
  734. // CloseDataSource - close the connection to the data source
  735. public void CloseDataSource () {
  736. string msg = "";
  737. if (conn != null) {
  738. OutputLine ("Attempt to Close...");
  739. try {
  740. conn.Close ();
  741. OutputLine ("Close was successfull.");
  742. } catch(Exception e) {
  743. msg = "Exeception Caught Closing. " + e.Message;
  744. Console.WriteLine (msg);
  745. }
  746. conn = null;
  747. }
  748. }
  749. // ChangeProvider - change the provider string variable
  750. public void ChangeProvider (string[] parms) {
  751. string[] extp;
  752. if (parms.Length == 2) {
  753. string parm = parms [1].ToUpper ();
  754. switch (parm) {
  755. case "ORACLE":
  756. extp = new string[3] {
  757. "\\loadextprovider",
  758. @"System.Data.OracleClient, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
  759. "System.Data.OracleClient.OracleConnection"};
  760. SetupExternalProvider (extp);
  761. UseParameters = false;
  762. UseSimpleReader = false;
  763. break;
  764. case "TDS":
  765. extp = new string[3] {
  766. "\\loadextprovider",
  767. @"Mono.Data.TdsClient, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756",
  768. "Mono.Data.TdsClient.TdsConnection"};
  769. SetupExternalProvider (extp);
  770. UseParameters = false;
  771. UseSimpleReader = false;
  772. break;
  773. case "SYBASE":
  774. extp = new string[3] {
  775. "\\loadextprovider",
  776. @"Mono.Data.SybaseClient, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756",
  777. "Mono.Data.SybaseClient.SybaseConnection"};
  778. SetupExternalProvider (extp);
  779. UseParameters = false;
  780. UseSimpleReader = false;
  781. break;
  782. case "MYSQL":
  783. case "MYSQLNET":
  784. extp = new string[3] {
  785. "\\loadextprovider",
  786. @"ByteFX.Data, Version=0.7.6.1, Culture=neutral, PublicKeyToken=0738eb9f132ed756",
  787. "ByteFX.Data.MySqlClient.MySqlConnection"};
  788. SetupExternalProvider (extp);
  789. UseParameters = false;
  790. UseSimpleReader = false;
  791. break;
  792. case "SQLITE":
  793. extp = new string[3] {
  794. "\\loadextprovider",
  795. @"Mono.Data.SqliteClient, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756",
  796. "Mono.Data.SqliteClient.SqliteConnection"};
  797. SetupExternalProvider (extp);
  798. UseParameters = false;
  799. UseSimpleReader = true;
  800. break;
  801. case "SQLCLIENT":
  802. UseParameters = false;
  803. UseSimpleReader = false;
  804. provider = parm;
  805. break;
  806. case "ODBC": // for MS NET 1.1 and above
  807. extp = new string[3] {
  808. "\\loadextprovider",
  809. @"System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
  810. "System.Data.Odbc.OdbcConnection"};
  811. SetupExternalProvider (extp);
  812. UseParameters = false;
  813. UseSimpleReader = false;
  814. break;
  815. case "MSODBC": // for MS NET 1.0
  816. extp = new string[3] {
  817. "\\loadextprovider",
  818. @"Microsoft.Data.Odbc, Culture=neutral, PublicKeyToken=b77a5c561934e089, Version=1.0.3300.0",
  819. "Microsoft.Data.Odbc.OdbcConnection"};
  820. SetupExternalProvider (extp);
  821. UseParameters = false;
  822. UseSimpleReader = false;
  823. break;
  824. case "OLEDB":
  825. UseParameters = false;
  826. UseSimpleReader = true;
  827. provider = parm;
  828. break;
  829. case "FIREBIRD":
  830. extp = new string[3] {
  831. "\\loadextprovider",
  832. @"FirebirdSql.Data.Firebird, Version=1.6.3.0, Culture=neutral, PublicKeyToken=e1b4f92304d7b12f",
  833. "FirebirdSql.Data.Firebird.FbConnection"};
  834. SetupExternalProvider (extp);
  835. UseParameters = false;
  836. UseSimpleReader = false;
  837. break;
  838. case "POSTGRESQL":
  839. case "NPGSQL":
  840. extp = new string[3] {
  841. "\\loadextprovider",
  842. @"Npgsql, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7",
  843. "Npgsql.NpgsqlConnection"};
  844. SetupExternalProvider (extp);
  845. UseParameters = false;
  846. UseSimpleReader = false;
  847. break;
  848. default:
  849. Console.WriteLine ("Error: " + "Bad argument or Provider not supported.");
  850. break;
  851. }
  852. OutputLine ("The default Provider is " + provider);
  853. if (provider.Equals ("LOADEXTPROVIDER")) {
  854. OutputLine (" Assembly: " +
  855. providerAssembly);
  856. OutputLine (" Connection Class: " +
  857. providerConnectionClass);
  858. }
  859. }
  860. else
  861. Console.WriteLine ("Error: provider only has one parameter.");
  862. }
  863. // ChangeConnectionString - change the connection string variable
  864. public void ChangeConnectionString (string entry)
  865. {
  866. if (entry.Length > 18)
  867. connectionString = entry.Substring (18, entry.Length - 18);
  868. else
  869. connectionString = "";
  870. }
  871. public void SetupOutputResultsFile (string[] parms) {
  872. if (parms.Length != 2) {
  873. Console.WriteLine ("Error: wrong number of parameters");
  874. return;
  875. }
  876. try {
  877. outputFilestream = new StreamWriter (parms[1]);
  878. }
  879. catch (Exception e) {
  880. Console.WriteLine ("Error: Unable to setup output results file. " + e.Message);
  881. return;
  882. }
  883. }
  884. public void SetupInputCommandsFile (string[] parms)
  885. {
  886. if (parms.Length != 2) {
  887. Console.WriteLine ("Error: wrong number of parameters");
  888. return;
  889. }
  890. try {
  891. inputFilestream = new StreamReader (parms[1]);
  892. }
  893. catch (Exception e) {
  894. Console.WriteLine ("Error: Unable to setup input commmands file. " + e.Message);
  895. return;
  896. }
  897. }
  898. public void LoadBufferFromFile (string[] parms)
  899. {
  900. if (parms.Length != 2) {
  901. Console.WriteLine ("Error: wrong number of parameters");
  902. return;
  903. }
  904. string inFilename = parms[1];
  905. try {
  906. StreamReader sr = new StreamReader (inFilename);
  907. StringBuilder buffer = new StringBuilder ();
  908. string NextLine;
  909. while ((NextLine = sr.ReadLine ()) != null) {
  910. buffer.Append (NextLine);
  911. buffer.Append ("\n");
  912. }
  913. sr.Close ();
  914. buff = buffer.ToString ();
  915. build = null;
  916. build = new StringBuilder ();
  917. build.Append(buff);
  918. }
  919. catch (Exception e) {
  920. Console.WriteLine ("Error: Unable to read file into SQL Buffer. " + e.Message);
  921. }
  922. }
  923. public void SaveBufferToFile(string[] parms)
  924. {
  925. if (parms.Length != 2) {
  926. Console.WriteLine ("Error: wrong number of parameters");
  927. return;
  928. }
  929. string outFilename = parms[1];
  930. try {
  931. StreamWriter sw = new StreamWriter (outFilename);
  932. sw.WriteLine (buff);
  933. sw.Close ();
  934. }
  935. catch (Exception e) {
  936. Console.WriteLine ("Error: Could not save SQL Buffer to file." + e.Message);
  937. }
  938. }
  939. public void SetUseParameters (string[] parms)
  940. {
  941. if (parms.Length != 2) {
  942. Console.WriteLine ("Error: wrong number of parameters");
  943. return;
  944. }
  945. string parm = parms[1].ToUpper ();
  946. if (parm.Equals ("TRUE"))
  947. UseParameters = true;
  948. else if (parm.Equals ("FALSE"))
  949. UseParameters = false;
  950. else
  951. Console.WriteLine ("Error: invalid parameter.");
  952. }
  953. public void SetUseSimpleReader (string[] parms)
  954. {
  955. if (parms.Length != 2) {
  956. Console.WriteLine ("Error: wrong number of parameters");
  957. return;
  958. }
  959. string parm = parms[1].ToUpper ();
  960. if (parm.Equals ("TRUE"))
  961. UseSimpleReader = true;
  962. else if (parm.Equals ("FALSE"))
  963. UseSimpleReader = false;
  964. else
  965. Console.WriteLine ("Error: invalid parameter.");
  966. }
  967. public void SetupSilentMode (string[] parms)
  968. {
  969. if (parms.Length != 2) {
  970. Console.WriteLine ("Error: wrong number of parameters");
  971. return;
  972. }
  973. string parm = parms[1].ToUpper ();
  974. if (parm.Equals ("TRUE"))
  975. silent = true;
  976. else if (parm.Equals ("FALSE"))
  977. silent = false;
  978. else
  979. Console.WriteLine ("Error: invalid parameter.");
  980. }
  981. public void SetInternalVariable(string[] parms)
  982. {
  983. if (parms.Length < 2) {
  984. Console.WriteLine ("Error: wrong number of parameters.");
  985. return;
  986. }
  987. string parm = parms[1];
  988. StringBuilder ps = new StringBuilder ();
  989. for (int i = 2; i < parms.Length; i++)
  990. ps.Append (parms[i]);
  991. internalVariables[parm] = ps.ToString ();
  992. }
  993. public void UnSetInternalVariable(string[] parms)
  994. {
  995. if (parms.Length != 2) {
  996. Console.WriteLine ("Error: wrong number of parameters.");
  997. return;
  998. }
  999. string parm = parms[1];
  1000. try {
  1001. internalVariables.Remove (parm);
  1002. } catch(Exception e) {
  1003. Console.WriteLine ("Error: internal variable does not exist: " + e.Message);
  1004. }
  1005. }
  1006. public void ShowInternalVariable(string[] parms)
  1007. {
  1008. string internalVariableValue = "";
  1009. if (parms.Length != 2) {
  1010. Console.WriteLine ("Error: wrong number of parameters.");
  1011. return;
  1012. }
  1013. string parm = parms[1];
  1014. if (GetInternalVariable(parm, out internalVariableValue) == true)
  1015. Console.WriteLine ("Internal Variable - Name: " +
  1016. parm + " Value: " + internalVariableValue);
  1017. }
  1018. public bool GetInternalVariable(string name, out string sValue)
  1019. {
  1020. sValue = "";
  1021. bool valueReturned = false;
  1022. try {
  1023. if (internalVariables.ContainsKey (name) == true) {
  1024. sValue = (string) internalVariables[name];
  1025. valueReturned = true;
  1026. }
  1027. else
  1028. Console.WriteLine ("Error: internal variable does not exist.");
  1029. }
  1030. catch(Exception e) {
  1031. Console.WriteLine ("Error: internal variable does not exist: "+ e.Message);
  1032. }
  1033. return valueReturned;
  1034. }
  1035. public void SetupExternalProvider(string[] parms)
  1036. {
  1037. if (parms.Length != 3) {
  1038. Console.WriteLine ("Error: Wrong number of parameters.");
  1039. return;
  1040. }
  1041. provider = "LOADEXTPROVIDER";
  1042. providerAssembly = parms[1];
  1043. providerConnectionClass = parms[2];
  1044. }
  1045. public bool LoadExternalProvider ()
  1046. {
  1047. string msg = "";
  1048. bool success = false;
  1049. // For example: for the MySQL provider in Mono.Data.MySql
  1050. // \LoadExtProvider Mono.Data.MySql Mono.Data.MySql.MySqlConnection
  1051. // \ConnectionString dbname=test
  1052. // \open
  1053. // insert into sometable (tid, tdesc, aint) values ('abc','def',12)
  1054. // \exenonquery
  1055. // \close
  1056. // \quit
  1057. try {
  1058. OutputLine ("Loading external provider...");
  1059. Assembly ps = Assembly.Load (providerAssembly);
  1060. conType = ps.GetType (providerConnectionClass);
  1061. conn = (IDbConnection) Activator.CreateInstance (conType);
  1062. success = true;
  1063. OutputLine ("External provider loaded.");
  1064. UseParameters = false;
  1065. } catch(FileNotFoundException f) {
  1066. msg = "Error: unable to load the assembly of the provider: " + providerAssembly + " : " + f.Message;
  1067. Console.WriteLine(msg);
  1068. }
  1069. catch(Exception e) {
  1070. msg = "Error: unable to load the assembly of the provider: " + providerAssembly + " : " + e.Message;
  1071. Console.WriteLine(msg);
  1072. }
  1073. return success;
  1074. }
  1075. // used for outputting message, but if silent is set,
  1076. // don't display
  1077. public void OutputLine (string line)
  1078. {
  1079. if (silent == false)
  1080. OutputData (line);
  1081. }
  1082. // used for outputting the header columns of a result
  1083. public void OutputHeader (string line)
  1084. {
  1085. if (showHeader == true)
  1086. OutputData (line);
  1087. }
  1088. // OutputData() - used for outputting data
  1089. // if an output filename is set, then the data will
  1090. // go to a file; otherwise, it will go to the Console.
  1091. public void OutputData(string line)
  1092. {
  1093. if (outputFilestream == null)
  1094. Console.WriteLine (line);
  1095. else
  1096. outputFilestream.WriteLine (line);
  1097. }
  1098. // HandleCommand - handle SqlSharpCli commands entered
  1099. public void HandleCommand (string entry)
  1100. {
  1101. string[] parms;
  1102. parms = entry.Split (new char[1] {' '});
  1103. string userCmd = parms[0].ToUpper ();
  1104. switch (userCmd) {
  1105. case "\\PROVIDER":
  1106. ChangeProvider (parms);
  1107. break;
  1108. case "\\CONNECTIONSTRING":
  1109. ChangeConnectionString (entry);
  1110. break;
  1111. case "\\LOADEXTPROVIDER":
  1112. SetupExternalProvider (parms);
  1113. break;
  1114. case "\\OPEN":
  1115. OpenDataSource ();
  1116. break;
  1117. case "\\CLOSE":
  1118. CloseDataSource ();
  1119. break;
  1120. case "\\S":
  1121. SetupSilentMode (parms);
  1122. break;
  1123. case "\\E":
  1124. case "\\EXEQUERY":
  1125. case "\\EXEREADER":
  1126. case "\\EXECUTE":
  1127. // Execute SQL Commands or Queries
  1128. if (conn == null)
  1129. Console.WriteLine ("Error: connection is not Open.");
  1130. else if (conn.State == ConnectionState.Closed)
  1131. Console.WriteLine ("Error: connection is not Open.");
  1132. else {
  1133. if (build == null)
  1134. Console.WriteLine ("Error: SQL Buffer is empty.");
  1135. else {
  1136. buff = build.ToString ();
  1137. ExecuteSql (buff);
  1138. }
  1139. build = null;
  1140. }
  1141. break;
  1142. case "\\EXENONQUERY":
  1143. if (conn == null)
  1144. Console.WriteLine ("Error: connection is not Open.");
  1145. else if (conn.State == ConnectionState.Closed)
  1146. Console.WriteLine ("Error: connection is not Open.");
  1147. else {
  1148. if (build == null)
  1149. Console.WriteLine ("Error: SQL Buffer is empty.");
  1150. else {
  1151. buff = build.ToString ();
  1152. ExecuteSqlNonQuery (buff);
  1153. }
  1154. build = null;
  1155. }
  1156. break;
  1157. case "\\EXESCALAR":
  1158. if (conn == null)
  1159. Console.WriteLine ("Error: connection is not Open.");
  1160. else if (conn.State == ConnectionState.Closed)
  1161. Console.WriteLine ("Error: connection is not Open.");
  1162. else {
  1163. if (build == null)
  1164. Console.WriteLine ("Error: SQL Buffer is empty.");
  1165. else {
  1166. buff = build.ToString ();
  1167. ExecuteSqlScalar (buff);
  1168. }
  1169. build = null;
  1170. }
  1171. break;
  1172. case "\\EXEXML":
  1173. // \exexml OUTPUT_FILENAME
  1174. if (conn == null)
  1175. Console.WriteLine ("Error: connection is not Open.");
  1176. else if (conn.State == ConnectionState.Closed)
  1177. Console.WriteLine ("Error: connection is not Open.");
  1178. else {
  1179. if (build == null)
  1180. Console.WriteLine ("Error: SQL Buffer is empty.");
  1181. else {
  1182. buff = build.ToString ();
  1183. ExecuteSqlXml (buff, parms);
  1184. }
  1185. build = null;
  1186. }
  1187. break;
  1188. case "\\F":
  1189. SetupInputCommandsFile (parms);
  1190. break;
  1191. case "\\O":
  1192. SetupOutputResultsFile (parms);
  1193. break;
  1194. case "\\LOAD":
  1195. // Load file into SQL buffer: \load FILENAME
  1196. LoadBufferFromFile (parms);
  1197. break;
  1198. case "\\SAVE":
  1199. // Save SQL buffer to file: \save FILENAME
  1200. SaveBufferToFile (parms);
  1201. break;
  1202. case "\\H":
  1203. case "\\HELP":
  1204. // Help
  1205. ShowHelp ();
  1206. break;
  1207. case "\\DEFAULTS":
  1208. // show the defaults for provider and connection strings
  1209. ShowDefaults ();
  1210. break;
  1211. case "\\Q":
  1212. case "\\QUIT":
  1213. // Quit
  1214. break;
  1215. case "\\CLEAR":
  1216. case "\\RESET":
  1217. case "\\R":
  1218. // reset (clear) the query buffer
  1219. build = null;
  1220. break;
  1221. case "\\SET":
  1222. // sets internal variable
  1223. // \set name value
  1224. SetInternalVariable (parms);
  1225. break;
  1226. case "\\UNSET":
  1227. // deletes internal variable
  1228. // \unset name
  1229. UnSetInternalVariable (parms);
  1230. break;
  1231. case "\\VARIABLE":
  1232. ShowInternalVariable (parms);
  1233. break;
  1234. case "\\PRINT":
  1235. if (build == null)
  1236. Console.WriteLine ("SQL Buffer is empty.");
  1237. else
  1238. Console.WriteLine ("SQL Bufer:\n" + buff);
  1239. break;
  1240. case "\\USEPARAMETERS":
  1241. SetUseParameters (parms);
  1242. break;
  1243. case "\\USESIMPLEREADER":
  1244. SetUseSimpleReader (parms);
  1245. break;
  1246. default:
  1247. // Error
  1248. Console.WriteLine ("Error: Unknown user command.");
  1249. break;
  1250. }
  1251. }
  1252. public void DealWithArgs(string[] args)
  1253. {
  1254. for (int a = 0; a < args.Length; a++) {
  1255. if (args[a].Substring (0,1).Equals ("-")) {
  1256. string arg = args [a].ToUpper ().Substring (1, args [a].Length - 1);
  1257. switch (arg) {
  1258. case "S":
  1259. silent = true;
  1260. break;
  1261. case "F":
  1262. if (a + 1 >= args.Length)
  1263. Console.WriteLine ("Error: Missing FILENAME for -f switch");
  1264. else {
  1265. inputFilename = args [a + 1];
  1266. inputFilestream = new StreamReader (inputFilename);
  1267. }
  1268. break;
  1269. case "O":
  1270. if (a + 1 >= args.Length)
  1271. Console.WriteLine ("Error: Missing FILENAME for -o switch");
  1272. else {
  1273. outputFilename = args [a + 1];
  1274. outputFilestream = new StreamWriter (outputFilename);
  1275. }
  1276. break;
  1277. default:
  1278. Console.WriteLine ("Error: Unknow switch: " + args [a]);
  1279. break;
  1280. }
  1281. }
  1282. }
  1283. }
  1284. public string ReadSqlSharpCommand()
  1285. {
  1286. string entry = "";
  1287. if (inputFilestream == null) {
  1288. if (silent == false)
  1289. Console.Error.Write ("\nSQL# ");
  1290. entry = Console.ReadLine ();
  1291. }
  1292. else {
  1293. try {
  1294. entry = inputFilestream.ReadLine ();
  1295. if (entry == null) {
  1296. OutputLine ("Executing SQL# Commands from file done.");
  1297. }
  1298. }
  1299. catch (Exception e) {
  1300. Console.WriteLine ("Error: Reading command from file: " + e.Message);
  1301. }
  1302. if (silent == false)
  1303. Console.Error.Write ("\nSQL# ");
  1304. entry = Console.ReadLine ();
  1305. }
  1306. return entry;
  1307. }
  1308. public void Run (string[] args)
  1309. {
  1310. DealWithArgs (args);
  1311. string entry = "";
  1312. build = null;
  1313. if (silent == false) {
  1314. Console.WriteLine ("Welcome to SQL#. The interactive SQL command-line client ");
  1315. Console.WriteLine ("for Mono.Data. See http://www.mono-project.com/ for more details.\n");
  1316. StartupHelp ();
  1317. ShowDefaults ();
  1318. }
  1319. while (entry.ToUpper ().Equals ("\\Q") == false &&
  1320. entry.ToUpper ().Equals ("\\QUIT") == false) {
  1321. while ((entry = ReadSqlSharpCommand ()) == "") {}
  1322. if (entry.Substring(0,1).Equals ("\\")) {
  1323. HandleCommand (entry);
  1324. }
  1325. else if (entry.IndexOf(";") >= 0) {
  1326. // most likely the end of SQL Command or Query found
  1327. // execute the SQL
  1328. if (conn == null)
  1329. Console.WriteLine ("Error: connection is not Open.");
  1330. else if (conn.State == ConnectionState.Closed)
  1331. Console.WriteLine ("Error: connection is not Open.");
  1332. else {
  1333. if (build == null) {
  1334. build = new StringBuilder ();
  1335. }
  1336. build.Append (entry);
  1337. //build.Append ("\n");
  1338. buff = build.ToString ();
  1339. ExecuteSql (buff);
  1340. build = null;
  1341. }
  1342. }
  1343. else {
  1344. // most likely a part of a SQL Command or Query found
  1345. // append this part of the SQL
  1346. if (build == null) {
  1347. build = new StringBuilder ();
  1348. }
  1349. build.Append (entry + "\n");
  1350. buff = build.ToString ();
  1351. }
  1352. }
  1353. CloseDataSource ();
  1354. if (outputFilestream != null)
  1355. outputFilestream.Close ();
  1356. }
  1357. }
  1358. public enum BindVariableCharacter {
  1359. Colon, // ':' - named parameter - :name
  1360. At, // '@' - named parameter - @name
  1361. QuestionMark, // '?' - positioned parameter - ?
  1362. SquareBrackets // '[]' - delimited named parameter - [name]
  1363. }
  1364. public class ParametersBuilder
  1365. {
  1366. private BindVariableCharacter bindCharSetting;
  1367. private char bindChar;
  1368. private IDataParameterCollection parms;
  1369. private string sql;
  1370. private IDbCommand cmd;
  1371. private void SetBindCharacter ()
  1372. {
  1373. switch(bindCharSetting) {
  1374. case BindVariableCharacter.Colon:
  1375. bindChar = ':';
  1376. break;
  1377. case BindVariableCharacter.At:
  1378. bindChar = '@';
  1379. break;
  1380. case BindVariableCharacter.SquareBrackets:
  1381. bindChar = '[';
  1382. break;
  1383. case BindVariableCharacter.QuestionMark:
  1384. bindChar = '?';
  1385. break;
  1386. }
  1387. }
  1388. public ParametersBuilder (IDbCommand command, BindVariableCharacter bindVarChar)
  1389. {
  1390. cmd = command;
  1391. sql = cmd.CommandText;
  1392. parms = cmd.Parameters;
  1393. bindCharSetting = bindVarChar;
  1394. SetBindCharacter();
  1395. }
  1396. public char ParameterMarkerCharacter {
  1397. get {
  1398. return bindChar;
  1399. }
  1400. }
  1401. public int ParseParameters ()
  1402. {
  1403. int numParms = 0;
  1404. IDataParameterCollection parms = cmd.Parameters;
  1405. char[] chars = sql.ToCharArray ();
  1406. bool bStringConstFound = false;
  1407. for (int i = 0; i < chars.Length; i++) {
  1408. if (chars[i] == '\'') {
  1409. if (bStringConstFound == true)
  1410. bStringConstFound = false;
  1411. else
  1412. bStringConstFound = true;
  1413. }
  1414. else if (chars[i] == bindChar &&
  1415. bStringConstFound == false) {
  1416. if (bindChar != '?') {
  1417. StringBuilder parm = new StringBuilder ();
  1418. i++;
  1419. if (bindChar.Equals ('[')) {
  1420. bool endingBracketFound = false;
  1421. while (i <= chars.Length) {
  1422. char ch;
  1423. if (i == chars.Length)
  1424. ch = ' '; // a space
  1425. else
  1426. ch = chars[i];
  1427. if (Char.IsLetterOrDigit (ch) || ch == ' ') {
  1428. parm.Append (ch);
  1429. }
  1430. else if (ch == ']') {
  1431. endingBracketFound = true;
  1432. string p = parm.ToString ();
  1433. AddParameter (p);
  1434. numParms ++;
  1435. break;
  1436. }
  1437. else throw new Exception("SQL Parser Error: Invalid character in parameter name");
  1438. i++;
  1439. }
  1440. i--;
  1441. if (endingBracketFound == false)
  1442. throw new Exception("SQL Parser Error: Ending bracket not found for parameter");
  1443. }
  1444. else {
  1445. while (i <= chars.Length) {
  1446. char ch;
  1447. if (i == chars.Length)
  1448. ch = ' '; // a space
  1449. else
  1450. ch = chars[i];
  1451. if (Char.IsLetterOrDigit(ch)) {
  1452. parm.Append (ch);
  1453. }
  1454. else {
  1455. string p = parm.ToString ();
  1456. AddParameter (p);
  1457. numParms ++;
  1458. break;
  1459. }
  1460. i++;
  1461. }
  1462. i--;
  1463. }
  1464. }
  1465. else {
  1466. // placeholder paramaeter for ?
  1467. string p = numParms.ToString ();
  1468. AddParameter (p);
  1469. numParms ++;
  1470. }
  1471. }
  1472. }
  1473. return numParms;
  1474. }
  1475. public void AddParameter (string p)
  1476. {
  1477. Console.WriteLine ("Add Parameter: " + p);
  1478. if (parms.Contains (p) == false) {
  1479. IDataParameter prm = cmd.CreateParameter ();
  1480. prm.ParameterName = p;
  1481. prm.Direction = ParameterDirection.Input;
  1482. prm.DbType = DbType.String; // default
  1483. prm.Value = ""; // default
  1484. cmd.Parameters.Add(prm);
  1485. }
  1486. }
  1487. }
  1488. public class SqlSharpDriver
  1489. {
  1490. public static void Main (string[] args)
  1491. {
  1492. SqlSharpCli sqlCommandLineEngine = new SqlSharpCli ();
  1493. sqlCommandLineEngine.Run (args);
  1494. }
  1495. }
  1496. }