ReadPostgresData.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. //
  2. // ReadPostgresData.cs
  3. //
  4. // Uses the PostgresLibrary to retrieve a recordset.
  5. // This is not meant to be used in Production, but as a
  6. // learning aid in coding class System.Data.SqlClient.SqlDataReader.
  7. //
  8. // Author:
  9. // Daniel Morgan <[email protected]>
  10. //
  11. // (C) 2002 Daniel Morgan
  12. //
  13. using System;
  14. using System.Data;
  15. using System.Runtime.InteropServices;
  16. using System.Diagnostics;
  17. namespace LearnToCreateSqlDataReader
  18. {
  19. sealed public class PostgresHelper {
  20. public static object OidTypeToSystem (int oid, string value) {
  21. object obj = null;
  22. switch(oid) {
  23. case 1043: // varchar
  24. Console.WriteLine("oid 1023 varchar ==> String found");
  25. obj = (object) String.Copy(value); // String
  26. break;
  27. case 25: // text
  28. Console.WriteLine("oid 25 text ==> String found");
  29. obj = (object) String.Copy(value); // String
  30. break;
  31. case 18: // char
  32. Console.WriteLine("oid 18 char ==> String found");
  33. obj = (object) String.Copy(value); // String
  34. break;
  35. case 16: // bool
  36. Console.WriteLine("oid 16 bool ==> Boolean found");
  37. obj = (object) Boolean.Parse(value);
  38. break;
  39. case 21: // int2
  40. Console.WriteLine("oid 21 int2 ==> Int16 found");
  41. obj = (object) Int16.Parse(value);
  42. break;
  43. case 23: // int4
  44. Console.WriteLine("oid 23 int4 ==> Int32 found");
  45. obj = (object) Int32.Parse(value);
  46. break;
  47. case 20: // int8
  48. Console.WriteLine("oid 20 int8 ==> Int64 found");
  49. obj = (object) Int64.Parse(value);
  50. break;
  51. default:
  52. Console.WriteLine("OidTypeToSystem Not Done Yet: oid: " +
  53. oid + " Value: " + value);
  54. break;
  55. }
  56. return obj;
  57. }
  58. public static Type OidToType (int oid) {
  59. Type typ = null;
  60. switch(oid) {
  61. case 1043: // varchar
  62. case 25: // text
  63. case 18: // char
  64. typ = typeof(String);
  65. break;
  66. case 16: // bool
  67. typ = typeof(Boolean);
  68. break;
  69. case 21: // int2
  70. typ = typeof(Int16);
  71. break;
  72. case 23: // int4
  73. typ = typeof(Int32);
  74. break;
  75. case 20: // int8
  76. typ = typeof(Int64);
  77. break;
  78. default:
  79. throw new NotImplementedException(
  80. "PGNI2: PostgreSQL oid type " + oid +
  81. " not mapped to .NET System Type.");
  82. }
  83. return typ;
  84. }
  85. }
  86. sealed public class PostgresLibrary {
  87. public enum ConnStatusType {
  88. CONNECTION_OK,
  89. CONNECTION_BAD,
  90. CONNECTION_STARTED,
  91. CONNECTION_MADE,
  92. CONNECTION_AWAITING_RESPONSE,
  93. CONNECTION_AUTH_OK,
  94. CONNECTION_SETENV
  95. }
  96. public enum PostgresPollingStatusType {
  97. PGRES_POLLING_FAILED = 0,
  98. PGRES_POLLING_READING,
  99. PGRES_POLLING_WRITING,
  100. PGRES_POLLING_OK,
  101. PGRES_POLLING_ACTIVE
  102. }
  103. public enum ExecStatusType {
  104. PGRES_EMPTY_QUERY = 0,
  105. PGRES_COMMAND_OK,
  106. PGRES_TUPLES_OK,
  107. PGRES_COPY_OUT,
  108. PGRES_COPY_IN,
  109. PGRES_BAD_RESPONSE,
  110. PGRES_NONFATAL_ERROR,
  111. PGRES_FATAL_ERROR
  112. }
  113. [DllImport("pq")]
  114. public static extern string PQerrorMessage (IntPtr conn);
  115. // char *PQerrorMessage(const PGconn *conn);
  116. [DllImport("pq")]
  117. public static extern IntPtr PQconnectdb(String conninfo);
  118. // PGconn *PQconnectdb(const char *conninfo)
  119. [DllImport("pq")]
  120. public static extern void PQfinish(IntPtr conn);
  121. // void PQfinish(PGconn *conn)
  122. [DllImport("pq")]
  123. public static extern IntPtr PQexec(IntPtr conn,
  124. String query);
  125. // PGresult *PQexec(PGconn *conn, const char *query);
  126. [DllImport("pq")]
  127. public static extern int PQntuples (IntPtr res);
  128. // int PQntuples(const PGresult *res);
  129. [DllImport("pq")]
  130. public static extern int PQnfields (IntPtr res);
  131. // int PQnfields(const PGresult *res);
  132. [DllImport("pq")]
  133. public static extern ConnStatusType PQstatus (IntPtr conn);
  134. // ConnStatusType PQstatus(const PGconn *conn);
  135. [DllImport("pq")]
  136. public static extern ExecStatusType PQresultStatus (IntPtr res);
  137. // ExecStatusType PQresultStatus(const PGresult *res);
  138. [DllImport("pq")]
  139. public static extern string PQresStatus (ExecStatusType status);
  140. // char *PQresStatus(ExecStatusType status);
  141. [DllImport("pq")]
  142. public static extern string PQresultErrorMessage (IntPtr res);
  143. // char *PQresultErrorMessage(const PGresult *res);
  144. [DllImport("pq")]
  145. public static extern int PQbinaryTuples (IntPtr res);
  146. // int PQbinaryTuples(const PGresult *res);
  147. [DllImport("pq")]
  148. public static extern string PQfname (IntPtr res,
  149. int field_num);
  150. // char *PQfname(const PGresult *res,
  151. // int field_num);
  152. [DllImport("pq")]
  153. public static extern int PQfnumber (IntPtr res,
  154. string field_name);
  155. // int PQfnumber(const PGresult *res,
  156. // const char *field_name);
  157. [DllImport("pq")]
  158. public static extern int PQfmod (IntPtr res, int field_num);
  159. // int PQfmod(const PGresult *res, int field_num);
  160. [DllImport("pq")]
  161. public static extern int PQftype (IntPtr res,
  162. int field_num);
  163. // Oid PQftype(const PGresult *res,
  164. // int field_num);
  165. [DllImport("pq")]
  166. public static extern int PQfsize (IntPtr res,
  167. int field_num);
  168. // int PQfsize(const PGresult *res,
  169. // int field_num);
  170. [DllImport("pq")]
  171. public static extern string PQcmdStatus (IntPtr res);
  172. // char *PQcmdStatus(PGresult *res);
  173. [DllImport("pq")]
  174. public static extern string PQoidStatus (IntPtr res);
  175. // char *PQoidStatus(const PGresult *res);
  176. [DllImport("pq")]
  177. public static extern int PQoidValue (IntPtr res);
  178. // Oid PQoidValue(const PGresult *res);
  179. [DllImport("pq")]
  180. public static extern string PQcmdTuples (IntPtr res);
  181. // char *PQcmdTuples(PGresult *res);
  182. [DllImport("pq")]
  183. public static extern string PQgetvalue (IntPtr res,
  184. int tup_num, int field_num);
  185. // char *PQgetvalue(const PGresult *res,
  186. // int tup_num, int field_num);
  187. [DllImport("pq")]
  188. public static extern int PQgetlength (IntPtr res,
  189. int tup_num, int field_num);
  190. // int PQgetlength(const PGresult *res,
  191. // int tup_num, int field_num);
  192. [DllImport("pq")]
  193. public static extern int PQgetisnull (IntPtr res,
  194. int tup_num, int field_num);
  195. // int PQgetisnull(const PGresult *res,
  196. // int tup_num, int field_num);
  197. [DllImport("pq")]
  198. public static extern void PQclear (IntPtr res);
  199. // void PQclear(PGresult *res);
  200. }
  201. public class ReadPostgresData
  202. {
  203. static void Test() {
  204. String errorMessage;
  205. IntPtr pgConn;
  206. String sConnInfo;
  207. PostgresLibrary.ConnStatusType connStatus;
  208. String sQuery;
  209. IntPtr pgResult;
  210. sConnInfo = "host=localhost dbname=test user=danmorg password=viewsonic";
  211. sQuery =
  212. "select tid, tdesc " +
  213. "from sometable ";
  214. pgConn = PostgresLibrary.PQconnectdb (sConnInfo);
  215. connStatus = PostgresLibrary.PQstatus (pgConn);
  216. if(connStatus ==
  217. PostgresLibrary.
  218. ConnStatusType.CONNECTION_OK) {
  219. Console.WriteLine("CONNECTION_OK");
  220. pgResult = PostgresLibrary.PQexec(pgConn, sQuery);
  221. PostgresLibrary.ExecStatusType execStatus;
  222. execStatus = PostgresLibrary.
  223. PQresultStatus (pgResult);
  224. if(execStatus ==
  225. PostgresLibrary.
  226. ExecStatusType.PGRES_TUPLES_OK)
  227. {
  228. Console.WriteLine("PGRES_TUPLES_OK");
  229. int nRows = PostgresLibrary.
  230. PQntuples(pgResult);
  231. Console.WriteLine("Rows: " + nRows);
  232. int nFields = PostgresLibrary.
  233. PQnfields(pgResult);
  234. Console.WriteLine("Columns: " + nFields);
  235. String fieldName;
  236. // get meta data fromm result set (schema)
  237. // for each column (field)
  238. for(int fieldIndex = 0;
  239. fieldIndex < nFields;
  240. fieldIndex ++) {
  241. // get column name
  242. fieldName = PostgresLibrary.
  243. PQfname(pgResult, fieldIndex);
  244. Console.WriteLine("Field " +
  245. fieldIndex + ": " +
  246. fieldName);
  247. int oid;
  248. // get PostgreSQL data type (OID)
  249. oid = PostgresLibrary.
  250. PQftype(pgResult, fieldIndex);
  251. Console.WriteLine("Data Type oid: " + oid);
  252. int definedSize;
  253. // get defined size of column
  254. definedSize = PostgresLibrary.
  255. PQfsize(pgResult, fieldIndex);
  256. Console.WriteLine("definedSize: " +
  257. definedSize);
  258. }
  259. // for each row and column, get the data value
  260. for(int row = 0;
  261. row < nRows;
  262. row++) {
  263. for(int col = 0;
  264. col < nFields;
  265. col++) {
  266. String value;
  267. // get data value
  268. value = PostgresLibrary.
  269. PQgetvalue(
  270. pgResult,
  271. row, col);
  272. Console.WriteLine("Row: " + row +
  273. " Col: " + col);
  274. Console.WriteLine("Value: " +
  275. value);
  276. int columnIsNull;
  277. // is column NULL?
  278. columnIsNull = PostgresLibrary.
  279. PQgetisnull(pgResult,
  280. row, col);
  281. Console.WriteLine("Data is " +
  282. (columnIsNull == 0 ? "NOT NULL" : "NULL"));
  283. int actualLength;
  284. // get Actual Length
  285. actualLength = PostgresLibrary.
  286. PQgetlength(pgResult,
  287. row, col);
  288. Console.WriteLine("Actual Length: " +
  289. actualLength);
  290. }
  291. }
  292. // close result set
  293. PostgresLibrary.PQclear (pgResult);
  294. }
  295. else {
  296. // display execution error
  297. errorMessage = PostgresLibrary.
  298. PQresStatus(execStatus);
  299. errorMessage += " " + PostgresLibrary.
  300. PQresultErrorMessage(pgResult);
  301. Console.WriteLine(errorMessage);
  302. }
  303. // close database conneciton
  304. PostgresLibrary.PQfinish(pgConn);
  305. }
  306. else {
  307. errorMessage = PostgresLibrary.
  308. PQerrorMessage (pgConn);
  309. errorMessage += ": Could not connect to database.";
  310. Console.WriteLine(errorMessage);
  311. }
  312. }
  313. public static object ExecuteScalar(string sql) {
  314. object obj = null; // return
  315. int nRow;
  316. int nCol;
  317. String errorMessage;
  318. IntPtr pgConn;
  319. String sConnInfo;
  320. PostgresLibrary.ConnStatusType connStatus;
  321. String sQuery;
  322. IntPtr pgResult;
  323. sConnInfo = "host=localhost dbname=test user=danmorg password=viewsonic";
  324. sQuery = sql;
  325. pgConn = PostgresLibrary.PQconnectdb (sConnInfo);
  326. connStatus = PostgresLibrary.PQstatus (pgConn);
  327. if(connStatus ==
  328. PostgresLibrary.
  329. ConnStatusType.CONNECTION_OK) {
  330. Console.WriteLine("CONNECTION_OK");
  331. pgResult = PostgresLibrary.PQexec(pgConn, sQuery);
  332. PostgresLibrary.ExecStatusType execStatus;
  333. execStatus = PostgresLibrary.
  334. PQresultStatus (pgResult);
  335. if(execStatus ==
  336. PostgresLibrary.
  337. ExecStatusType.PGRES_TUPLES_OK) {
  338. Console.WriteLine("PGRES_TUPLES_OK");
  339. int nRows = PostgresLibrary.
  340. PQntuples(pgResult);
  341. Console.WriteLine("Rows: " + nRows);
  342. int nFields = PostgresLibrary.
  343. PQnfields(pgResult);
  344. Console.WriteLine("Columns: " + nFields);
  345. if(nRows > 0 && nFields > 0) {
  346. nRow = 0;
  347. nCol = 0;
  348. // get column name
  349. String fieldName;
  350. fieldName = PostgresLibrary.
  351. PQfname(pgResult, nCol);
  352. Console.WriteLine("Field " +
  353. nCol + ": " +
  354. fieldName);
  355. int oid;
  356. // get PostgreSQL data type (OID)
  357. oid = PostgresLibrary.
  358. PQftype(pgResult, nCol);
  359. Console.WriteLine("Data Type oid: " + oid);
  360. int definedSize;
  361. // get defined size of column
  362. definedSize = PostgresLibrary.
  363. PQfsize(pgResult, nCol);
  364. Console.WriteLine("DefinedSize: " +
  365. definedSize);
  366. String value;
  367. // get data value
  368. value = PostgresLibrary.
  369. PQgetvalue(
  370. pgResult,
  371. nRow, nCol);
  372. Console.WriteLine("Row: " + nRow +
  373. " Col: " + nCol);
  374. Console.WriteLine("Value: " + value);
  375. int columnIsNull;
  376. // is column NULL?
  377. columnIsNull = PostgresLibrary.
  378. PQgetisnull(pgResult,
  379. nRow, nCol);
  380. Console.WriteLine("Data is " +
  381. (columnIsNull == 0 ? "NOT NULL" : "NULL"));
  382. int actualLength;
  383. // get Actual Length
  384. actualLength = PostgresLibrary.
  385. PQgetlength(pgResult,
  386. nRow, nCol);
  387. Console.WriteLine("Actual Length: " +
  388. actualLength);
  389. obj = PostgresHelper.
  390. OidTypeToSystem (oid, value);
  391. }
  392. // close result set
  393. PostgresLibrary.PQclear (pgResult);
  394. }
  395. else {
  396. // display execution error
  397. errorMessage = PostgresLibrary.
  398. PQresStatus(execStatus);
  399. errorMessage += " " + PostgresLibrary.
  400. PQresultErrorMessage(pgResult);
  401. Console.WriteLine(errorMessage);
  402. }
  403. // close database conneciton
  404. PostgresLibrary.PQfinish(pgConn);
  405. }
  406. else {
  407. errorMessage = PostgresLibrary.
  408. PQerrorMessage (pgConn);
  409. errorMessage += ": Could not connect to database.";
  410. Console.WriteLine(errorMessage);
  411. }
  412. return obj;
  413. }
  414. static void TestExecuteScalar() {
  415. String selectStatement;
  416. try {
  417. selectStatement =
  418. "select count(*) " +
  419. "from sometable";
  420. Int64 myCount = (Int64) ExecuteScalar(selectStatement);
  421. Console.WriteLine("Count: " + myCount);
  422. selectStatement =
  423. "select max(tdesc) " +
  424. "from sometable";
  425. string myMax = (string) ExecuteScalar(selectStatement);
  426. Console.WriteLine("Max: " + myMax);
  427. }
  428. catch(Exception e) {
  429. Console.WriteLine(e);
  430. }
  431. }
  432. [STAThread]
  433. static void Main(string[] args)
  434. {
  435. // Test();
  436. // TestExecuteScalar();
  437. Type t;
  438. int oid;
  439. oid = 1043;
  440. t = PostgresHelper.OidToType(oid); // varchar ==> String
  441. Console.WriteLine("OidToType varchar oid: " + oid +
  442. " ==> t: " + t.ToString());
  443. oid = 23;
  444. t = PostgresHelper.OidToType(oid); // int4 ==> Int32
  445. Console.WriteLine("OidToType int4 oid: " + oid +
  446. " ==> t: " + t.ToString());
  447. }
  448. }
  449. }