aboutsummaryrefslogtreecommitdiff
path: root/src/interfaces/jdbc/example
diff options
context:
space:
mode:
Diffstat (limited to 'src/interfaces/jdbc/example')
-rw-r--r--src/interfaces/jdbc/example/ImageViewer.java517
-rw-r--r--src/interfaces/jdbc/example/Unicode.java276
-rw-r--r--src/interfaces/jdbc/example/basic.java219
-rw-r--r--src/interfaces/jdbc/example/blobtest.java255
-rw-r--r--src/interfaces/jdbc/example/corba/StockClient.java348
-rw-r--r--src/interfaces/jdbc/example/corba/StockDB.java134
-rw-r--r--src/interfaces/jdbc/example/corba/StockDispenserImpl.java92
-rw-r--r--src/interfaces/jdbc/example/corba/StockItemImpl.java208
-rw-r--r--src/interfaces/jdbc/example/corba/StockServer.java58
-rw-r--r--src/interfaces/jdbc/example/corba/readme34
-rwxr-xr-xsrc/interfaces/jdbc/example/corba/stock.idl40
-rw-r--r--src/interfaces/jdbc/example/corba/stock.sql27
-rw-r--r--src/interfaces/jdbc/example/datestyle.java186
-rw-r--r--src/interfaces/jdbc/example/metadata.java296
-rw-r--r--src/interfaces/jdbc/example/psql.java234
-rw-r--r--src/interfaces/jdbc/example/threadsafe.java402
16 files changed, 0 insertions, 3326 deletions
diff --git a/src/interfaces/jdbc/example/ImageViewer.java b/src/interfaces/jdbc/example/ImageViewer.java
deleted file mode 100644
index 0401780b5ca..00000000000
--- a/src/interfaces/jdbc/example/ImageViewer.java
+++ /dev/null
@@ -1,517 +0,0 @@
-package example;
-
-import java.awt.*;
-import java.awt.event.*;
-import java.io.*;
-import java.sql.*;
-import org.postgresql.largeobject.*;
-
-/*
- * This example is a small application that stores and displays images
- * held on a postgresql database.
- *
- * Before running this application, you need to create a database, and
- * on the first time you run it, select "Initialise" in the "PostgreSQL"
- * menu.
- *
- * Important note: You will notice we import the org.postgresql.largeobject
- * package, but don't import the org.postgresql package. The reason for this is
- * that importing postgresql can confuse javac (we have conflicting class names
- * in org.postgresql.* and java.sql.*). This doesn't cause any problems, as
- * long as no code imports org.postgresql.
- *
- * Under normal circumstances, code using any jdbc driver only needs to import
- * java.sql, so this isn't a problem.
- *
- * It's only if you use the non jdbc facilities, do you have to take this into
- * account.
- *
- * Note: For PostgreSQL 6.4, the driver is now Thread safe, so this example
- * application has been updated to use multiple threads, especially in the
- * image storing and retrieving methods.
- */
-
-public class ImageViewer implements ItemListener
-{
- Connection db;
- Statement stat;
- LargeObjectManager lom;
- Frame frame;
- Label label; // Label used to display the current name
- List list; // The list of available images
- imageCanvas canvas; // Canvas used to display the image
- String currentImage; // The current images name
-
- // This is a simple component to display our image
- public class imageCanvas extends Canvas
- {
- // holds the image
- private Image image;
-
- // holds the background buffer
- private Image bkg;
-
- // the size of the buffer
- private Dimension size;
-
- public imageCanvas()
- {
- image = null;
- }
-
- public void setImage(Image img)
- {
- image = img;
- repaint();
- }
-
- // This defines our minimum size
- public Dimension getMinimumSize()
- {
- return new Dimension(400, 400);
- }
-
- public Dimension getPreferedSize()
- {
- return getMinimumSize();
- }
-
- public void update(Graphics g)
- {
- paint(g);
- }
-
- /*
- * Paints the image, using double buffering to prevent screen flicker
- */
- public void paint(Graphics gr)
- {
- Dimension s = getSize();
-
- if (size == null || bkg == null || !s.equals(size))
- {
- size = s;
- bkg = createImage(size.width, size.height);
- }
-
- // now set the background
- Graphics g = bkg.getGraphics();
- g.setColor(Color.gray);
- g.fillRect(0, 0, s.width, s.height);
-
- // now paint the image over the background
- if (image != null)
- g.drawImage(image, 0, 0, this);
-
- // dispose the graphics instance
- g.dispose();
-
- // paint the image onto the component
- gr.drawImage(bkg, 0, 0, this);
-
- }
-
- }
-
- public ImageViewer(Frame f, String url, String user, String password) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
- {
- frame = f;
-
- MenuBar mb = new MenuBar();
- Menu m;
- MenuItem i;
-
- f.setMenuBar(mb);
- mb.add(m = new Menu("PostgreSQL"));
- m.add(i = new MenuItem("Initialise"));
- i.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- ImageViewer.this.init();
- }
- }
- );
-
- m.add(i = new MenuItem("Exit"));
- ActionListener exitListener = new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- ImageViewer.this.close();
- }
- };
- m.addActionListener(exitListener);
-
- mb.add(m = new Menu("Image"));
- m.add(i = new MenuItem("Import"));
- ActionListener importListener = new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- ImageViewer.this.importImage();
- }
- };
- i.addActionListener(importListener);
-
- m.add(i = new MenuItem("Remove"));
- ActionListener removeListener = new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- ImageViewer.this.removeImage();
- }
- };
- i.addActionListener(removeListener);
-
- // To the north is a label used to display the current images name
- f.add("North", label = new Label());
-
- // We have a panel to the south of the frame containing the controls
- Panel p = new Panel();
- p.setLayout(new FlowLayout());
- Button b;
- p.add(b = new Button("Refresh List"));
- b.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- ImageViewer.this.refreshList();
- }
- }
- );
- p.add(b = new Button("Import new image"));
- b.addActionListener(importListener);
- p.add(b = new Button("Remove image"));
- b.addActionListener(removeListener);
- p.add(b = new Button("Quit"));
- b.addActionListener(exitListener);
- f.add("South", p);
-
- // And a panel to the west containing the list of available images
- f.add("West", list = new List());
- list.addItemListener(this);
-
- // Finally the centre contains our image
- f.add("Center", canvas = new imageCanvas());
-
- // Load the driver
- Class.forName("org.postgresql.Driver");
-
- // Connect to database
- db = DriverManager.getConnection(url, user, password);
-
- // Create a statement
- stat = db.createStatement();
-
- // Also, get the LargeObjectManager for this connection
- lom = ((org.postgresql.PGConnection)db).getLargeObjectAPI();
-
- // Now refresh the image selection list
- refreshList();
- }
-
-
- /*
- * This method initialises the database by creating a table that contains
- * the image names, and Large Object OID's
- */
- public void init()
- {
- try
- {
- //db.setAutoCommit(true);
- stat.executeUpdate("create table images (imgname name,imgoid oid)");
- label.setText("Initialised database");
- db.commit();
- }
- catch (SQLException ex)
- {
- label.setText(ex.toString());
- }
-
- // This must run outside the previous try{} catch{} segment
- //try {
- //db.setAutoCommit(true);
- //} catch(SQLException ex) {
- //label.setText(ex.toString());
- //}
- }
-
- /*
- * This closes the connection, and ends the application
- */
- public void close()
- {
- try
- {
- db.close();
- }
- catch (SQLException ex)
- {
- System.err.println(ex.toString());
- }
- System.exit(0);
- }
-
- /*
- * This imports an image into the database, using a Thread to do this in the
- * background.
- */
- public void importImage()
- {
- FileDialog d = new FileDialog(frame, "Import Image", FileDialog.LOAD);
- d.setVisible(true);
- String name = d.getFile();
- String dir = d.getDirectory();
- d.dispose();
-
- // now start the true importer
- Thread t = new importer(db, name, dir);
- //t.setPriority(Thread.MAX_PRIORITY);
- t.start();
- }
-
- /*
- * This is an example of using a thread to import a file into a Large Object.
- * It uses the Large Object extension, to write blocks of the file to the
- * database.
- */
- class importer extends Thread
- {
- String name, dir;
- Connection db;
-
- public importer(Connection db, String name, String dir)
- {
- this.db = db;
- this.name = name;
- this.dir = dir;
- }
-
- public void run()
- {
- // Now the real import stuff
- if (name != null && dir != null)
- {
- Statement stat = null;
-
- try
- {
- // fetch the large object manager
- LargeObjectManager lom = ((org.postgresql.PGConnection)db).getLargeObjectAPI();
-
- db.setAutoCommit(false);
-
- // A temporary buffer - this can be as large as you like
- byte buf[] = new byte[2048];
-
- // Open the file
- FileInputStream fis = new FileInputStream(new File(dir, name));
-
- // Now create the large object
- int oid = lom.create();
- LargeObject blob = lom.open(oid);
-
- // Now copy the file into the object.
- //
- // Note: we dont use write(buf), as the last block is rarely the same
- // size as our buffer, so we have to use the amount read.
- int s, t = 0;
- while ((s = fis.read(buf, 0, buf.length)) > 0)
- {
- t += s;
- blob.write(buf, 0, s);
- }
-
- // Close the object
- blob.close();
-
- // Now store the entry into the table
-
- // As we are a different thread to the other window, we must use
- // our own thread
- stat = db.createStatement();
- stat.executeUpdate("insert into images values ('" + name + "'," + oid + ")");
- db.commit();
- db.setAutoCommit(false);
-
- // Finally refresh the names list, and display the current image
- ImageViewer.this.refreshList();
- ImageViewer.this.displayImage(name);
- }
- catch (Exception ex)
- {
- label.setText(ex.toString());
- }
- finally
- {
- // ensure the statement is closed after us
- try
- {
- if (stat != null)
- stat.close();
- }
- catch (SQLException se)
- {
- System.err.println("closing of Statement failed");
- }
- }
- }
- }
- }
-
- /*
- * This refreshes the list of available images
- */
- public void refreshList()
- {
- try
- {
- // First, we'll run a query, retrieving all of the image names
- ResultSet rs = stat.executeQuery("select imgname from images order by imgname");
- if (rs != null)
- {
- list.removeAll();
- while (rs.next())
- list.addItem(rs.getString(1));
- rs.close();
- }
- }
- catch (SQLException ex)
- {
- label.setText(ex.toString() + " Have you initialised the database?");
- }
- }
-
- /*
- * This removes an image from the database
- *
- * Note: With postgresql, this is the only way of deleting a large object
- * using Java.
- */
- public void removeImage()
- {
- try
- {
- //
- // Delete any large objects for the current name
- //
- // Note: We don't need to worry about being in a transaction
- // here, because we are not opening any blobs, only deleting
- // them
- //
- ResultSet rs = stat.executeQuery("select imgoid from images where imgname='" + currentImage + "'");
- if (rs != null)
- {
- // Even though there should only be one image, we still have to
- // cycle through the ResultSet
- while (rs.next())
- {
- lom.delete(rs.getInt(1));
- }
- }
- rs.close();
-
- // Finally delete any entries for that name
- stat.executeUpdate("delete from images where imgname='" + currentImage + "'");
-
- label.setText(currentImage + " deleted");
- currentImage = null;
- refreshList();
- }
- catch (SQLException ex)
- {
- label.setText(ex.toString());
- }
- }
-
- /*
- * This displays an image from the database.
- *
- * For images, this is the easiest method.
- */
- public void displayImage(String name)
- {
- try
- {
- //
- // Now as we are opening and reading a large object we must
- // turn on Transactions. This includes the ResultSet.getBytes()
- // method when it's used on a field of type oid!
- //
- db.setAutoCommit(false);
-
- ResultSet rs = stat.executeQuery("select imgoid from images where imgname='" + name + "'");
- if (rs != null)
- {
- // Even though there should only be one image, we still have to
- // cycle through the ResultSet
- while (rs.next())
- {
- canvas.setImage(canvas.getToolkit().createImage(rs.getBytes(1)));
- label.setText(currentImage = name);
- }
- }
- rs.close();
- }
- catch (SQLException ex)
- {
- label.setText(ex.toString());
- }
- finally
- {
- try
- {
- db.setAutoCommit(true);
- }
- catch (SQLException ex2)
- {}
- }
- }
-
- public void itemStateChanged(ItemEvent e)
- {
- displayImage(list.getItem(((Integer)e.getItem()).intValue()));
- }
-
- /*
- * This is the command line instructions
- */
- public static void instructions()
- {
- System.err.println("java example.ImageViewer jdbc-url user password");
- System.err.println("\nExamples:\n");
- System.err.println("java -Djdbc.driver=org.postgresql.Driver example.ImageViewer jdbc:postgresql:test postgres password\n");
-
- System.err.println("This example tests the binary large object api of the driver.\nBasically, it will allow you to store and view images held in the database.");
- System.err.println("Note: If you are running this for the first time on a particular database,\nyou have to select \"Initialise\" in the \"PostgreSQL\" menu.\nThis will create a table used to store image names.");
- }
-
- /*
- * This is the application entry point
- */
- public static void main(String args[])
- {
- if (args.length != 3)
- {
- instructions();
- System.exit(1);
- }
-
- try
- {
- Frame frame = new Frame("PostgreSQL ImageViewer v7.0 rev 1");
- frame.setLayout(new BorderLayout());
- ImageViewer viewer = new ImageViewer(frame, args[0], args[1], args[2]);
- frame.pack();
- frame.setLocation(0, 50);
- frame.setVisible(true);
- }
- catch (Exception ex)
- {
- System.err.println("Exception caught.\n" + ex);
- ex.printStackTrace();
- }
- }
-}
diff --git a/src/interfaces/jdbc/example/Unicode.java b/src/interfaces/jdbc/example/Unicode.java
deleted file mode 100644
index b1d1db299c6..00000000000
--- a/src/interfaces/jdbc/example/Unicode.java
+++ /dev/null
@@ -1,276 +0,0 @@
-package example;
-
-import java.sql.*;
-import java.util.*;
-
-/*
- * Test inserting and extracting Unicode-encoded strings.
- *
- * Synopsis:
- * example.Unicode <url> <user> <password>
- * where <url> must specify an existing database to which <user> and
- * <password> give access and which has UNICODE as its encoding.
- * (To create a database with UNICODE encoding, you need to run createdb
- * with the flag "-E UNICODE".)
- *
- * This test only produces output on error.
- *
- * @author William Webber <william@live.com.au>
- */
-public class Unicode
-{
-
- /*
- * The url for the database to connect to.
- */
- private String url;
-
- /*
- * The user to connect as.
- */
- private String user;
-
- /*
- * The password to connect with.
- */
- private String password;
-
- private static void usage()
- {
- log("usage: example.Unicode <url> <user> <password>");
- }
-
- private static void log(String message)
- {
- System.err.println(message);
- }
-
- private static void log(String message, Exception e)
- {
- System.err.println(message);
- e.printStackTrace();
- }
-
-
- public Unicode(String url, String user, String password)
- {
- this.url = url;
- this.user = user;
- this.password = password;
- }
-
- /*
- * Establish and return a connection to the database.
- */
- private Connection getConnection() throws SQLException,
- ClassNotFoundException
- {
- Class.forName("org.postgresql.Driver");
- Properties info = new Properties();
- info.put("user", user);
- info.put("password", password);
- info.put("charSet", "utf-8");
- return DriverManager.getConnection(url, info);
- }
-
- /*
- * Get string representing a block of 256 consecutive unicode characters.
- * We exclude the null character, "'", and "\".
- */
- private String getSqlSafeUnicodeBlock(int blockNum)
- {
- if (blockNum < 0 || blockNum > 255)
- throw new IllegalArgumentException("blockNum must be from 0 to "
- + "255: " + blockNum);
- StringBuffer sb = new StringBuffer(256);
- int blockFirst = blockNum * 256;
- int blockLast = blockFirst + 256;
- for (int i = blockFirst; i < blockLast; i++)
- {
- char c = (char) i;
- if (c == '\0' || c == '\'' || c == '\\')
- continue;
- sb.append(c);
- }
- return sb.toString();
- }
-
- /*
- * Is the block a block of valid unicode values.
- * d800 to db7f is the "unassigned high surrogate" range.
- * db80 to dbff is the "private use" range.
- * These should not be used in actual Unicode strings;
- * at least, jdk1.2 will not convert them to utf-8.
- */
- private boolean isValidUnicodeBlock(int blockNum)
- {
- if (blockNum >= 0xd8 && blockNum <= 0xdb)
- return false;
- else
- return true;
- }
-
- /*
- * Report incorrect block retrieval.
- */
- private void reportRetrievalError(int blockNum, String block,
- String retrieved)
- {
- String message = "Block " + blockNum + " returned incorrectly: ";
- int i = 0;
- for (i = 0; i < block.length(); i++)
- {
- if (i >= retrieved.length())
- {
- message += "too short";
- break;
- }
- else if (retrieved.charAt(i) != block.charAt(i))
- {
- message +=
- "first changed character at position " + i + ", sent as 0x"
- + Integer.toHexString((int) block.charAt(i))
- + ", retrieved as 0x"
- + Integer.toHexString ((int) retrieved.charAt(i));
- break;
- }
- }
- if (i >= block.length())
- message += "too long";
- log(message);
- }
-
- /*
- * Do the testing.
- */
- public void runTest()
- {
- Connection connection = null;
- Statement statement = null;
- int blockNum = 0;
- final int CREATE = 0;
- final int INSERT = 1;
- final int SELECT = 2;
- final int LIKE = 3;
- int mode = CREATE;
- try
- {
- connection = getConnection();
- statement = connection.createStatement();
- statement.executeUpdate("CREATE TABLE test_unicode "
- + "( blockNum INT PRIMARY KEY, "
- + "block TEXT );");
- mode = INSERT;
- for (blockNum = 0; blockNum < 256; blockNum++)
- {
- if (isValidUnicodeBlock(blockNum))
- {
- String block = getSqlSafeUnicodeBlock(blockNum);
- statement.executeUpdate
- ("INSERT INTO test_unicode VALUES ( " + blockNum
- + ", '" + block + "');");
- }
- }
- mode = SELECT;
- for (blockNum = 0; blockNum < 256; blockNum++)
- {
- if (isValidUnicodeBlock(blockNum))
- {
- String block = getSqlSafeUnicodeBlock(blockNum);
- ResultSet rs = statement.executeQuery
- ("SELECT block FROM test_unicode WHERE blockNum = "
- + blockNum + ";");
- if (!rs.next())
- log("Could not retrieve block " + blockNum);
- else
- {
- String retrieved = rs.getString(1);
- if (!retrieved.equals(block))
- {
- reportRetrievalError(blockNum, block, retrieved);
- }
- }
- }
- }
- mode = LIKE;
- for (blockNum = 0; blockNum < 256; blockNum++)
- {
- if (isValidUnicodeBlock(blockNum))
- {
- String block = getSqlSafeUnicodeBlock(blockNum);
- String likeString = "%" +
- block.substring(2, block.length() - 3) + "%" ;
- ResultSet rs = statement.executeQuery
- ("SELECT blockNum FROM test_unicode WHERE block LIKE '"
- + likeString + "';");
- if (!rs.next())
- log("Could get block " + blockNum + " using LIKE");
- }
- }
- }
- catch (SQLException sqle)
- {
- switch (mode)
- {
- case CREATE:
- log("Exception creating database", sqle);
- break;
- case INSERT:
- log("Exception inserting block " + blockNum, sqle);
- break;
- case SELECT:
- log("Exception selecting block " + blockNum, sqle);
- break;
- case LIKE:
- log("Exception doing LIKE on block " + blockNum, sqle);
- break;
- default:
- log("Exception", sqle);
- break;
- }
- }
- catch (ClassNotFoundException cnfe)
- {
- log("Unable to load driver", cnfe);
- return ;
- }
- try
- {
- if (statement != null)
- statement.close();
- if (connection != null)
- connection.close();
- }
- catch (SQLException sqle)
- {
- log("Exception closing connections", sqle);
- }
- if (mode > CREATE)
- {
- // If the backend gets what it regards as garbage on a connection,
- // that connection may become unusable. To be safe, we create
- // a fresh connection to delete the table.
- try
- {
- connection = getConnection();
- statement = connection.createStatement();
- statement.executeUpdate("DROP TABLE test_unicode;");
- }
- catch (Exception sqle)
- {
- log("*** ERROR: unable to delete test table "
- + "test_unicode; must be deleted manually", sqle);
- }
- }
- }
-
- public static void main(String [] args)
- {
- if (args.length != 3)
- {
- usage();
- System.exit(1);
- }
- new Unicode(args[0], args[1], args[2]).runTest();
- }
-}
diff --git a/src/interfaces/jdbc/example/basic.java b/src/interfaces/jdbc/example/basic.java
deleted file mode 100644
index d1a7e602941..00000000000
--- a/src/interfaces/jdbc/example/basic.java
+++ /dev/null
@@ -1,219 +0,0 @@
-package example;
-
-import java.io.*;
-import java.sql.*;
-
-/*
- *
- * $PostgreSQL: pgsql/src/interfaces/jdbc/example/basic.java,v 1.15 2003/11/29 22:41:19 pgsql Exp $
- *
- * This example tests the basic components of the JDBC driver, and shows
- * how even the simplest of queries can be implemented.
- *
- * To use this example, you need a database to be in existence. This example
- * will create a table called basic.
- *
- * Note: This will only work with post 7.0 drivers.
- *
- */
-
-public class basic
-{
- Connection db; // The connection to the database
- Statement st; // Our statement to run queries with
-
- public basic(String args[]) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
- {
- String url = args[0];
- String usr = args[1];
- String pwd = args[2];
-
- // Load the driver
- Class.forName("org.postgresql.Driver");
-
- // Connect to database
- System.out.println("Connecting to Database URL = " + url);
- db = DriverManager.getConnection(url, usr, pwd);
-
- System.out.println("Connected...Now creating a statement");
- st = db.createStatement();
-
- // Clean up the database (in case we failed earlier) then initialise
- cleanup();
-
- // Now run tests using JDBC methods
- doexample();
-
- // Clean up the database
- cleanup();
-
- // Finally close the database
- System.out.println("Now closing the connection");
- st.close();
- db.close();
-
- //throw postgresql.Driver.notImplemented();
- }
-
- /*
- * This drops the table (if it existed). No errors are reported.
- */
- public void cleanup()
- {
- try
- {
- st.executeUpdate("drop table basic");
- }
- catch (Exception ex)
- {
- // We ignore any errors here
- }
- }
-
- /*
- * This performs the example
- */
- public void doexample() throws SQLException
- {
- System.out.println("\nRunning tests:");
-
- // First we need a table to store data in
- st.executeUpdate("create table basic (a int2, b int2)");
-
- // Now insert some data, using the Statement
- st.executeUpdate("insert into basic values (1,1)");
- st.executeUpdate("insert into basic values (2,1)");
- st.executeUpdate("insert into basic values (3,1)");
-
- // This shows how to get the oid of a just inserted row
- st.executeUpdate("insert into basic values (4,1)");
- long insertedOID = ((org.postgresql.PGStatement)st).getLastOID();
- System.out.println("Inserted row with oid " + insertedOID);
-
- // Now change the value of b from 1 to 8
- st.executeUpdate("update basic set b=8");
- System.out.println("Updated " + st.getUpdateCount() + " rows");
-
- // Now delete 2 rows
- st.executeUpdate("delete from basic where a<3");
- System.out.println("deleted " + st.getUpdateCount() + " rows");
-
- // For large inserts, a PreparedStatement is more efficient, because it
- // supports the idea of precompiling the SQL statement, and to store
- // directly, a Java object into any column. PostgreSQL doesnt support
- // precompiling, but does support setting a column to the value of a
- // Java object (like Date, String, etc).
- //
- // Also, this is the only way of writing dates in a datestyle independent
- // manner. (DateStyles are PostgreSQL's way of handling different methods
- // of representing dates in the Date data type.)
- PreparedStatement ps = db.prepareStatement("insert into basic values (?,?)");
- for (int i = 2;i < 5;i++)
- {
- ps.setInt(1, 4); // "column a" = 5
- ps.setInt(2, i); // "column b" = i
- ps.executeUpdate(); // executeUpdate because insert returns no data
- }
- ps.close(); // Always close when we are done with it
-
- // Finally perform a query on the table
- System.out.println("performing a query");
- ResultSet rs = st.executeQuery("select a, b from basic");
- if (rs != null)
- {
- // Now we run through the result set, printing out the result.
- // Note, we must call .next() before attempting to read any results
- while (rs.next())
- {
- int a = rs.getInt("a"); // This shows how to get the value by name
- int b = rs.getInt(2); // This shows how to get the value by column
- System.out.println(" a=" + a + " b=" + b);
- }
- rs.close(); // again, you must close the result when done
- }
-
- // Now run the query again, showing a more efficient way of getting the
- // result if you don't know what column number a value is in
-
-
-
- System.out.println("performing another query");
- rs = st.executeQuery("select * from basic where b>1");
- if (rs != null)
- {
- // First find out the column numbers.
- //
- // It's best to do this here, as calling the methods with the column
- // numbers actually performs this call each time they are called. This
- // really speeds things up on large queries.
- //
- int col_a = rs.findColumn("a");
- int col_b = rs.findColumn("b");
-
- // Now we run through the result set, printing out the result.
- // Again, we must call .next() before attempting to read any results
- while (rs.next())
- {
- int a = rs.getInt(col_a); // This shows how to get the value by name
- int b = rs.getInt(col_b); // This shows how to get the value by column
- System.out.println(" a=" + a + " b=" + b);
- }
- rs.close(); // again, you must close the result when done
- }
-
- // Now test maxrows by setting it to 3 rows
-
-
-
- st.setMaxRows(3);
- System.out.println("performing a query limited to " + st.getMaxRows());
- rs = st.executeQuery("select a, b from basic");
- while (rs.next())
- {
- int a = rs.getInt("a"); // This shows how to get the value by name
- int b = rs.getInt(2); // This shows how to get the value by column
- System.out.println(" a=" + a + " b=" + b);
- }
- rs.close(); // again, you must close the result when done
-
- // The last thing to do is to drop the table. This is done in the
- // cleanup() method.
- }
-
- /*
- * Display some instructions on how to run the example
- */
- public static void instructions()
- {
- System.out.println("\nThis example tests the basic components of the JDBC driver, demonstrating\nhow to build simple queries in java.\n");
- System.out.println("Useage:\n java example.basic jdbc:postgresql:database user password [debug]\n\nThe debug field can be anything. It's presence will enable DriverManager's\ndebug trace. Unless you want to see screens of items, don't put anything in\nhere.");
- System.exit(1);
- }
-
- /*
- * This little lot starts the test
- */
- public static void main(String args[])
- {
- System.out.println("PostgreSQL basic test v6.3 rev 1\n");
-
- if (args.length < 3)
- instructions();
-
- // This line outputs debug information to stderr. To enable this, simply
- // add an extra parameter to the command line
- if (args.length > 3)
- DriverManager.setLogStream(System.err);
-
- // Now run the tests
- try
- {
- basic test = new basic(args);
- }
- catch (Exception ex)
- {
- System.err.println("Exception caught.\n" + ex);
- ex.printStackTrace();
- }
- }
-}
diff --git a/src/interfaces/jdbc/example/blobtest.java b/src/interfaces/jdbc/example/blobtest.java
deleted file mode 100644
index d517d267b75..00000000000
--- a/src/interfaces/jdbc/example/blobtest.java
+++ /dev/null
@@ -1,255 +0,0 @@
-package example;
-
-import java.io.*;
-import java.sql.*;
-import org.postgresql.largeobject.*;
-
-/*
- * This test attempts to create a blob in the database, then to read
- * it back.
- *
- * Important note: You will notice we import the org.postgresql.largeobject
- * package, but don't import the org.postgresql package. The reason for this is
- * that importing postgresql can confuse javac (we have conflicting class names
- * in org.postgresql.* and java.sql.*). This doesn't cause any problems, as
- * long as no code imports org.postgresql.
- *
- * Under normal circumstances, code using any jdbc driver only needs to import
- * java.sql, so this isn't a problem.
- *
- * It's only if you use the non jdbc facilities, do you have to take this into
- * account.
- *
- */
-
-public class blobtest
-{
- Connection db;
- Statement s;
- LargeObjectManager lobj;
-
- public blobtest(String args[]) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
- {
- String url = args[0];
- String usr = args[1];
- String pwd = args[2];
-
- // Load the driver
- Class.forName("org.postgresql.Driver");
-
- // Connect to database
- System.out.println("Connecting to Database URL = " + url);
- db = DriverManager.getConnection(url, usr, pwd);
-
- // This is required for all LargeObject calls
- System.out.println("Connected... First turn off autoCommit()");
- db.setAutoCommit(false);
-
- System.out.println("Now creating a statement");
- s = db.createStatement();
-
- // Now run tests using postgresql's own Large object api
- // NOTE: The methods shown in this example are _NOT_ JDBC, but are
- // an implementation of the calls found in libpq. Unless you need to
- // use this functionality, look at the jdbc tests on how to access blobs.
- ownapi();
-
- // Now run tests using JDBC methods
- //jdbcapi(db,s);
-
- // Finally close the database
- System.out.println("Now closing the connection");
- s.close();
- db.close();
- }
-
- /*
- * Now this is an extension to JDBC, unique to postgresql. Here we fetch
- * an PGlobj object, which provides us with access to postgresql's
- * large object api.
- */
- public void ownapi() throws FileNotFoundException, IOException, SQLException
- {
- System.out.println("\n----------------------------------------------------------------------\nTesting postgresql large object api\n----------------------------------------------------------------------\n");
-
- // Internally, the driver provides JDBC compliant methods to access large
- // objects, however the unique methods available to postgresql makes
- // things a little easier.
- System.out.println("Gaining access to large object api");
- lobj = ((org.postgresql.PGConnection)db).getLargeObjectAPI();
-
- int oid = ownapi_test1();
- ownapi_test2(oid);
-
- // Now call the jdbc2api test
- jdbc2api(oid);
-
- // finally delete the large object
- ownapi_test3(oid);
- System.out.println("\n\nOID=" + oid);
- }
-
- private int ownapi_test1() throws FileNotFoundException, IOException, SQLException
- {
- System.out.println("Test 1 Creating a large object\n");
-
- // Ok, test 1 is to create a large object. To do this, we use the create
- // method.
- System.out.println("Creating a large object");
- int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
- DriverManager.println("got large object oid=" + oid);
-
- LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);
- DriverManager.println("got large object obj=" + obj);
-
- // Now open a test file - this class will do
- System.out.println("Opening test source object");
- FileInputStream fis = new FileInputStream("example/blobtest.java");
-
- // copy the data
- System.out.println("Copying file to large object");
- byte buf[] = new byte[2048];
- int s, tl = 0;
- while ((s = fis.read(buf, 0, 2048)) > 0)
- {
- System.out.println("Block size=" + s + " offset=" + tl);
- //System.out.write(buf);
- obj.write(buf, 0, s);
- tl += s;
- }
- DriverManager.println("Copied " + tl + " bytes");
-
- // Close the object
- System.out.println("Closing object");
- obj.close();
-
- return oid;
- }
-
- private void ownapi_test2(int oid) throws FileNotFoundException, IOException, SQLException
- {
- System.out.println("Test 2 Reading a large object and save as a file\n");
-
- // Now open the large object
- System.out.println("Opening large object " + oid);
- LargeObject obj = lobj.open(oid, LargeObjectManager.READ);
- DriverManager.println("got obj=" + obj);
-
- // Now open a test file - this class will do
- System.out.println("Opening test destination object");
- FileOutputStream fos = new FileOutputStream("blob_testoutput");
-
- // copy the data
- System.out.println("Copying large object to file");
- byte buf[] = new byte[512];
- int s = obj.size();
- int tl = 0;
- while (s > 0)
- {
- int rs = buf.length;
- if (s < rs)
- rs = s;
- obj.read(buf, 0, rs);
- fos.write(buf, 0, rs);
- tl += rs;
- s -= rs;
- }
- DriverManager.println("Copied " + tl + "/" + obj.size() + " bytes");
-
- // Close the object
- System.out.println("Closing object");
- obj.close();
- }
-
- private void ownapi_test3(int oid) throws SQLException
- {
- System.out.println("Test 3 Deleting a large object\n");
-
- // Now open the large object
- System.out.println("Deleting large object " + oid);
- lobj.unlink(oid);
- }
-
- // This tests the Blob interface of the JDBC 2.0 specification
- public void jdbc2api(int oid) throws SQLException, IOException
- {
- System.out.println("Testing JDBC2 Blob interface:");
- jdbc2api_cleanup();
-
- System.out.println("Creating Blob on large object " + oid);
- s.executeUpdate("create table basic (a oid)");
-
- System.out.println("Inserting row");
- s.executeUpdate("insert into basic values (" + oid + ")");
-
- System.out.println("Selecting row");
- ResultSet rs = s.executeQuery("select a from basic");
- if (rs != null)
- {
- while (rs.next())
- {
- System.out.println("Fetching Blob");
- Blob b = rs.getBlob("a");
- System.out.println("Blob.length() = " + b.length());
- System.out.println("Characters 400-500:");
- System.out.write(b.getBytes(400l, 100));
- System.out.println();
- }
- rs.close();
- }
-
- System.out.println("Cleaning up");
- jdbc2api_cleanup();
- }
-
- private void jdbc2api_cleanup() throws SQLException
- {
- db.setAutoCommit(true);
- try
- {
- s.executeUpdate("drop table basic");
- }
- catch (Exception ex)
- {
- // We ignore any errors here
- }
- db.setAutoCommit(false);
- }
-
- public static void instructions()
- {
- System.err.println("java example.blobtest jdbc-url user password [debug]");
- System.err.println("\nExamples:\n");
- System.err.println("java -Djdbc.driver=org.postgresql.Driver example.blobtest jdbc:postgresql:test postgres password\nThis will run the tests on the database test on the local host.\n");
- System.err.println("java -Djdbc.driver=org.postgresql.Driver example.blobtest jdbc:postgresql:test postgres password debug\nThis is the same as above, but will output debug information.\n");
-
- System.err.println("This example tests the binary large object api of the driver.\nThis allows images or java objects to be stored in the database, and retrieved\nusing both postgresql's own api, and the standard JDBC api.");
- }
-
- public static void main(String args[])
- {
- System.out.println("PostgreSQL blobtest v7.0 rev 1\n");
-
- if (args.length < 3)
- {
- instructions();
- System.exit(1);
- }
-
- // This line outputs debug information to stderr. To enable this, simply
- // add an extra parameter to the command line
- if (args.length > 3)
- DriverManager.setLogStream(System.err);
-
- // Now run the tests
- try
- {
- blobtest test = new blobtest(args);
- }
- catch (Exception ex)
- {
- System.err.println("Exception caught.\n" + ex);
- ex.printStackTrace();
- }
- }
-}
diff --git a/src/interfaces/jdbc/example/corba/StockClient.java b/src/interfaces/jdbc/example/corba/StockClient.java
deleted file mode 100644
index 217552f0810..00000000000
--- a/src/interfaces/jdbc/example/corba/StockClient.java
+++ /dev/null
@@ -1,348 +0,0 @@
-package example.corba;
-
-import java.io.*;
-import java.sql.*;
-import org.omg.CosNaming.*;
-
-/*
- * This class is the frontend to our mini CORBA application.
- *
- * It has no GUI, just a text frontend to keep it simple.
- *
- * $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/StockClient.java,v 1.7 2003/11/29 22:41:21 pgsql Exp $
- */
-public class StockClient
-{
- org.omg.CosNaming.NamingContext nameService;
-
- stock.StockDispenser dispenser;
- stock.StockItem item;
-
- BufferedReader in;
-
- public StockClient(String[] args)
- {
- try
- {
- // We need this for our IO
- in = new BufferedReader(new InputStreamReader(System.in));
-
- // Initialize the orb
- org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
-
- // Get a reference to the Naming Service
- org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService");
- if (nameServiceObj == null)
- {
- System.err.println("nameServiceObj == null");
- return ;
- }
-
- nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj);
- if (nameService == null)
- {
- System.err.println("nameService == null");
- return ;
- }
-
- // Resolve the dispenser
- NameComponent[] dispName = {
- new NameComponent("StockDispenser", "Stock")
- };
- dispenser = stock.StockDispenserHelper.narrow(nameService.resolve(dispName));
- if (dispenser == null)
- {
- System.err.println("dispenser == null");
- return ;
- }
-
- // Now run the front end.
- run();
- }
- catch (Exception e)
- {
- System.out.println(e.toString());
- e.printStackTrace();
- System.exit(1);
- }
- }
-
- public static void main(String[] args)
- {
- new StockClient(args);
- }
-
- public void run()
- {
- // First reserve a StockItem
- try
- {
- item = dispenser.reserveItem();
- }
- catch (Exception e)
- {
- System.out.println(e.toString());
- e.printStackTrace();
- System.exit(1);
- }
-
- mainMenu();
-
- // finally free the StockItem
- try
- {
- dispenser.releaseItem(item);
- }
- catch (Exception e)
- {
- System.out.println(e.toString());
- e.printStackTrace();
- System.exit(1);
- }
- }
-
- private void mainMenu()
- {
- boolean run = true;
- while (run)
- {
- System.out.println("\nCORBA Stock System\n");
- System.out.println(" 1 Display stock item");
- System.out.println(" 2 Remove item from stock");
- System.out.println(" 3 Put item into stock");
- System.out.println(" 4 Order item");
- System.out.println(" 5 Display all items");
- System.out.println(" 0 Exit");
- int i = getMenu("Main", 5);
- switch (i)
- {
- case 0:
- run = false;
- break;
-
- case 1:
- displayItem();
- break;
-
- case 2:
- bookOut();
- break;
-
- case 3:
- bookIn();
- break;
-
- case 4:
- order(0);
- break;
-
- case 5:
- displayAll();
- break;
- }
- }
- }
-
- private void displayItem()
- {
- try
- {
- int id = getMenu("\nStockID to display", item.getLastID());
- if (id > 0)
- {
- item.fetchItem(id);
- System.out.println("========================================");
-
- String status = "";
- if (!item.isItemValid())
- status = " ** Superceded **";
-
- int av = item.getAvailable();
-
- System.out.println(" Stock ID: " + id + status +
- "\nItems Available: " + av +
- "\nItems on order: " + item.getOrdered() +
- "\n Description: " + item.getDescription());
- System.out.println("========================================");
-
- if (av > 0)
- if (yn("Take this item out of stock?"))
- {
- int rem = 1;
- if (av > 1)
- rem = getMenu("How many?", av);
- if (rem > 0)
- item.removeStock(rem);
- }
-
- }
- }
- catch (Exception e)
- {
- System.out.println(e.toString());
- e.printStackTrace();
- }
- }
-
- private void bookOut()
- {
- try
- {
- int id = getMenu("\nStockID to take out", item.getLastID());
- if (id > 0)
- {
- item.fetchItem(id);
- int av = item.getAvailable();
- if (av > 0)
- if (yn("Take this item out of stock?"))
- {
- int rem = 1;
- if (av > 1)
- rem = getMenu("How many?", av);
- if (rem > 0)
- item.removeStock(rem);
- }
- else
- {
- System.out.println("This item is not in stock.");
- int order = item.getOrdered();
- if (order > 0)
- System.out.println("There are " + item.getOrdered() + " items on order.");
- else
- {
- if (item.isItemValid())
- {
- System.out.println("You will need to order some more " + item.getDescription());
- order(id);
- }
- else
- System.out.println("This item is now obsolete");
- }
- }
- }
- else
- System.out.println(item.getDescription() + "\nThis item is out of stock");
- }
- catch (Exception e)
- {
- System.out.println(e.toString());
- e.printStackTrace();
- }
- }
-
- // book an item into stock
- private void bookIn()
- {
- try
- {
- int id = getMenu("\nStockID to book in", item.getLastID());
- item.fetchItem(id);
- System.out.println(item.getDescription());
-
- if (item.getOrdered() > 0)
- {
- int am = getMenu("How many do you want to book in", item.getOrdered());
- if (am > 0)
- item.addNewStock(am);
- }
- else
- System.out.println("You don't have any of this item on ordered");
-
- }
- catch (Exception e)
- {
- System.out.println(e.toString());
- e.printStackTrace();
- }
- }
-
- // Order an item
- private void order(int id)
- {
- try
- {
- if (id == 0)
- id = getMenu("\nStockID to order", item.getLastID());
- item.fetchItem(id);
- System.out.println(item.getDescription());
- int am = getMenu("How many do you want to order", 999);
- if (am > 0)
- item.orderStock(am);
- }
- catch (Exception e)
- {
- System.out.println(e.toString());
- e.printStackTrace();
- }
- }
-
- private void displayAll()
- {
- try
- {
- boolean cont = true;
- int nr = item.getLastID();
- String header = "\nId\tAvail\tOrdered\tDescription";
- System.out.println(header);
- for (int i = 1;i <= nr && cont;i++)
- {
- item.fetchItem(i);
- System.out.println("" + i + "\t" + item.getAvailable() + "\t" + item.getOrdered() + "\t" + item.getDescription());
- if ((i % 20) == 0)
- {
- if ((cont = yn("Continue?")))
- System.out.println(header);
- }
- }
- }
- catch (Exception e)
- {
- System.out.println(e.toString());
- e.printStackTrace();
- }
- }
-
- private int getMenu(String title, int max)
- {
- int v = -1;
- while (v < 0 || v > max)
- {
- System.out.print(title);
- System.out.print(" [0-" + max + "]: ");
- System.out.flush();
- try
- {
- v = Integer.parseInt(in.readLine());
- }
- catch (Exception nfe)
- {
- v = -1;
- }
- }
- return v;
- }
-
- private boolean yn(String title)
- {
- try
- {
- while (true)
- {
- System.out.print(title);
- System.out.flush();
- String s = in.readLine();
- if (s.startsWith("y") || s.startsWith("Y"))
- return true;
- if (s.startsWith("n") || s.startsWith("N"))
- return false;
- }
- }
- catch (Exception nfe)
- {
- System.out.println(nfe.toString());
- nfe.printStackTrace();
- System.exit(1);
- }
- return false;
- }
-}
diff --git a/src/interfaces/jdbc/example/corba/StockDB.java b/src/interfaces/jdbc/example/corba/StockDB.java
deleted file mode 100644
index 90fb8d28048..00000000000
--- a/src/interfaces/jdbc/example/corba/StockDB.java
+++ /dev/null
@@ -1,134 +0,0 @@
-package example.corba;
-
-import java.sql.*;
-
-/*
- * This class handles the JDBC side of things. It opens a connection to
- * the database, and performes queries on that database.
- *
- * In essence, you could use this class on it's own. The rest of the classes
- * in this example handle either the CORBA mechanism, or the frontend.
- *
- * Note: Before you ask, why perform a query on each call, you have to remember
- * that an object could be changed by another client, and we need to ensure that
- * the returned data is live and accurate.
- *
- * $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/StockDB.java,v 1.5 2003/11/29 22:41:21 pgsql Exp $
- */
-public class StockDB
-{
- Connection con;
- Statement st;
-
- // the current stock number
- int id = -1;
-
- public void connect(String url, String usr, String pwd) throws Exception
- {
- Class.forName("org.postgresql.Driver");
- System.out.println("Connecting to " + url);
- con = DriverManager.getConnection(url, usr, pwd);
- st = con.createStatement();
- }
-
- public void closeConnection() throws Exception
- {
- con.close();
- }
-
- public void fetchItem(int id) throws Exception
- {
- this.id = id;
- }
-
- public int newItem() throws Exception
- {
- // tba
- return -1;
- }
-
- public String getDescription() throws SQLException
- {
- ResultSet rs = st.executeQuery("select description from stock where id=" + id);
- if (rs != null)
- {
- rs.next();
- String s = rs.getString(1);
- rs.close();
- return s;
- }
- throw new SQLException("No ResultSet");
- }
-
- public int getAvailable() throws SQLException
- {
- ResultSet rs = st.executeQuery("select avail from stock where id=" + id);
- if (rs != null)
- {
- rs.next();
- int v = rs.getInt(1);
- rs.close();
- return v;
- }
- throw new SQLException("No ResultSet");
- }
-
- public int getOrdered() throws SQLException
- {
- ResultSet rs = st.executeQuery("select ordered from stock where id=" + id);
- if (rs != null)
- {
- rs.next();
- int v = rs.getInt(1);
- rs.close();
- return v;
- }
- throw new SQLException("No ResultSet");
- }
-
- public boolean isItemValid() throws SQLException
- {
- ResultSet rs = st.executeQuery("select valid from stock where id=" + id);
- if (rs != null)
- {
- rs.next();
- boolean b = rs.getBoolean(1);
- rs.close();
- return b;
- }
- throw new SQLException("No ResultSet");
- }
-
- public void addNewStock(int amount) throws SQLException
- {
- st.executeUpdate("update stock set avail=avail+" + amount +
- ", ordered=ordered-" + amount +
- " where id=" + id + " and ordered>=" + amount);
- }
-
- public void removeStock(int amount) throws SQLException
- {
- st.executeUpdate("update stock set avail=avail-" + amount +
- " where id=" + id);
- }
-
- public void orderStock(int amount) throws SQLException
- {
- st.executeUpdate("update stock set ordered=ordered+" + amount +
- " where id=" + id);
- }
-
- public int getLastID() throws SQLException
- {
- ResultSet rs = st.executeQuery("select max(id) from stock");
- if (rs != null)
- {
- rs.next();
- int v = rs.getInt(1);
- rs.close();
- return v;
- }
- throw new SQLException("No ResultSet");
- }
-
-}
diff --git a/src/interfaces/jdbc/example/corba/StockDispenserImpl.java b/src/interfaces/jdbc/example/corba/StockDispenserImpl.java
deleted file mode 100644
index 132b58f64c0..00000000000
--- a/src/interfaces/jdbc/example/corba/StockDispenserImpl.java
+++ /dev/null
@@ -1,92 +0,0 @@
-package example.corba;
-
-import org.omg.CosNaming.*;
-
-/*
- * This class implements the server side of the example.
- *
- * $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/StockDispenserImpl.java,v 1.6 2003/11/29 22:41:21 pgsql Exp $
- */
-public class StockDispenserImpl extends stock._StockDispenserImplBase
-{
- private int maxObjects = 10;
- private int numObjects = 0;
- private StockItemStatus[] stock = new StockItemStatus[maxObjects];
-
- public StockDispenserImpl(String[] args, String name, int num)
- {
- super();
-
- try
- {
- // get reference to orb
- org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
-
- // prestart num objects
- if (num >= maxObjects)
- num = maxObjects;
- numObjects = num;
- for (int i = 0;i < numObjects;i++)
- {
- stock[i] = new StockItemStatus();
- stock[i].ref = new StockItemImpl(args, "StockItem" + (i + 1));
- orb.connect(stock[i].ref);
- }
- }
- catch (org.omg.CORBA.SystemException e)
- {
- e.printStackTrace();
- }
- }
-
- /*
- * This method, defined in stock.idl, reserves a slot in the dispenser
- */
- public stock.StockItem reserveItem() throws stock.StockException
- {
- for (int i = 0;i < numObjects;i++)
- {
- if (!stock[i].inUse)
- {
- stock[i].inUse = true;
- System.out.println("Reserving slot " + i);
- return stock[i].ref;
- }
- }
- return null;
- }
-
- /*
- * This releases a slot from the dispenser
- */
- public void releaseItem(stock.StockItem item) throws stock.StockException
- {
- for (int i = 0;i < numObjects;i++)
- {
- if (stock[i].ref.getInstanceName().equals(item.getInstanceName()))
- {
- stock[i].inUse = false;
- System.out.println("Releasing slot " + i);
- return ;
- }
- }
- System.out.println("Reserved object not a member of this dispenser");
- return ;
- }
-
- /*
- * This class defines a slot in the dispenser
- */
- class StockItemStatus
- {
- StockItemImpl ref;
- boolean inUse;
-
- StockItemStatus()
- {
- ref = null;
- inUse = false;
- }
- }
-
-}
diff --git a/src/interfaces/jdbc/example/corba/StockItemImpl.java b/src/interfaces/jdbc/example/corba/StockItemImpl.java
deleted file mode 100644
index 4b52dc18056..00000000000
--- a/src/interfaces/jdbc/example/corba/StockItemImpl.java
+++ /dev/null
@@ -1,208 +0,0 @@
-package example.corba;
-
-import org.omg.CosNaming.*;
-
-/*
- * This class implements the server side of the example.
- *
- * $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/StockItemImpl.java,v 1.4 2003/11/29 22:41:21 pgsql Exp $
- */
-public class StockItemImpl extends stock._StockItemImplBase
-{
- private StockDB db;
- private String instanceName;
-
- public StockItemImpl(String[] args, String iname)
- {
- super();
- try
- {
- db = new StockDB();
- db.connect(args[1], args[2], args[3]);
- System.out.println("StockDB object " + iname + " created");
- instanceName = iname;
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
-
- /*
- * This is defined in stock.idl
- *
- * It sets the item to view
- */
- public void fetchItem(int id) throws stock.StockException
- {
- try
- {
- db.fetchItem(id);
- }
- catch (Exception e)
- {
- throw new stock.StockException(e.toString());
- }
- }
-
-
- /*
- * This is defined in stock.idl
- *
- * It sets the item to view
- */
- public int newItem() throws stock.StockException
- {
- try
- {
- return db.newItem();
- }
- catch (Exception e)
- {
- throw new stock.StockException(e.toString());
- }
- }
-
- /*
- * This is defined in stock.idl
- *
- * It returns the description of a Stock item
- */
- public String getDescription() throws stock.StockException
- {
- try
- {
- return db.getDescription();
- }
- catch (Exception e)
- {
- throw new stock.StockException(e.toString());
- }
- }
-
- /*
- * This is defined in stock.idl
- *
- * It returns the description of a Stock item
- */
- public int getAvailable() throws stock.StockException
- {
- try
- {
- return db.getAvailable();
- }
- catch (Exception e)
- {
- throw new stock.StockException(e.toString());
- }
- }
-
- /*
- * This is defined in stock.idl
- *
- * It returns the description of a Stock item
- */
- public int getOrdered() throws stock.StockException
- {
- try
- {
- return db.getOrdered();
- }
- catch (Exception e)
- {
- throw new stock.StockException(e.toString());
- }
- }
-
- /*
- * This is defined in stock.idl
- *
- * It returns the description of a Stock item
- */
- public boolean isItemValid() throws stock.StockException
- {
- try
- {
- return db.isItemValid();
- }
- catch (Exception e)
- {
- throw new stock.StockException(e.toString());
- }
- }
-
- /*
- * This is defined in stock.idl
- *
- * It returns the description of a Stock item
- */
- public void addNewStock(int id) throws stock.StockException
- {
- try
- {
- db.addNewStock(id);
- }
- catch (Exception e)
- {
- throw new stock.StockException(e.toString());
- }
- }
-
- /*
- * This is defined in stock.idl
- *
- * It returns the description of a Stock item
- */
- public void removeStock(int id) throws stock.StockException
- {
- try
- {
- db.removeStock(id);
- }
- catch (Exception e)
- {
- throw new stock.StockException(e.toString());
- }
- }
-
- /*
- * This is defined in stock.idl
- *
- * It returns the description of a Stock item
- */
- public void orderStock(int id) throws stock.StockException
- {
- try
- {
- db.orderStock(id);
- }
- catch (Exception e)
- {
- throw new stock.StockException(e.toString());
- }
- }
-
- /*
- * This returns the highest id used, hence the number of items available
- */
- public int getLastID() throws stock.StockException
- {
- try
- {
- return db.getLastID();
- }
- catch (Exception e)
- {
- throw new stock.StockException(e.toString());
- }
- }
-
- /*
- * This is used by our Dispenser
- */
- public String getInstanceName()
- {
- return instanceName;
- }
-}
-
diff --git a/src/interfaces/jdbc/example/corba/StockServer.java b/src/interfaces/jdbc/example/corba/StockServer.java
deleted file mode 100644
index 18c8b893faa..00000000000
--- a/src/interfaces/jdbc/example/corba/StockServer.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package example.corba;
-
-import org.omg.CosNaming.*;
-
-/*
- * This class implements the server side of the example.
- *
- * $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/StockServer.java,v 1.6 2003/11/29 22:41:21 pgsql Exp $
- */
-public class StockServer
-{
- public static void main(String[] args)
- {
- int numInstances = 3;
-
- try
- {
- // Initialise the ORB
- org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
-
- // Create the StockDispenser object
- StockDispenserImpl dispenser = new StockDispenserImpl(args, "Stock Dispenser", numInstances);
-
- // Export the new object
- orb.connect(dispenser);
-
- // Get the naming service
- org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService");
- if (nameServiceObj == null)
- {
- System.err.println("nameServiceObj = null");
- return ;
- }
-
- org.omg.CosNaming.NamingContext nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj);
- if (nameService == null)
- {
- System.err.println("nameService = null");
- return ;
- }
-
- // bind the dispenser into the naming service
- NameComponent[] dispenserName = {
- new NameComponent("StockDispenser", "Stock")
- };
- nameService.rebind(dispenserName, dispenser);
-
- // Now wait forever for the current thread to die
- Thread.currentThread().join();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
-}
-
-
diff --git a/src/interfaces/jdbc/example/corba/readme b/src/interfaces/jdbc/example/corba/readme
deleted file mode 100644
index d44c17613f3..00000000000
--- a/src/interfaces/jdbc/example/corba/readme
+++ /dev/null
@@ -1,34 +0,0 @@
-
-The CORBA example is the most complicated of the examples. It
-aims to show how to use JDBC & Java2's ORB to access PostgreSQL.
-
-To compile:
-
-Type "make corba" to build the example. This will create a new directory
-stock which contains the stubs needed by the orb, and all required classes
-under the example/corba directory.
-
-To run:
-
-NOTE: To run, you will need 3 shells on Win32 (under unix you can get away
-with two shells):
-
-1: Start the naming service
-
-Unix: tnameserv -ORBInitialPort 1050 &
-Win32: tnameserv -ORBInitialPort 1050
-
-2: Start the StockServer
-
- java example.corba.StockServer 3 jdbc:postgresql:dbase user passwd -ORBInitialPort 1050
-
-Where:
- 3 Number of concurrent sessions to allow
- dbase The database (including a hostname if required)
- user The PostgreSQL user name
- passwd The password
-
-3: Using a fresh shell, run the client:
-
- java example.corba.StockClient -ORBInitialPort 1050
-
diff --git a/src/interfaces/jdbc/example/corba/stock.idl b/src/interfaces/jdbc/example/corba/stock.idl
deleted file mode 100755
index 4be5a79d7d2..00000000000
--- a/src/interfaces/jdbc/example/corba/stock.idl
+++ /dev/null
@@ -1,40 +0,0 @@
-// $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/stock.idl,v 1.2 2003/11/29 22:41:21 pgsql Exp $
-//
-// This is our CORBA bindings for a very simple stock control
-// system.
-//
-// $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/stock.idl,v 1.2 2003/11/29 22:41:21 pgsql Exp $
-//
-
-// For some reason, idltojava on my setup doesn't like this to be
-// in caps. It could be a problem with Win95 & Samba, but for now,
-// this is in lowercase
-module stock
-{
- exception StockException
- {
- string reason;
- };
-
- interface StockItem
- {
- void fetchItem(in long id) raises (StockException);
- long newItem() raises (StockException);
- string getDescription() raises (StockException);
- long getAvailable() raises (StockException);
- long getOrdered() raises (StockException);
- boolean isItemValid() raises (StockException);
- void addNewStock(in long amount) raises (StockException);
- void removeStock(in long amount) raises (StockException);
- void orderStock(in long amount) raises (StockException);
- long getLastID() raises (StockException);
- string getInstanceName();
- };
-
- interface StockDispenser
- {
- StockItem reserveItem() raises (StockException);
- void releaseItem(in StockItem item) raises (StockException);
- };
-
-};
diff --git a/src/interfaces/jdbc/example/corba/stock.sql b/src/interfaces/jdbc/example/corba/stock.sql
deleted file mode 100644
index 6082ad6fe1e..00000000000
--- a/src/interfaces/jdbc/example/corba/stock.sql
+++ /dev/null
@@ -1,27 +0,0 @@
---
--- This creates the database for the stock example
--- $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/stock.sql,v 1.2 2003/11/29 22:41:21 pgsql Exp $
---
-drop table stock;
-
-create table stock (
- id int4,
- avail int4,
- ordered int4,
- valid bool,
- description text
-);
-
-create index stock_id on stock(id);
-
-copy stock from stdin;
-1 19 0 t Dell Latitude XPi P133 Laptop
-2 3 2 t Iomega Zip Plus drive
-3 2 0 f Iomega Ext/Par drive
-4 0 4 t Iomega Ext USB drive
-5 200 0 t Blank Unbranded CDR media
-6 20 30 t Iomega Zip media 100Mb
-\.
-
-grant all on stock to public;
-grant all on stock_id to public;
diff --git a/src/interfaces/jdbc/example/datestyle.java b/src/interfaces/jdbc/example/datestyle.java
deleted file mode 100644
index 26a14a760bb..00000000000
--- a/src/interfaces/jdbc/example/datestyle.java
+++ /dev/null
@@ -1,186 +0,0 @@
-package example;
-
-import java.io.*;
-import java.sql.*;
-
-/*
- * This example tests the various date styles that are available to postgresql.
- *
- * To use this example, you need a database to be in existence. This example
- * will create a table called datestyle.
- */
-
-public class datestyle
-{
- Connection db; // The connection to the database
- Statement st; // Our statement to run queries with
-
- // This is our standard to compare results with.
- java.sql.Date standard;
-
- // This is a list of the available date styles including variants.
- // These have to match what the "set datestyle" statement accepts.
- String styles[] = {
- "postgres,european",
- "postgres,us",
- "iso", // iso has no variants - us/european has no affect
- "sql,european",
- "sql,us",
- "german" // german has no variants - us/european has no affect
- };
-
- public datestyle(String args[]) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
- {
- String url = args[0];
- String usr = args[1];
- String pwd = args[2];
-
- // Load the driver
- Class.forName("org.postgresql.Driver");
-
- // Connect to database
- System.out.println("Connecting to Database URL = " + url);
- db = DriverManager.getConnection(url, usr, pwd);
-
- System.out.println("Connected...Now creating a statement");
- st = db.createStatement();
-
- // Clean up the database (in case we failed earlier) then initialise
- cleanup();
- init();
-
- // Now run tests using JDBC methods
- doexample();
-
- // Clean up the database
- cleanup();
-
- // Finally close the database
- System.out.println("Now closing the connection");
- st.close();
- db.close();
-
- }
-
- /*
- * This drops the table (if it existed). No errors are reported.
- */
- public void cleanup()
- {
- try
- {
- st.executeUpdate("drop table datestyle");
- }
- catch (Exception ex)
- {
- // We ignore any errors here
- }
- }
-
- /*
- * This initialises the database for this example
- */
- public void init() throws SQLException
- {
- // Create a table holding a single date
- st.executeUpdate("create table datestyle (dt date)");
-
- // Now create our standard date for the test.
- //
- // NB: each component of the date should be different, otherwise the tests
- // will not be valid.
- //
- // NB: January = 0 here
- //
- standard = new java.sql.Date(98, 0, 8);
-
- // Now store the result.
- //
- // This is an example of how to set a date in a date style independent way.
- // The only way of doing this is by using a PreparedStatement.
- //
- PreparedStatement ps = db.prepareStatement("insert into datestyle values (?)");
- ps.setDate(1, standard);
- ps.executeUpdate();
- ps.close();
- }
-
- /*
- * This performs the example
- */
- public void doexample() throws SQLException
- {
- System.out.println("\nRunning tests:");
-
- for (int i = 0;i < styles.length;i++)
- {
- System.out.print("Test " + i + " - " + styles[i]);
- System.out.flush();
-
- // set the style
- st.executeUpdate("set datestyle='" + styles[i] + "'");
-
- // Now because the driver needs to know what the current style is,
- // we have to run the following:
- st.executeUpdate("show datestyle");
- // This is a limitation, but there is no real way around this.
-
- // Now we query the table.
- ResultSet rs = st.executeQuery("select dt from datestyle");
-
- // Throw an exception if there is no result (if the table is empty
- // there should still be a result).
- if (rs == null)
- throw new SQLException("The test query returned no data");
-
- while (rs.next())
- {
- // The JDBC spec states we should only read each column once.
- // In the current implementation of the driver, this is not necessary.
- // Here we use this fact to see what the query really returned.
- if (standard.equals(rs.getDate(1)))
- System.out.println(" passed, returned " + rs.getString(1));
- else
- System.out.println(" failed, returned " + rs.getString(1));
- }
- rs.close();
- }
- }
-
- /*
- * Display some instructions on how to run the example
- */
- public static void instructions()
- {
- System.out.println("\nThis example tests the drivers ability to handle dates correctly if the\nbackend is running any of the various date styles that it supports.\nIdealy this should work fine. If it doesn't, then there is something wrong\npossibly in postgresql.Connection or in the backend itself. If this does occur\nthen please email a bug report.\n");
- System.out.println("Useage:\n java example.datestyle jdbc:postgresql:database user password [debug]\n\nThe debug field can be anything. It's presence will enable DriverManager's\ndebug trace. Unless you want to see screens of items, don't put anything in\nhere.");
- System.exit(1);
- }
-
- /*
- * This little lot starts the test
- */
- public static void main(String args[])
- {
- System.out.println("PostgreSQL datestyle test v6.3 rev 1\n");
-
- if (args.length < 3)
- instructions();
-
- // This line outputs debug information to stderr. To enable this, simply
- // add an extra parameter to the command line
- if (args.length > 3)
- DriverManager.setLogStream(System.err);
-
- // Now run the tests
- try
- {
- datestyle test = new datestyle(args);
- }
- catch (Exception ex)
- {
- System.err.println("Exception caught.\n" + ex);
- ex.printStackTrace();
- }
- }
-}
diff --git a/src/interfaces/jdbc/example/metadata.java b/src/interfaces/jdbc/example/metadata.java
deleted file mode 100644
index b796329923a..00000000000
--- a/src/interfaces/jdbc/example/metadata.java
+++ /dev/null
@@ -1,296 +0,0 @@
-package example;
-
-import java.io.*;
-import java.sql.*;
-
-/*
- * This example application is not really an example. It actually performs
- * some tests on various methods in the DatabaseMetaData and ResultSetMetaData
- * classes.
- *
- * To use it, simply have a database created. It will create some work tables
- * and run tests on them.
- */
-
-public class metadata
-{
- Connection db; // The connection to the database
- Statement st; // Our statement to run queries with
- DatabaseMetaData dbmd; // This defines the structure of the database
-
- /*
- * These are the available tests on DatabaseMetaData
- */
- public void doDatabaseMetaData() throws SQLException
- {
- if (doTest("getProcedures() - should show all available procedures"))
- displayResult(dbmd.getProcedures(null, null, null));
-
- if (doTest("getProcedures() with pattern - should show all circle procedures"))
- displayResult(dbmd.getProcedures(null, null, "circle%"));
-
- if (doTest("getProcedureColumns() on circle procedures"))
- displayResult(dbmd.getProcedureColumns(null, null, "circle%", null));
-
- if (doTest("getTables()"))
- displayResult(dbmd.getTables(null, null, null, null));
-
- if (doTest("getColumns() - should show all tables, can take a while to run"))
- displayResult(dbmd.getColumns(null, null, null, null));
-
- if (doTest("getColumns() - should show the test_b table"))
- displayResult(dbmd.getColumns(null, null, "test_b", null));
-
- if (doTest("getColumnPrivileges() - should show all tables"))
- displayResult(dbmd.getColumnPrivileges(null, null, null, null));
-
- if (doTest("getPrimaryKeys()"))
- displayResult(dbmd.getPrimaryKeys(null, null, null));
-
- if (doTest("getTypeInfo()"))
- displayResult(dbmd.getTypeInfo());
-
- }
-
- /*
- * These are the available tests on ResultSetMetaData
- */
- public void doResultSetMetaData() throws SQLException
- {
-
- String sql = "select imagename,descr,source,cost from test_a,test_b,test_c where test_a.id=test_b.imageid and test_a.id=test_c.imageid";
-
- System.out.println("Executing query for tests");
- ResultSet rs = st.executeQuery(sql);
- ResultSetMetaData rsmd = rs.getMetaData();
-
- if (doTest("isCurrency()"))
- System.out.println("isCurrency on col 1 = " + rsmd.isCurrency(1) + " should be false\nisCurrency on col 4 = " + rsmd.isCurrency(4) + " should be true");
-
- // Finally close the query. Now give the user a chance to display the
- // ResultSet.
- //
- // NB: displayResult() actually closes the ResultSet.
- if (doTest("Display query result"))
- {
- System.out.println("Query: " + sql);
- displayResult(rs);
- }
- else
- rs.close();
- }
-
- /*
- * This creates some test data
- */
- public void init() throws SQLException
- {
- System.out.println("Creating some tables");
- cleanup();
- st.executeUpdate("create table test_a (imagename name,image oid,id int4)");
- st.executeUpdate("create table test_b (descr text,imageid int4,id int4)");
- st.executeUpdate("create table test_c (source text,cost money,imageid int4)");
-
- System.out.println("Adding some data");
- st.executeUpdate("insert into test_a values ('test1',0,1)");
- st.executeUpdate("insert into test_b values ('A test description',1,2)");
- st.executeUpdate("insert into test_c values ('nowhere particular','$10.99',1)");
- }
-
- /*
- * This removes the test data
- */
- public void cleanup() throws SQLException
- {
- try
- {
- st.executeUpdate("drop table test_a");
- st.executeUpdate("drop table test_b");
- st.executeUpdate("drop table test_c");
- }
- catch (Exception ex)
- {
- // We ignore any errors here
- }
- }
-
- public metadata(String args[]) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
- {
- String url = args[0];
- String usr = args[1];
- String pwd = args[2];
-
- // Load the driver
- Class.forName("org.postgresql.Driver");
-
- // Connect to database
- System.out.println("Connecting to Database URL = " + url);
- db = DriverManager.getConnection(url, usr, pwd);
-
- dbmd = db.getMetaData();
- st = db.createStatement();
-
- // This prints the backend's version
- System.out.println("Connected to " + dbmd.getDatabaseProductName() + " " + dbmd.getDatabaseProductVersion());
-
- init();
-
- System.out.println();
-
- // Now the tests
- if (doTest("Test DatabaseMetaData"))
- doDatabaseMetaData();
-
- if (doTest("Test ResultSetMetaData"))
- doResultSetMetaData();
-
- System.out.println("\nNow closing the connection");
- st.close();
- db.close();
-
- cleanup();
- }
-
- /*
- * This asks if the user requires to run a test.
- */
- public boolean doTest(String s)
- {
- System.out.println();
- System.out.print(s);
- System.out.print(" Perform test? Y or N:");
- System.out.flush();
- char c = ' ';
- try
- {
- while (!(c == 'n' || c == 'y' || c == 'N' || c == 'Y'))
- {
- c = (char)System.in.read();
- }
- }
- catch (IOException ioe)
- {
- return false;
- }
-
- return c == 'y' || c == 'Y';
- }
-
- /*
- * This displays a result set.
- * Note: it closes the result once complete.
- */
- public void displayResult(ResultSet rs) throws SQLException
- {
- ResultSetMetaData rsmd = rs.getMetaData();
- int count = 0;
-
- // Print the result column names
- int cols = rsmd.getColumnCount();
- for (int i = 1;i <= cols;i++)
- System.out.print(rsmd.getColumnLabel(i) + (i < cols ? "\t" : "\n"));
-
- // now the results
- while (rs.next())
- {
- count++;
- for (int i = 1;i <= cols;i++)
- {
- Object o = rs.getObject(i);
- if (rs.wasNull())
- System.out.print("{null}" + (i < cols ? "\t" : "\n"));
- else
- System.out.print(o.toString() + (i < cols ? "\t" : "\n"));
- }
- }
-
- System.out.println("Result returned " + count + " rows.");
-
- // finally close the result set
- rs.close();
- }
-
- /*
- * This process / commands (for now just /d)
- */
- public void processSlashCommand(String line) throws SQLException
- {
- if (line.startsWith("\\d"))
- {
- if (line.startsWith("\\d "))
- {
- // Display details about a table
- String table = line.substring(3);
- displayResult(dbmd.getColumns(null, null, table, "%"));
- }
- else
- {
- String types[] = null;
- if (line.equals("\\d"))
- types = allUserTables;
- else if (line.equals("\\di"))
- types = usrIndices;
- else if (line.equals("\\dt"))
- types = usrTables;
- else if (line.equals("\\ds"))
- types = usrSequences;
- else if (line.equals("\\dS"))
- types = sysTables;
- else
- throw new SQLException("Unsupported \\d command: " + line);
-
- // Display details about all system tables
- //
- // Note: the first two arguments are ignored. To keep to the spec,
- // you must put null here
- //
- displayResult(dbmd.getTables(null, null, "%", types));
- }
- }
- else
- throw new SQLException("Unsupported \\ command: " + line);
- }
-
- private static final String allUserTables[] = {"TABLE", "INDEX", "SEQUENCE"};
- private static final String usrIndices[] = {"INDEX"};
- private static final String usrTables[] = {"TABLE"};
- private static final String usrSequences[] = {"SEQUENCE"};
- private static final String sysTables[] = {"SYSTEM TABLE", "SYSTEM INDEX"};
-
- /*
- * Display some instructions on how to run the example
- */
- public static void instructions()
- {
- System.out.println("\nThis is not really an example, but is used to test the various methods in\nthe DatabaseMetaData and ResultSetMetaData classes.\n");
- System.out.println("Useage:\n java example.metadata jdbc:postgresql:database user password [debug]\n\nThe debug field can be anything. It's presence will enable DriverManager's\ndebug trace. Unless you want to see screens of debug items, don't put anything in\nhere.");
- System.exit(1);
- }
-
- /*
- * This little lot starts the test
- */
- public static void main(String args[])
- {
- System.out.println("PostgreSQL metdata tester v6.4 rev 1\n");
-
- if (args.length < 3)
- instructions();
-
- // This line outputs debug information to stderr. To enable this, simply
- // add an extra parameter to the command line
- if (args.length > 3)
- DriverManager.setLogStream(System.err);
-
- // Now run the tests
- try
- {
- metadata test = new metadata(args);
- }
- catch (Exception ex)
- {
- System.err.println("Exception caught.\n" + ex);
- ex.printStackTrace();
- }
- }
-}
diff --git a/src/interfaces/jdbc/example/psql.java b/src/interfaces/jdbc/example/psql.java
deleted file mode 100644
index 283739acd72..00000000000
--- a/src/interfaces/jdbc/example/psql.java
+++ /dev/null
@@ -1,234 +0,0 @@
-package example;
-
-import java.io.*;
-import java.sql.*;
-
-/*
- * This example application demonstrates some of the drivers other features
- * by implementing a simple psql replacement in Java.
- *
- */
-
-public class psql
-{
- Connection db; // The connection to the database
- Statement st; // Our statement to run queries with
- DatabaseMetaData dbmd; // This defines the structure of the database
- boolean done = false; // Added by CWJ to permit \q command
-
- public psql(String args[]) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
- {
- String url = args[0];
- String usr = args[1];
- String pwd = args[2];
-
- // Load the driver
- Class.forName("org.postgresql.Driver");
-
- // Connect to database
- System.out.println("Connecting to Database URL = " + url);
- db = DriverManager.getConnection(url, usr, pwd);
-
- dbmd = db.getMetaData();
- st = db.createStatement();
-
- // This prints the backend's version
- System.out.println("Connected to " + dbmd.getDatabaseProductName() + " " + dbmd.getDatabaseProductVersion());
-
- System.out.println();
-
- // This provides us the means of reading from stdin
- StreamTokenizer input = new StreamTokenizer(new InputStreamReader(System.in));
- input.resetSyntax();
- input.slashSlashComments(true); // allow // as a comment delimiter
- input.eolIsSignificant(false); // treat eol's as spaces
- input.wordChars(32, 126);
- input.whitespaceChars(59, 59);
- // input.quoteChar(39); *** CWJ: messes up literals in query string ***
-
- // Now the main loop.
- int tt = 0, lineno = 1;
- while (tt != StreamTokenizer.TT_EOF && ! done)
- {
- System.out.print("[" + lineno + "] ");
- System.out.flush();
-
- // Here, we trap SQLException so they don't terminate the application
- try
- {
- if ((tt = input.nextToken()) == StreamTokenizer.TT_WORD)
- {
- processLine(input.sval);
- lineno++;
- }
- }
- catch (SQLException ex)
- {
- System.out.println(ex.getMessage());
- }
- }
-
- System.out.println("Now closing the connection");
- st.close();
- db.close();
- }
-
- /*
- * This processes a statement
- */
- public void processLine(String line) throws SQLException
- {
- if (line.startsWith("\\"))
- {
- processSlashCommand(line);
- return ;
- }
-
- boolean type = st.execute(line);
- boolean loop = true;
- while (loop)
- {
- if (type)
- {
- // A ResultSet was returned
- ResultSet rs = st.getResultSet();
- displayResult(rs);
- }
- else
- {
- int count = st.getUpdateCount();
-
- if (count == -1)
- {
- // This indicates nothing left
- loop = false;
- }
- else
- {
- // An update count was returned
- System.out.println("Updated " + st.getUpdateCount() + " rows");
- }
- }
-
- if (loop)
- type = st.getMoreResults();
- }
- }
-
- /*
- * This displays a result set.
- * Note: it closes the result once complete.
- */
- public void displayResult(ResultSet rs) throws SQLException
- {
- ResultSetMetaData rsmd = rs.getMetaData();
-
- // Print the result column names
- int cols = rsmd.getColumnCount();
- for (int i = 1;i <= cols;i++)
- System.out.print(rsmd.getColumnLabel(i) + (i < cols ? "\t" : "\n"));
-
- // now the results
- while (rs.next())
- {
- for (int i = 1;i <= cols;i++)
- {
- Object o = rs.getObject(i);
- if (rs.wasNull())
- System.out.print("{null}" + (i < cols ? "\t" : "\n"));
- else
- System.out.print(o.toString() + (i < cols ? "\t" : "\n"));
- }
- }
-
- // finally close the result set
- rs.close();
- }
-
- /*
- * This process / commands (for now just /d)
- */
- public void processSlashCommand(String line) throws SQLException
- {
- if (line.startsWith("\\d"))
- {
-
- if (line.startsWith("\\d "))
- {
- // Display details about a table
- String table = line.substring(3);
- displayResult(dbmd.getColumns(null, null, table, "%"));
- }
- else
- {
- String types[] = null;
- if (line.equals("\\d"))
- types = allUserTables;
- else if (line.equals("\\di"))
- types = usrIndices;
- else if (line.equals("\\dt"))
- types = usrTables;
- else if (line.equals("\\ds"))
- types = usrSequences;
- else if (line.equals("\\dS"))
- types = sysTables;
- else
- throw new SQLException("Unsupported \\d command: " + line);
-
- // Display details about all system tables
- //
- // Note: the first two arguments are ignored. To keep to the spec,
- // you must put null here
- //
- displayResult(dbmd.getTables(null, null, "%", types));
- }
- }
- else if (line.equals("\\q")) // Added by CWJ to permit \q command
- done = true;
- else
- throw new SQLException("Unsupported \\ command: " + line);
- }
-
- private static final String allUserTables[] = {"TABLE", "INDEX", "SEQUENCE"};
- private static final String usrIndices[] = {"INDEX"};
- private static final String usrTables[] = {"TABLE"};
- private static final String usrSequences[] = {"SEQUENCE"};
- private static final String sysTables[] = {"SYSTEM TABLE", "SYSTEM INDEX"};
-
- /*
- * Display some instructions on how to run the example
- */
- public static void instructions()
- {
- System.out.println("\nThis example shows how some of the other JDBC features work within the\ndriver. It does this by implementing a very simple psql equivalent in java.\nNot everything that psql does is implemented.\n");
- System.out.println("Useage:\n java example.psql jdbc:postgresql:database user password [debug]\n\nThe debug field can be anything. It's presence will enable DriverManager's\ndebug trace. Unless you want to see screens of items, don't put anything in\nhere.");
- System.exit(1);
- }
-
- /*
- * This little lot starts the test
- */
- public static void main(String args[])
- {
- System.out.println("PostgreSQL psql example v6.3 rev 1\n");
-
- if (args.length < 3)
- instructions();
-
- // This line outputs debug information to stderr. To enable this, simply
- // add an extra parameter to the command line
- if (args.length > 3)
- DriverManager.setLogStream(System.err);
-
- // Now run the tests
- try
- {
- psql test = new psql(args);
- }
- catch (Exception ex)
- {
- System.err.println("Exception caught.\n" + ex);
- ex.printStackTrace();
- }
- }
-}
diff --git a/src/interfaces/jdbc/example/threadsafe.java b/src/interfaces/jdbc/example/threadsafe.java
deleted file mode 100644
index cb6c0d03f2f..00000000000
--- a/src/interfaces/jdbc/example/threadsafe.java
+++ /dev/null
@@ -1,402 +0,0 @@
-package example;
-
-import java.io.*;
-import java.sql.*;
-
-// rare in user code, but we use the LargeObject API in this test
-import org.postgresql.largeobject.*;
-
-/*
- * This example tests the thread safety of the driver.
- *
- * It does this by performing several queries, in different threads. Each
- * thread has it's own Statement object, which is (in my understanding of the
- * jdbc specification) the minimum requirement.
- *
- */
-
-public class threadsafe
-{
- Connection db; // The connection to the database
- Statement st; // Our statement to run queries with
-
- public threadsafe(String args[]) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
- {
- String url = args[0];
- String usr = args[1];
- String pwd = args[2];
-
- // Load the driver
- Class.forName("org.postgresql.Driver");
-
- // Connect to database
- System.out.println("Connecting to Database URL = " + url);
- db = DriverManager.getConnection(url, usr, pwd);
-
- System.out.println("Connected...Now creating a statement");
- st = db.createStatement();
-
- // Clean up the database (in case we failed earlier) then initialise
- cleanup();
-
- // Because we use LargeObjects, we must use Transactions
- db.setAutoCommit(false);
-
- // Now run tests using JDBC methods, then LargeObjects
- doexample();
-
- // Clean up the database
- cleanup();
-
- // Finally close the database
- System.out.println("Now closing the connection");
- st.close();
- db.close();
- }
-
- /*
- * This drops the table (if it existed). No errors are reported.
- */
- public void cleanup()
- {
- try
- {
- st.executeUpdate("drop table basic1");
- }
- catch (Exception ex)
- {
- // We ignore any errors here
- }
-
- try
- {
- st.executeUpdate("drop table basic2");
- }
- catch (Exception ex)
- {
- // We ignore any errors here
- }
- }
-
- /*
- * This performs the example
- */
- public void doexample() throws SQLException
- {
- System.out.println("\nThis test runs three Threads. Two simply insert data into a table, then\nthey perform a query. While they are running, a third thread is running,\nand it load data into, then reads from a Large Object.\n\nIf alls well, this should run without any errors. If so, we are Thread Safe.\nWhy test JDBC & LargeObject's? Because both will run over the network\nconnection, and if locking on the stream isn't done correctly, the backend\nwill get pretty confused!\n");
-
- thread3 thread3 = null;
-
- try
- {
-
- // create the two threads
- Thread thread0 = Thread.currentThread();
- Thread thread1 = new thread1(db);
- Thread thread2 = new thread2(db);
- thread3 = new thread3(db);
-
- // now run, and wait for them
- thread1.start();
- thread2.start();
- thread3.start();
-
- // ok, I know this is bad, but it does the trick here as our main thread
- // will yield as long as either of the children are still running
- System.out.println("Waiting for threads to run");
- while (thread1.isAlive() || thread2.isAlive() || thread3.isAlive())
- Thread.yield();
- }
- finally
- {
- // clean up after thread3 (the finally ensures this is run even
- // if an exception is thrown inside the try { } construct)
- if (thread3 != null)
- thread3.cleanup();
- }
-
- System.out.println("No Exceptions have been thrown. This is a good omen, as it means that we are\npretty much thread safe as we can get.");
- }
-
- // This is the first thread. It's the same as the basic test
- class thread1 extends Thread
- {
- Connection c;
- Statement st;
-
- public thread1(Connection c) throws SQLException
- {
- this.c = c;
- st = c.createStatement();
- }
-
- public void run()
- {
- try
- {
- System.out.println("Thread 1 running...");
-
- // First we need a table to store data in
- st.executeUpdate("create table basic1 (a int2, b int2)");
-
- // Now insert some data, using the Statement
- st.executeUpdate("insert into basic1 values (1,1)");
- st.executeUpdate("insert into basic1 values (2,1)");
- st.executeUpdate("insert into basic1 values (3,1)");
-
- // For large inserts, a PreparedStatement is more efficient, because it
- // supports the idea of precompiling the SQL statement, and to store
- // directly, a Java object into any column. PostgreSQL doesnt support
- // precompiling, but does support setting a column to the value of a
- // Java object (like Date, String, etc).
- //
- // Also, this is the only way of writing dates in a datestyle independent
- // manner. (DateStyles are PostgreSQL's way of handling different methods
- // of representing dates in the Date data type.)
- PreparedStatement ps = db.prepareStatement("insert into basic1 values (?,?)");
- for (int i = 2;i < 2000;i++)
- {
- ps.setInt(1, 4); // "column a" = 5
- ps.setInt(2, i); // "column b" = i
- ps.executeUpdate(); // executeUpdate because insert returns no data
- // c.commit();
- if ((i % 50) == 0)
- DriverManager.println("Thread 1 done " + i + " inserts");
- }
- ps.close(); // Always close when we are done with it
-
- // Finally perform a query on the table
- DriverManager.println("Thread 1 performing a query");
- ResultSet rs = st.executeQuery("select a, b from basic1");
- int cnt = 0;
- if (rs != null)
- {
- // Now we run through the result set, printing out the result.
- // Note, we must call .next() before attempting to read any results
- while (rs.next())
- {
- int a = rs.getInt("a"); // This shows how to get the value by name
- int b = rs.getInt(2); // This shows how to get the value by column
- //System.out.println(" a="+a+" b="+b);
- cnt++;
- }
- rs.close(); // again, you must close the result when done
- }
- DriverManager.println("Thread 1 read " + cnt + " rows");
-
- // The last thing to do is to drop the table. This is done in the
- // cleanup() method.
- System.out.println("Thread 1 finished");
- }
- catch (SQLException se)
- {
- System.err.println("Thread 1: " + se.toString());
- se.printStackTrace();
- System.exit(1);
- }
- }
- }
-
- // This is the second thread. It's the similar to the basic test, and thread1
- // except it works on another table.
- class thread2 extends Thread
- {
- Connection c;
- Statement st;
-
- public thread2(Connection c) throws SQLException
- {
- this.c = c;
- st = c.createStatement();
- }
-
- public void run()
- {
- try
- {
- System.out.println("Thread 2 running...");
-
- // First we need a table to store data in
- st.executeUpdate("create table basic2 (a int2, b int2)");
-
- // For large inserts, a PreparedStatement is more efficient, because it
- // supports the idea of precompiling the SQL statement, and to store
- // directly, a Java object into any column. PostgreSQL doesnt support
- // precompiling, but does support setting a column to the value of a
- // Java object (like Date, String, etc).
- //
- // Also, this is the only way of writing dates in a datestyle independent
- // manner. (DateStyles are PostgreSQL's way of handling different methods
- // of representing dates in the Date data type.)
- PreparedStatement ps = db.prepareStatement("insert into basic2 values (?,?)");
- for (int i = 2;i < 2000;i++)
- {
- ps.setInt(1, 4); // "column a" = 5
- ps.setInt(2, i); // "column b" = i
- ps.executeUpdate(); // executeUpdate because insert returns no data
- // c.commit();
- if ((i % 50) == 0)
- DriverManager.println("Thread 2 done " + i + " inserts");
- }
- ps.close(); // Always close when we are done with it
-
- // Finally perform a query on the table
- DriverManager.println("Thread 2 performing a query");
- ResultSet rs = st.executeQuery("select * from basic2 where b>1");
- int cnt = 0;
- if (rs != null)
- {
- // First find out the column numbers.
- //
- // It's best to do this here, as calling the methods with the column
- // numbers actually performs this call each time they are called. This
- // really speeds things up on large queries.
- //
- int col_a = rs.findColumn("a");
- int col_b = rs.findColumn("b");
-
- // Now we run through the result set, printing out the result.
- // Again, we must call .next() before attempting to read any results
- while (rs.next())
- {
- int a = rs.getInt(col_a); // This shows how to get the value by name
- int b = rs.getInt(col_b); // This shows how to get the value by column
- //System.out.println(" a="+a+" b="+b);
- cnt++;
- }
- rs.close(); // again, you must close the result when done
- }
- DriverManager.println("Thread 2 read " + cnt + " rows");
-
- // The last thing to do is to drop the table. This is done in the
- // cleanup() method.
- System.out.println("Thread 2 finished");
- }
- catch (SQLException se)
- {
- System.err.println("Thread 2: " + se.toString());
- se.printStackTrace();
- System.exit(1);
- }
- }
- }
-
- // This is the third thread. It loads, then reads from a LargeObject, using
- // our LargeObject api.
- //
- // The purpose of this is to test that FastPath will work in between normal
- // JDBC queries.
- class thread3 extends Thread
- {
- Connection c;
- Statement st;
- LargeObjectManager lom;
- LargeObject lo;
- int oid;
-
- public thread3(Connection c) throws SQLException
- {
- this.c = c;
- //st = c.createStatement();
-
- // create a blob
- lom = ((org.postgresql.PGConnection)c).getLargeObjectAPI();
- oid = lom.create();
- System.out.println("Thread 3 has created a blob of oid " + oid);
- }
-
- public void run()
- {
- try
- {
- System.out.println("Thread 3 running...");
-
- DriverManager.println("Thread 3: Loading data into blob " + oid);
- lo = lom.open(oid);
- FileInputStream fis = new FileInputStream("example/threadsafe.java");
- // keep the buffer size small, to allow the other thread a chance
- byte buf[] = new byte[128];
- int rc, bc = 1, bs = 0;
- while ((rc = fis.read(buf)) > 0)
- {
- DriverManager.println("Thread 3 read block " + bc + " " + bs + " bytes");
- lo.write(buf, 0, rc);
- bc++;
- bs += rc;
- }
- lo.close();
- fis.close();
-
- DriverManager.println("Thread 3: Reading blob " + oid);
- lo = lom.open(oid);
- bc = 0;
- while (buf.length > 0)
- {
- buf = lo.read(buf.length);
- if (buf.length > 0)
- {
- String s = new String(buf);
- bc++;
- DriverManager.println("Thread 3 block " + bc);
- DriverManager.println("Block " + bc + " got " + s);
- }
- }
- lo.close();
-
- System.out.println("Thread 3 finished");
- }
- catch (Exception se)
- {
- System.err.println("Thread 3: " + se.toString());
- se.printStackTrace();
- System.exit(1);
- }
- }
-
- public void cleanup() throws SQLException
- {
- if (lom != null && oid != 0)
- {
- System.out.println("Thread 3: Removing blob oid=" + oid);
- lom.delete(oid);
- }
- }
- }
-
- /*
- * Display some instructions on how to run the example
- */
- public static void instructions()
- {
- System.out.println("\nThis tests the thread safety of the driver.\n\nThis is done in two parts, the first with standard JDBC calls, and the\nsecond mixing FastPath and LargeObject calls with queries.\n");
- System.out.println("Useage:\n java example.threadsafe jdbc:postgresql:database user password [debug]\n\nThe debug field can be anything. It's presence will enable DriverManager's\ndebug trace. Unless you want to see screens of items, don't put anything in\nhere.");
- System.exit(1);
- }
-
- /*
- * This little lot starts the test
- */
- public static void main(String args[])
- {
- System.out.println("PostgreSQL Thread Safety test v6.4 rev 1\n");
-
- if (args.length < 3)
- instructions();
-
- // This line outputs debug information to stderr. To enable this, simply
- // add an extra parameter to the command line
- if (args.length > 3)
- DriverManager.setLogStream(System.err);
-
- // Now run the tests
- try
- {
- threadsafe test = new threadsafe(args);
- }
- catch (Exception ex)
- {
- System.err.println("Exception caught.\n" + ex);
- ex.printStackTrace();
- }
- }
-}